title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
FileField - Django Models - GeeksforGeeks
12 Feb, 2020 FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput. Syntax field_name = models.FileField(upload_to=None, max_length=254, **options) FileField has an optional arguments: FileField.upload_to This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. If you specify a string value, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example: class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT / uploads upload = models.FileField(upload_to ='uploads/') # or... # file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30 upload = models.FileField(upload_to ='uploads/% Y/% m/% d/') If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. If you are using different storage, check that storage’s documentation to see how it handles upload_to. upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are: For example: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to = user_directory_path) Illustration of FileField 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. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.FileField() Add the geeks app to INSTALLED_APPS # 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 # 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.FileField()), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field FileField is created when you run migrations on the project. It is a field to store any kind of file in the database. FileField is used for storing files into the database. One can any type of file in FileField. Let’s try storing an image in the model created above. To start creating instances of model, create an admin account by using the following command.Python manage.py createsuperuser Python manage.py createsuperuser Enter a username, email and a secure password. Then in your browser enter the following URL.http://localhost:8000/admin/ http://localhost:8000/admin/ Go to add in front of Geeks Models. Choose the file you want to upload and click on 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 FileField will enable it to store empty values for that table in relational database.Here are the field options and attributes that a FileField can use. NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24362, "s": 24334, "text": "\n12 Feb, 2020" }, { "code": null, "e": 24599, "s": 24362, "text": "FileField is a file-upload field. Before uploading files, one needs to specify a lot of settings so that file is securely saved and can be retrieved in a convenient manner. The default form widget for this field is a ClearableFileInput." }, { "code": null, "e": 24606, "s": 24599, "text": "Syntax" }, { "code": null, "e": 24679, "s": 24606, "text": "field_name = models.FileField(upload_to=None, max_length=254, **options)" }, { "code": null, "e": 24716, "s": 24679, "text": "FileField has an optional arguments:" }, { "code": null, "e": 24736, "s": 24716, "text": "FileField.upload_to" }, { "code": null, "e": 25107, "s": 24736, "text": "This attribute provides a way of setting the upload directory and file name, and can be set in two ways. In both cases, the value is passed to the Storage.save() method. If you specify a string value, it may contain strftime() formatting, which will be replaced by the date/time of the file upload (so that uploaded files don’t fill up the given directory). For example:" }, { "code": "class MyModel(models.Model): # file will be uploaded to MEDIA_ROOT / uploads upload = models.FileField(upload_to ='uploads/') # or... # file will be saved to MEDIA_ROOT / uploads / 2015 / 01 / 30 upload = models.FileField(upload_to ='uploads/% Y/% m/% d/')", "e": 25383, "s": 25107, "text": null }, { "code": null, "e": 25675, "s": 25383, "text": "If you are using the default FileSystemStorage, the string value will be appended to your MEDIA_ROOT path to form the location on the local filesystem where uploaded files will be stored. If you are using different storage, check that storage’s documentation to see how it handles upload_to." }, { "code": null, "e": 25957, "s": 25675, "text": "upload_to may also be a callable, such as a function. This will be called to obtain the upload path, including the filename. This callable must accept two arguments and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments are:" }, { "code": null, "e": 25970, "s": 25957, "text": "For example:" }, { "code": "def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT / user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to = user_directory_path)", "e": 26233, "s": 25970, "text": null }, { "code": null, "e": 26343, "s": 26233, "text": "Illustration of FileField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 26430, "s": 26343, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 26481, "s": 26430, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 26514, "s": 26481, "text": "How to Create an App in Django ?" }, { "code": null, "e": 26573, "s": 26514, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.FileField()", "e": 26724, "s": 26573, "text": null }, { "code": null, "e": 26760, "s": 26724, "text": "Add the geeks app to INSTALLED_APPS" }, { "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": 26998, "s": 26760, "text": null }, { "code": null, "e": 27056, "s": 26998, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 27088, "s": 27056, "text": "Python manage.py makemigrations" }, { "code": null, "e": 27188, "s": 27088, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "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.FileField()), ], ), ]", "e": 27774, "s": 27188, "text": null }, { "code": null, "e": 27783, "s": 27774, "text": "Now run," }, { "code": null, "e": 27808, "s": 27783, "text": "Python manage.py migrate" }, { "code": null, "e": 27947, "s": 27808, "text": "Thus, an geeks_field FileField is created when you run migrations on the project. It is a field to store any kind of file in the database." }, { "code": null, "e": 28096, "s": 27947, "text": "FileField is used for storing files into the database. One can any type of file in FileField. Let’s try storing an image in the model created above." }, { "code": null, "e": 28222, "s": 28096, "text": "To start creating instances of model, create an admin account by using the following command.Python manage.py createsuperuser" }, { "code": null, "e": 28255, "s": 28222, "text": "Python manage.py createsuperuser" }, { "code": null, "e": 28376, "s": 28255, "text": "Enter a username, email and a secure password. Then in your browser enter the following URL.http://localhost:8000/admin/" }, { "code": null, "e": 28405, "s": 28376, "text": "http://localhost:8000/admin/" }, { "code": null, "e": 28441, "s": 28405, "text": "Go to add in front of Geeks Models." }, { "code": null, "e": 28574, "s": 28441, "text": "Choose the file you want to upload and click on save. Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 28919, "s": 28574, "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 FileField will enable it to store empty values for that table in relational database.Here are the field options and attributes that a FileField can use." }, { "code": null, "e": 28931, "s": 28919, "text": "NaveenArora" }, { "code": null, "e": 28945, "s": 28931, "text": "Django-models" }, { "code": null, "e": 28959, "s": 28945, "text": "Python Django" }, { "code": null, "e": 28966, "s": 28959, "text": "Python" }, { "code": null, "e": 29064, "s": 28966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29082, "s": 29064, "text": "Python Dictionary" }, { "code": null, "e": 29117, "s": 29082, "text": "Read a file line by line in Python" }, { "code": null, "e": 29139, "s": 29117, "text": "Enumerate() in Python" }, { "code": null, "e": 29171, "s": 29139, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29201, "s": 29171, "text": "Iterate over a list in Python" }, { "code": null, "e": 29243, "s": 29201, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29269, "s": 29243, "text": "Python String | replace()" }, { "code": null, "e": 29306, "s": 29269, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29349, "s": 29306, "text": "Python program to convert a list to string" } ]
MySQL - SHOW TABLE STATUS Statement
The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column. The SHOW TABLE STATUS Statement of MySQL provides information about the non-TEMPORARY tables in a database. Following is the syntax of the SHOW TABLES Statement − SHOW TABLE STATUS [{FROM | IN} db_name] [LIKE 'pattern' | WHERE expr] Assume we have created 4 tables in the current database using the CREATE statement as shown below − mysql> CREATE TABLE TestTable1(value VARCHAR(10)); Query OK, 0 rows affected (2.88 sec) mysql> CREATE TABLE TestTable2(value VARCHAR(10)); Query OK, 0 rows affected (0.74 sec) mysql> CREATE TABLE TestTable3(value VARCHAR(10)); Query OK, 0 rows affected (0.81 sec) mysql> CREATE TABLE TestTable4(value VARCHAR(10)); Query OK, 0 rows affected (1.26 sec) Following statement displays the information about the non-temporary trebles in the current database − mysql> SHOW TABLE STATUS; +------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | testtable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:03 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | testtable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:08 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | testtable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:15 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | testtable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:21 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | +------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ 4 rows in set (0.22 sec) You can retrieve information about the non-TEMPORARY tables from a specific database using the FROM clause. Assume we have created a database named demo using the CREATE DATABASE statement − mysql> CREATE DATABASE demo; Query OK, 1 row affected (0.18 sec) Now, let us create tables in it, using the CREATE TABLE statement − mysql> CREATE TABLE demo.myTable1 (data INT); Query OK, 0 rows affected (0.55 sec) mysql> CREATE TABLE demo.myTable2 (data INT); Query OK, 0 rows affected (1.54 sec) mysql> CREATE TABLE demo.myTable3 (data INT); Query OK, 0 rows affected (1.18 sec) mysql> CREATE TABLE demo.myTable4 (data INT); Query OK, 0 rows affected (0.86 sec) Following query lists out the information about tables in the database "demo" − mysql> SHOW TABLE STATUS FROM demo; +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | mytable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:47 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:00 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:12 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ 4 rows in set (0.20 sec) You can also use the IN clause instead of FROM as − mysql> SHOW TABLE STATUS IN demo; +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | mytable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:47 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:00 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:12 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ 4 rows in set (0.00 sec) Using the LIKE clause, you can specify a pattern to retrieve information about specific tables. Following query retrieves description about the tables with name starting with "my". mysql> use demo; Database changed mysql> SHOW TABLE STATUS LIKE 'my%'; +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ | mytable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:47 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:00 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | | mytable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:12 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | +----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+ 4 rows in set (0.00 sec) 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2504, "s": 2333, "text": "The CREATE TABLE statement is used to create tables in MYSQL database. Here, you need to specify the name of the table and, definition (name and datatype) of each column." }, { "code": null, "e": 2612, "s": 2504, "text": "The SHOW TABLE STATUS Statement of MySQL provides information about the non-TEMPORARY tables in a database." }, { "code": null, "e": 2667, "s": 2612, "text": "Following is the syntax of the SHOW TABLES Statement −" }, { "code": null, "e": 2744, "s": 2667, "text": "SHOW TABLE STATUS\n [{FROM | IN} db_name]\n [LIKE 'pattern' | WHERE expr]\n" }, { "code": null, "e": 2844, "s": 2744, "text": "Assume we have created 4 tables in the current database using the CREATE statement as shown below −" }, { "code": null, "e": 3199, "s": 2844, "text": "mysql> CREATE TABLE TestTable1(value VARCHAR(10));\nQuery OK, 0 rows affected (2.88 sec)\n\nmysql> CREATE TABLE TestTable2(value VARCHAR(10));\nQuery OK, 0 rows affected (0.74 sec)\n\nmysql> CREATE TABLE TestTable3(value VARCHAR(10));\nQuery OK, 0 rows affected (0.81 sec)\n\nmysql> CREATE TABLE TestTable4(value VARCHAR(10));\nQuery OK, 0 rows affected (1.26 sec)" }, { "code": null, "e": 3302, "s": 3199, "text": "Following statement displays the information about the non-temporary trebles in the current database −" }, { "code": null, "e": 5393, "s": 3302, "text": "mysql> SHOW TABLE STATUS;\n+------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| testtable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:03 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| testtable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:08 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| testtable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:15 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| testtable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:04:21 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n+------------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n4 rows in set (0.22 sec)" }, { "code": null, "e": 5501, "s": 5393, "text": "You can retrieve information about the non-TEMPORARY tables from a specific database using the FROM clause." }, { "code": null, "e": 5584, "s": 5501, "text": "Assume we have created a database named demo using the CREATE DATABASE statement −" }, { "code": null, "e": 5649, "s": 5584, "text": "mysql> CREATE DATABASE demo;\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 5717, "s": 5649, "text": "Now, let us create tables in it, using the CREATE TABLE statement −" }, { "code": null, "e": 6052, "s": 5717, "text": "mysql> CREATE TABLE demo.myTable1 (data INT);\nQuery OK, 0 rows affected (0.55 sec)\n\nmysql> CREATE TABLE demo.myTable2 (data INT);\nQuery OK, 0 rows affected (1.54 sec)\n\nmysql> CREATE TABLE demo.myTable3 (data INT);\nQuery OK, 0 rows affected (1.18 sec)\n\nmysql> CREATE TABLE demo.myTable4 (data INT);\nQuery OK, 0 rows affected (0.86 sec)" }, { "code": null, "e": 6132, "s": 6052, "text": "Following query lists out the information about tables in the database \"demo\" −" }, { "code": null, "e": 8218, "s": 6132, "text": "mysql> SHOW TABLE STATUS FROM demo;\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| mytable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | | \n| mytable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:47 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:00 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:12 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n4 rows in set (0.20 sec)" }, { "code": null, "e": 8270, "s": 8218, "text": "You can also use the IN clause instead of FROM as −" }, { "code": null, "e": 10353, "s": 8270, "text": "mysql> SHOW TABLE STATUS IN demo;\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| mytable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:47 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:00 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:12 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 10534, "s": 10353, "text": "Using the LIKE clause, you can specify a pattern to retrieve information about specific tables. Following query retrieves description about the tables with name starting with \"my\"." }, { "code": null, "e": 12654, "s": 10534, "text": "mysql> use demo;\nDatabase changed\nmysql> SHOW TABLE STATUS LIKE 'my%';\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| Name | Engine | Version | Row_format | Rows | Avg_row_length | Data_length | Max_data_length | Index_length | Data_free | Auto_increment | Create_time | Update_time | Check_time | Collation | Checksum | Create_options | Comment |\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n| mytable1 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:34 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable2 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:09:47 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable3 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:00 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n| mytable4 | InnoDB | 10 | Dynamic | 0 | 0 | 16384 | 0 | 0 | 0 | NULL | 2021-05-13 20:10:12 | NULL | NULL | utf8mb4_0900_ai_ci | NULL | | |\n+----------+--------+---------+------------+------+----------------+-------------+-----------------+--------------+-----------+----------------+---------------------+-------------+------------+--------------------+----------+----------------+---------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 12687, "s": 12654, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 12715, "s": 12687, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12750, "s": 12715, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 12767, "s": 12750, "text": " Frahaan Hussain" }, { "code": null, "e": 12801, "s": 12767, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 12836, "s": 12801, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 12870, "s": 12836, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 12898, "s": 12870, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 12931, "s": 12898, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 12951, "s": 12931, "text": " Harshit Srivastava" }, { "code": null, "e": 12984, "s": 12951, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 13002, "s": 12984, "text": " Trevoir Williams" }, { "code": null, "e": 13009, "s": 13002, "text": " Print" }, { "code": null, "e": 13020, "s": 13009, "text": " Add Notes" } ]
How to add two numbers in console using Node.js ? - GeeksforGeeks
26 Oct, 2021 In this article, we will see how to add two numbers in the console using NodeJS. For this purpose, we need to know about a node package called prompt. It helps to take user input from the console. We would use its method prompt.get() to take user input. Create NodeJS Application: Initialize the NodeJS application using the following command: npm init Module Installation: Install the prompt module using the following command. npm install prompt Implementation: Create an app.js file and write down the following code in it. app.js // Require would make the prompt// package available to useconst prompt = require("prompt"); // An utility function to add// two numbersfunction add() { // Start the prompt prompt.start(); // Get two numbers/properties // from user num1 and num2 prompt.get(["num1", "num2"], function (err, res) { // To handle any error if occurred if (err) { console.log(err); } else { // By default get methods takes // input in string So parseFloat // is used to convert String // into Float var sum = parseFloat(res.num1) + parseFloat(res.num2); // Print the sum console.log("Sum of " + res.num1 + " and " + res.num2 + " is " + sum); } });} // Calling add functionadd(); Step to run the application: Run the app.js file using the following command. node app.js Output: Now enter the user input and view output in the console. output So this is how you can add two numbers in the console using nodeJs. Prompts help us to take input from users. It also supports validation and defaults over the input. saurabh1990aror NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method Difference between npm i and npm ci in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25028, "s": 25000, "text": "\n26 Oct, 2021" }, { "code": null, "e": 25282, "s": 25028, "text": "In this article, we will see how to add two numbers in the console using NodeJS. For this purpose, we need to know about a node package called prompt. It helps to take user input from the console. We would use its method prompt.get() to take user input." }, { "code": null, "e": 25372, "s": 25282, "text": "Create NodeJS Application: Initialize the NodeJS application using the following command:" }, { "code": null, "e": 25381, "s": 25372, "text": "npm init" }, { "code": null, "e": 25457, "s": 25381, "text": "Module Installation: Install the prompt module using the following command." }, { "code": null, "e": 25476, "s": 25457, "text": "npm install prompt" }, { "code": null, "e": 25555, "s": 25476, "text": "Implementation: Create an app.js file and write down the following code in it." }, { "code": null, "e": 25564, "s": 25557, "text": "app.js" }, { "code": "// Require would make the prompt// package available to useconst prompt = require(\"prompt\"); // An utility function to add// two numbersfunction add() { // Start the prompt prompt.start(); // Get two numbers/properties // from user num1 and num2 prompt.get([\"num1\", \"num2\"], function (err, res) { // To handle any error if occurred if (err) { console.log(err); } else { // By default get methods takes // input in string So parseFloat // is used to convert String // into Float var sum = parseFloat(res.num1) + parseFloat(res.num2); // Print the sum console.log(\"Sum of \" + res.num1 + \" and \" + res.num2 + \" is \" + sum); } });} // Calling add functionadd();", "e": 26304, "s": 25564, "text": null }, { "code": null, "e": 26382, "s": 26304, "text": "Step to run the application: Run the app.js file using the following command." }, { "code": null, "e": 26394, "s": 26382, "text": "node app.js" }, { "code": null, "e": 26459, "s": 26394, "text": "Output: Now enter the user input and view output in the console." }, { "code": null, "e": 26466, "s": 26459, "text": "output" }, { "code": null, "e": 26633, "s": 26466, "text": "So this is how you can add two numbers in the console using nodeJs. Prompts help us to take input from users. It also supports validation and defaults over the input." }, { "code": null, "e": 26649, "s": 26633, "text": "saurabh1990aror" }, { "code": null, "e": 26666, "s": 26649, "text": "NodeJS-Questions" }, { "code": null, "e": 26673, "s": 26666, "text": "Picked" }, { "code": null, "e": 26681, "s": 26673, "text": "Node.js" }, { "code": null, "e": 26698, "s": 26681, "text": "Web Technologies" }, { "code": null, "e": 26796, "s": 26698, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26833, "s": 26796, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26865, "s": 26833, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 26896, "s": 26865, "text": "Express.js req.params Property" }, { "code": null, "e": 26923, "s": 26896, "text": "Mongoose Populate() Method" }, { "code": null, "e": 26970, "s": 26923, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 27012, "s": 26970, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27055, "s": 27012, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27105, "s": 27055, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27167, "s": 27105, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Java Program to Find the Most Repeated Word in a Text File - GeeksforGeeks
07 Feb, 2022 Map and Map.Entry interface will be used as the Map interface maps unique keys to values. A key is an object that is used to retrieve a value at a later date. The Map.Entry interface enables you to work with a map entry. Also, we will use the HashMap class to store items in “key/value” pairs and access them by an index of another type. Illustration: Suppose the content of the sample text file is as follows: Input: A text file containing sequence of arbitrary words “How to count the number of occurrence of each word? How to count number or each word in string. Calculating frequency of each word in a sentence in java.” Output: List of words that have the maximum occurrence in = 3 each = 3 of = 3 to = 3 Implementation: Sample file input image is as follows: Example Java // Java Program to Find the// Most Repeated Word in a Text File // Importing File classesimport java.io.File;import java.io.FileNotFoundException;// Importing Map and HashMap class from// java.util packageimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry;// Importing Scanner class to// take input from the userimport java.util.Scanner; // Class// To find maximum occurrencespublic class GFG { // Method 1 - getWords() // Reading out words from the file and // mapping key value pair corresponding to // each different word static void getWords(String fileName, Map<String, Integer> words) throws FileNotFoundException { // Creating a Scanner class object Scanner file = new Scanner(new File(fileName)); // Condition check using hasNext() method which // holds true till there is word being read from the // file. // As the end of file content,condition violates while (file.hasNext()) { // Reading word using next() method String word = file.next(); // Frequency count variable Integer count = words.get(word); // If the same word is repeating if (count != null) { // Incrementing corresponding count by unity // every time it repeats // while reading from the file count++; } else // If word never occurred after occurring // once, set count as unity count = 1; words.put(word, count); } // Close the file and free up the resources file.close(); } // Method 2 - getMaxOccurrence() // To get maximum occurred Word static int getMaxOccurrence(Map<String, Integer> words) { // Initially set maximum count as unity int max = 1; // Iterating over above Map using for-each loop for (Entry<String, Integer> word : words.entrySet()) { // Condition check // Update current max value with the value // exceeding unity in Map while traversing if (word.getValue() > max) { max = word.getValue(); } } // Return the maximum value from the Map return max; } // Method 3 // Main driver method public static void main(String[] args) throws FileNotFoundException { // Creating an object of type Map // Declaring object of String and Integer types Map<String, Integer> words = new HashMap<String, Integer>(); // Retrieving the path as parameter to Method1() // above to get the file to be read getWords("C:\\Users\\dell\\sample.txt", words); // Variable holding the maximum // repeated word count in a file int max = getMaxOccurrence(words); // Traversing using fo-each loop // Creating a set out of same elements // contained in a HashMap for (Entry<String, Integer> word : words.entrySet()) { // Comparing values using geValue() method if (word.getValue() == max) { // Print and display word-count pair System.out.println(word); } } } Output: gabaa406 akshaysingh98088 clintra kk9826225 kk773572498 Java-Files Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n07 Feb, 2022" }, { "code": null, "e": 23895, "s": 23557, "text": "Map and Map.Entry interface will be used as the Map interface maps unique keys to values. A key is an object that is used to retrieve a value at a later date. The Map.Entry interface enables you to work with a map entry. Also, we will use the HashMap class to store items in “key/value” pairs and access them by an index of another type." }, { "code": null, "e": 23909, "s": 23895, "text": "Illustration:" }, { "code": null, "e": 23968, "s": 23909, "text": "Suppose the content of the sample text file is as follows:" }, { "code": null, "e": 24027, "s": 23968, "text": "Input: A text file containing sequence of arbitrary words " }, { "code": null, "e": 24184, "s": 24027, "text": "“How to count the number of occurrence of each word? How to count number or each word in string. Calculating frequency of each word in a sentence in java.”" }, { "code": null, "e": 24239, "s": 24184, "text": "Output: List of words that have the maximum occurrence" }, { "code": null, "e": 24269, "s": 24239, "text": "in = 3\neach = 3\nof = 3\nto = 3" }, { "code": null, "e": 24324, "s": 24269, "text": "Implementation: Sample file input image is as follows:" }, { "code": null, "e": 24332, "s": 24324, "text": "Example" }, { "code": null, "e": 24337, "s": 24332, "text": "Java" }, { "code": "// Java Program to Find the// Most Repeated Word in a Text File // Importing File classesimport java.io.File;import java.io.FileNotFoundException;// Importing Map and HashMap class from// java.util packageimport java.util.HashMap;import java.util.Map;import java.util.Map.Entry;// Importing Scanner class to// take input from the userimport java.util.Scanner; // Class// To find maximum occurrencespublic class GFG { // Method 1 - getWords() // Reading out words from the file and // mapping key value pair corresponding to // each different word static void getWords(String fileName, Map<String, Integer> words) throws FileNotFoundException { // Creating a Scanner class object Scanner file = new Scanner(new File(fileName)); // Condition check using hasNext() method which // holds true till there is word being read from the // file. // As the end of file content,condition violates while (file.hasNext()) { // Reading word using next() method String word = file.next(); // Frequency count variable Integer count = words.get(word); // If the same word is repeating if (count != null) { // Incrementing corresponding count by unity // every time it repeats // while reading from the file count++; } else // If word never occurred after occurring // once, set count as unity count = 1; words.put(word, count); } // Close the file and free up the resources file.close(); } // Method 2 - getMaxOccurrence() // To get maximum occurred Word static int getMaxOccurrence(Map<String, Integer> words) { // Initially set maximum count as unity int max = 1; // Iterating over above Map using for-each loop for (Entry<String, Integer> word : words.entrySet()) { // Condition check // Update current max value with the value // exceeding unity in Map while traversing if (word.getValue() > max) { max = word.getValue(); } } // Return the maximum value from the Map return max; } // Method 3 // Main driver method public static void main(String[] args) throws FileNotFoundException { // Creating an object of type Map // Declaring object of String and Integer types Map<String, Integer> words = new HashMap<String, Integer>(); // Retrieving the path as parameter to Method1() // above to get the file to be read getWords(\"C:\\\\Users\\\\dell\\\\sample.txt\", words); // Variable holding the maximum // repeated word count in a file int max = getMaxOccurrence(words); // Traversing using fo-each loop // Creating a set out of same elements // contained in a HashMap for (Entry<String, Integer> word : words.entrySet()) { // Comparing values using geValue() method if (word.getValue() == max) { // Print and display word-count pair System.out.println(word); } } }", "e": 27673, "s": 24337, "text": null }, { "code": null, "e": 27681, "s": 27673, "text": "Output:" }, { "code": null, "e": 27690, "s": 27681, "text": "gabaa406" }, { "code": null, "e": 27707, "s": 27690, "text": "akshaysingh98088" }, { "code": null, "e": 27715, "s": 27707, "text": "clintra" }, { "code": null, "e": 27725, "s": 27715, "text": "kk9826225" }, { "code": null, "e": 27737, "s": 27725, "text": "kk773572498" }, { "code": null, "e": 27748, "s": 27737, "text": "Java-Files" }, { "code": null, "e": 27755, "s": 27748, "text": "Picked" }, { "code": null, "e": 27779, "s": 27755, "text": "Technical Scripter 2020" }, { "code": null, "e": 27784, "s": 27779, "text": "Java" }, { "code": null, "e": 27798, "s": 27784, "text": "Java Programs" }, { "code": null, "e": 27817, "s": 27798, "text": "Technical Scripter" }, { "code": null, "e": 27822, "s": 27817, "text": "Java" }, { "code": null, "e": 27920, "s": 27822, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27929, "s": 27920, "text": "Comments" }, { "code": null, "e": 27942, "s": 27929, "text": "Old Comments" }, { "code": null, "e": 27972, "s": 27942, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27987, "s": 27972, "text": "Stream In Java" }, { "code": null, "e": 28008, "s": 27987, "text": "Constructors in Java" }, { "code": null, "e": 28054, "s": 28008, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28073, "s": 28054, "text": "Exceptions in Java" }, { "code": null, "e": 28117, "s": 28073, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 28143, "s": 28117, "text": "Java Programming Examples" }, { "code": null, "e": 28177, "s": 28143, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 28224, "s": 28177, "text": "Implementing a Linked List in Java using Class" } ]
MySQL - Database Info
There are three types of information, which you would like to have from MySQL. Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement. Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement. Information about the tables and databases − This includes information pertaining to the structure of the tables and the databases. Information about the tables and databases − This includes information pertaining to the structure of the tables and the databases. Information about the MySQL server − This includes the status of the database server, version number, etc. Information about the MySQL server − This includes the status of the database server, version number, etc. It is very easy to get all this information at the MySQL prompt, but while using PERL or PHP APIs, we need to call various APIs explicitly to obtain all this information. Let is now see how to obtain this information. In DBI scripts, the affected row count is returned by the do( ) or by the execute( ) command, depending on how you execute the query. # Method 1 # execute $query using do( ) my $count = $dbh->do ($query); # report 0 rows if an error occurred printf "%d rows were affected\n", (defined ($count) ? $count : 0); # Method 2 # execute query using prepare( ) plus execute( ) my $sth = $dbh->prepare ($query); my $count = $sth->execute ( ); printf "%d rows were affected\n", (defined ($count) ? $count : 0); In PHP, invoke the mysql_affected_rows( ) function to find out how many rows a query changed. $result_id = mysql_query ($query, $conn_id); # report 0 rows if the query failed $count = ($result_id ? mysql_affected_rows ($conn_id) : 0); print ("$count rows were affected\n"); It is very easy to list down all the databases and the tables available with a database server. Your result may be null if you don't have the sufficient privileges. Apart from the method which is shown in the following code block, you can use SHOW TABLES or SHOW DATABASES queries to get the list of tables or databases either in PHP or in PERL. # Get all the tables available in current database. my @tables = $dbh->tables ( ); foreach $table (@tables ){ print "Table Name $table\n"; } Try the following example to get database info − Copy and paste the following example as mysql_example.php − <html> <head> <title>Getting MySQL Database Info</title> </head> <body> <?php $dbhost = 'localhost'; $dbuser = 'root'; $dbpass = 'root@123'; $dbname = 'TUTORIALS'; $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname); $tutorial_count = null; if($mysqli->connect_errno ) { printf("Connect failed: %s<br />", $mysqli->connect_error); exit(); } printf('Connected successfully.<br />'); if ($result = mysqli_query($mysqli, "SELECT DATABASE()")) { $row = mysqli_fetch_row($result); printf("Default database is %s<br />", $row[0]); mysqli_free_result($result); } $mysqli->close(); ?> </body> </html> Access the mysql_example.php deployed on apache web server and verify the output. Connected successfully. Default database is tutorials There are a few important commands in MySQL which can be executed either at the MySQL prompt or by using any script like PHP to get various important information about the database server. SELECT VERSION( ) Server version string SELECT DATABASE( ) Current database name (empty if none) SELECT USER( ) Current username SHOW STATUS Server status indicators SHOW VARIABLES Server configuration variables 31 Lectures 6 hours Eduonix Learning Solutions 84 Lectures 5.5 hours Frahaan Hussain 6 Lectures 3.5 hours DATAhill Solutions Srinivas Reddy 60 Lectures 10 hours Vijay Kumar Parvatha Reddy 10 Lectures 1 hours Harshit Srivastava 25 Lectures 4 hours Trevoir Williams Print Add Notes Bookmark this page
[ { "code": null, "e": 2412, "s": 2333, "text": "There are three types of information, which you would like to have from MySQL." }, { "code": null, "e": 2542, "s": 2412, "text": "Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement." }, { "code": null, "e": 2672, "s": 2542, "text": "Information about the result of queries − This includes the number of records affected by any SELECT, UPDATE or DELETE statement." }, { "code": null, "e": 2804, "s": 2672, "text": "Information about the tables and databases − This includes information pertaining to the structure of the tables and the databases." }, { "code": null, "e": 2936, "s": 2804, "text": "Information about the tables and databases − This includes information pertaining to the structure of the tables and the databases." }, { "code": null, "e": 3043, "s": 2936, "text": "Information about the MySQL server − This includes the status of the database server, version number, etc." }, { "code": null, "e": 3150, "s": 3043, "text": "Information about the MySQL server − This includes the status of the database server, version number, etc." }, { "code": null, "e": 3321, "s": 3150, "text": "It is very easy to get all this information at the MySQL prompt, but while using PERL or PHP APIs, we need to call various APIs explicitly to obtain all this information." }, { "code": null, "e": 3368, "s": 3321, "text": "Let is now see how to obtain this information." }, { "code": null, "e": 3502, "s": 3368, "text": "In DBI scripts, the affected row count is returned by the do( ) or by the execute( ) command, depending on how you execute the query." }, { "code": null, "e": 3870, "s": 3502, "text": "# Method 1\n# execute $query using do( )\nmy $count = $dbh->do ($query);\n# report 0 rows if an error occurred\nprintf \"%d rows were affected\\n\", (defined ($count) ? $count : 0);\n\n# Method 2\n# execute query using prepare( ) plus execute( )\nmy $sth = $dbh->prepare ($query);\nmy $count = $sth->execute ( );\nprintf \"%d rows were affected\\n\", (defined ($count) ? $count : 0);" }, { "code": null, "e": 3964, "s": 3870, "text": "In PHP, invoke the mysql_affected_rows( ) function to find out how many rows a query changed." }, { "code": null, "e": 4145, "s": 3964, "text": "$result_id = mysql_query ($query, $conn_id);\n# report 0 rows if the query failed\n$count = ($result_id ? mysql_affected_rows ($conn_id) : 0);\nprint (\"$count rows were affected\\n\");\n" }, { "code": null, "e": 4310, "s": 4145, "text": "It is very easy to list down all the databases and the tables available with a database server. Your result may be null if you don't have the sufficient privileges." }, { "code": null, "e": 4491, "s": 4310, "text": "Apart from the method which is shown in the following code block, you can use SHOW TABLES or SHOW DATABASES queries to get the list of tables or databases either in PHP or in PERL." }, { "code": null, "e": 4636, "s": 4491, "text": "# Get all the tables available in current database.\nmy @tables = $dbh->tables ( );\n\nforeach $table (@tables ){\n print \"Table Name $table\\n\";\n}" }, { "code": null, "e": 4685, "s": 4636, "text": "Try the following example to get database info −" }, { "code": null, "e": 4745, "s": 4685, "text": "Copy and paste the following example as mysql_example.php −" }, { "code": null, "e": 5549, "s": 4745, "text": "<html>\n <head>\n <title>Getting MySQL Database Info</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 $tutorial_count = null;\n\t\t \n if($mysqli->connect_errno ) {\n printf(\"Connect failed: %s<br />\", $mysqli->connect_error);\n exit();\n }\n printf('Connected successfully.<br />');\n\t\t \n if ($result = mysqli_query($mysqli, \"SELECT DATABASE()\")) {\n $row = mysqli_fetch_row($result);\n printf(\"Default database is %s<br />\", $row[0]);\n mysqli_free_result($result);\n }\n $mysqli->close();\n ?>\n </body>\n</html>" }, { "code": null, "e": 5631, "s": 5549, "text": "Access the mysql_example.php deployed on apache web server and verify the output." }, { "code": null, "e": 5686, "s": 5631, "text": "Connected successfully.\nDefault database is tutorials\n" }, { "code": null, "e": 5875, "s": 5686, "text": "There are a few important commands in MySQL which can be executed either at the MySQL prompt or by using any script like PHP to get various important information about the database server." }, { "code": null, "e": 5893, "s": 5875, "text": "SELECT VERSION( )" }, { "code": null, "e": 5915, "s": 5893, "text": "Server version string" }, { "code": null, "e": 5934, "s": 5915, "text": "SELECT DATABASE( )" }, { "code": null, "e": 5972, "s": 5934, "text": "Current database name (empty if none)" }, { "code": null, "e": 5987, "s": 5972, "text": "SELECT USER( )" }, { "code": null, "e": 6004, "s": 5987, "text": "Current username" }, { "code": null, "e": 6016, "s": 6004, "text": "SHOW STATUS" }, { "code": null, "e": 6041, "s": 6016, "text": "Server status indicators" }, { "code": null, "e": 6056, "s": 6041, "text": "SHOW VARIABLES" }, { "code": null, "e": 6087, "s": 6056, "text": "Server configuration variables" }, { "code": null, "e": 6120, "s": 6087, "text": "\n 31 Lectures \n 6 hours \n" }, { "code": null, "e": 6148, "s": 6120, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6183, "s": 6148, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6200, "s": 6183, "text": " Frahaan Hussain" }, { "code": null, "e": 6234, "s": 6200, "text": "\n 6 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6269, "s": 6234, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 6303, "s": 6269, "text": "\n 60 Lectures \n 10 hours \n" }, { "code": null, "e": 6331, "s": 6303, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 6364, "s": 6331, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6384, "s": 6364, "text": " Harshit Srivastava" }, { "code": null, "e": 6417, "s": 6384, "text": "\n 25 Lectures \n 4 hours \n" }, { "code": null, "e": 6435, "s": 6417, "text": " Trevoir Williams" }, { "code": null, "e": 6442, "s": 6435, "text": " Print" }, { "code": null, "e": 6453, "s": 6442, "text": " Add Notes" } ]
Neo4j - Return Clause
The RETURN clause is used return nodes, relationships, and properties in Neo4j. In this chapter, we are going to learn how to − Return nodes Return multiple nodes Return relationships Return properties Return all elements Return a variable with column alias You can return a node using the RETURN clause. Following is a syntax to return nodes using the RETURN clause. Create (node:label {properties}) RETURN node Before proceeding with the example, create 3 nodes and 2 relationships as shown below. Create (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"}) CREATE (Ind:Country {name: "India", result: "Winners"}) CREATE (CT2013:Tornament {name: "ICC Champions Trophy 2013"}) CREATE (Ind)-[r1:WINNERS_OF {NRR:0.938 ,pts:6}]->(CT2013) CREATE(Dhoni)-[r2:CAPTAIN_OF]->(Ind) Following is a sample Cypher Query which creates a node named Dhoni and returns it. Create (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"}) RETURN Dhoni To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. You can also return multiple nodes using the return clause. Following is the syntax to return multiple nodes using the return clause. CREATE (Ind:Country {name: "India", result: "Winners"}) CREATE (CT2013:Tornament {name: "ICC Champions Trophy 2013"}) RETURN Ind, CT2013 Following is a sample Cypher Query to return multiple nodes using the return clause. CREATE (Ind:Country {name: "India", result: "Winners"}) CREATE (CT2013:Tornament {name: "ICC Champions Trophy 2013"}) RETURN Ind, CT2013 To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Here you can observe that Neo4j returned 2 nodes. You can also return relationships using the Return clause. Following is the syntax to return relationships using the RETURN clause. CREATE (node1)-[Relationship:Relationship_type]->(node2) RETURN Relationship Following is a sample Cypher Query which creates two relationships and returns them. CREATE (Ind)-[r1:WINNERS_OF {NRR:0.938 ,pts:6}]->(CT2013) CREATE(Dhoni)-[r2:CAPTAIN_OF]->(Ind) RETURN r1, r2 To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. You can also return properties using the RETURN clause. Following is a syntax to return properties using the RETURN clause. Match (node:label {properties . . . . . . . . . . }) Return node.property Following is a sample Cypher Query to return the properties of a node. Match (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"}) Return Dhoni.name, Dhoni.POB To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. You can return all the elements in the Neo4j database using the RETURN clause. Following is an example Cypher Query to return all the elements in the database. Match p = (n {name: "India", result: "Winners"})-[r]-(x) RETURN * To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. You can return a particular column with alias using RETURN clause in Neo4j. Following is a sample Cypher Query which returns the column POB as Place Of Birth. Match (Dhoni:player {name: "MahendraSingh Dhoni", YOB: 1981, POB: "Ranchi"}) Return Dhoni.POB as Place Of Birth To execute the above query, carry out the following steps − Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot. Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot. On executing, you will get the following result. Print Add Notes Bookmark this page
[ { "code": null, "e": 2467, "s": 2339, "text": "The RETURN clause is used return nodes, relationships, and properties in Neo4j. In this chapter, we are going to learn how to −" }, { "code": null, "e": 2480, "s": 2467, "text": "Return nodes" }, { "code": null, "e": 2502, "s": 2480, "text": "Return multiple nodes" }, { "code": null, "e": 2523, "s": 2502, "text": "Return relationships" }, { "code": null, "e": 2541, "s": 2523, "text": "Return properties" }, { "code": null, "e": 2561, "s": 2541, "text": "Return all elements" }, { "code": null, "e": 2597, "s": 2561, "text": "Return a variable with column alias" }, { "code": null, "e": 2644, "s": 2597, "text": "You can return a node using the RETURN clause." }, { "code": null, "e": 2707, "s": 2644, "text": "Following is a syntax to return nodes using the RETURN clause." }, { "code": null, "e": 2755, "s": 2707, "text": "Create (node:label {properties}) \nRETURN node \n" }, { "code": null, "e": 2842, "s": 2755, "text": "Before proceeding with the example, create 3 nodes and 2 relationships as shown below." }, { "code": null, "e": 3138, "s": 2842, "text": "Create (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"}) \nCREATE (Ind:Country {name: \"India\", result: \"Winners\"}) \nCREATE (CT2013:Tornament {name: \"ICC Champions Trophy 2013\"}) \nCREATE (Ind)-[r1:WINNERS_OF {NRR:0.938 ,pts:6}]->(CT2013) \nCREATE(Dhoni)-[r2:CAPTAIN_OF]->(Ind) " }, { "code": null, "e": 3222, "s": 3138, "text": "Following is a sample Cypher Query which creates a node named Dhoni and returns it." }, { "code": null, "e": 3314, "s": 3222, "text": "Create (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"}) \nRETURN Dhoni" }, { "code": null, "e": 3374, "s": 3314, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 3552, "s": 3374, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 3705, "s": 3552, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 3754, "s": 3705, "text": "On executing, you will get the following result." }, { "code": null, "e": 3814, "s": 3754, "text": "You can also return multiple nodes using the return clause." }, { "code": null, "e": 3888, "s": 3814, "text": "Following is the syntax to return multiple nodes using the return clause." }, { "code": null, "e": 4029, "s": 3888, "text": "CREATE (Ind:Country {name: \"India\", result: \"Winners\"}) \nCREATE (CT2013:Tornament {name: \"ICC Champions Trophy 2013\"}) \nRETURN Ind, CT2013 \n" }, { "code": null, "e": 4114, "s": 4029, "text": "Following is a sample Cypher Query to return multiple nodes using the return clause." }, { "code": null, "e": 4254, "s": 4114, "text": "CREATE (Ind:Country {name: \"India\", result: \"Winners\"}) \nCREATE (CT2013:Tornament {name: \"ICC Champions Trophy 2013\"}) \nRETURN Ind, CT2013 " }, { "code": null, "e": 4314, "s": 4254, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 4492, "s": 4314, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 4645, "s": 4492, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 4744, "s": 4645, "text": "On executing, you will get the following result. Here you can observe that Neo4j returned 2 nodes." }, { "code": null, "e": 4803, "s": 4744, "text": "You can also return relationships using the Return clause." }, { "code": null, "e": 4876, "s": 4803, "text": "Following is the syntax to return relationships using the RETURN clause." }, { "code": null, "e": 4956, "s": 4876, "text": "CREATE (node1)-[Relationship:Relationship_type]->(node2) \nRETURN Relationship \n" }, { "code": null, "e": 5041, "s": 4956, "text": "Following is a sample Cypher Query which creates two relationships and returns them." }, { "code": null, "e": 5153, "s": 5041, "text": "CREATE (Ind)-[r1:WINNERS_OF {NRR:0.938 ,pts:6}]->(CT2013) \nCREATE(Dhoni)-[r2:CAPTAIN_OF]->(Ind) \nRETURN r1, r2 " }, { "code": null, "e": 5213, "s": 5153, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 5391, "s": 5213, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 5544, "s": 5391, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 5593, "s": 5544, "text": "On executing, you will get the following result." }, { "code": null, "e": 5649, "s": 5593, "text": "You can also return properties using the RETURN clause." }, { "code": null, "e": 5717, "s": 5649, "text": "Following is a syntax to return properties using the RETURN clause." }, { "code": null, "e": 5794, "s": 5717, "text": "Match (node:label {properties . . . . . . . . . . }) \nReturn node.property \n" }, { "code": null, "e": 5865, "s": 5794, "text": "Following is a sample Cypher Query to return the properties of a node." }, { "code": null, "e": 5973, "s": 5865, "text": "Match (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"}) \nReturn Dhoni.name, Dhoni.POB " }, { "code": null, "e": 6033, "s": 5973, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 6211, "s": 6033, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 6364, "s": 6211, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 6413, "s": 6364, "text": "On executing, you will get the following result." }, { "code": null, "e": 6492, "s": 6413, "text": "You can return all the elements in the Neo4j database using the RETURN clause." }, { "code": null, "e": 6573, "s": 6492, "text": "Following is an example Cypher Query to return all the elements in the database." }, { "code": null, "e": 6642, "s": 6573, "text": "Match p = (n {name: \"India\", result: \"Winners\"})-[r]-(x) \nRETURN * " }, { "code": null, "e": 6702, "s": 6642, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 6880, "s": 6702, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 7033, "s": 6880, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 7082, "s": 7033, "text": "On executing, you will get the following result." }, { "code": null, "e": 7158, "s": 7082, "text": "You can return a particular column with alias using RETURN clause in Neo4j." }, { "code": null, "e": 7241, "s": 7158, "text": "Following is a sample Cypher Query which returns the column POB as Place Of Birth." }, { "code": null, "e": 7354, "s": 7241, "text": "Match (Dhoni:player {name: \"MahendraSingh Dhoni\", YOB: 1981, POB: \"Ranchi\"}) \nReturn Dhoni.POB as Place Of Birth" }, { "code": null, "e": 7414, "s": 7354, "text": "To execute the above query, carry out the following steps −" }, { "code": null, "e": 7592, "s": 7414, "text": "Step 1 − Open the Neo4j desktop App and start the Neo4j Server. Open the built-in browser app of Neo4j using the URL http://localhost:7474/ as shown in the following screenshot." }, { "code": null, "e": 7745, "s": 7592, "text": "Step 2 − Copy and paste the desired query in the dollar prompt and press the play button (to execute the query) highlighted in the following screenshot." }, { "code": null, "e": 7794, "s": 7745, "text": "On executing, you will get the following result." }, { "code": null, "e": 7801, "s": 7794, "text": " Print" }, { "code": null, "e": 7812, "s": 7801, "text": " Add Notes" } ]
DFA in LEX code which accepts strings ending with 11 - GeeksforGeeks
22 May, 2019 Prerequisite: Designing Finite AutomataProblem: Design a LEX code to construct a DFA which accepts the language: all the strings ending with “11” over inputs ‘0’ and ‘1’. Examples: Input: 100011 Output: Accepted Input: 100101 Output: Not Accepted Input: asdf Output: Invalid Approach:LEX provides us with an INITIAL state by default. So in order to make a DFA, use this as the initial state of the DFA. Now we define three more states A, B and DEAD where DEAD state would be use if encounter a wrong or invalid input. When user input invalid character, move to DEAD state and print message “INVALID” and if input string ends at state B then display a message “Accepted”. If input string ends at state INITIAL and A then display a message “Not Accepted”. Note:To compile a LEX program, user need a UNIX system and flex which can be installed using sudo apt-get install flex. With all the above specification open UNIX terminal and do the following: Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file.Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file. Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file. Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file. lex lextest cc lex.yy.c -lfl LEX Code: %{%} %s A B DEAD %%<INITIAL>1 BEGIN A;<INITIAL>0 BEGIN INITIAL;<INITIAL>[^01\n] BEGIN DEAD;<INITIAL>\n BEGIN INITIAL; {printf("Not Accepted\n");} <A>1 BEGIN B;<A>0 BEGIN INITIAL;<A>[^01\n] BEGIN DEAD;<A>\n BEGIN INITIAL; {printf("Not Accepted\n");} <B>1 BEGIN B;<B>0 BEGIN INITIAL;<B>[^01\n] BEGIN DEAD;<B>\n BEGIN INITIAL; {printf("Accepted\n");} <DEAD>[^\n] BEGIN DEAD;<DEAD>\n BEGIN INITIAL; {printf("Invalid\n");} %% int main(){ printf("Enter String\n"); yylex();return 0;} Output: Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Directed Acyclic graph in Compiler Design (with examples) S - attributed and L - attributed SDTs in Syntax directed translation Difference between Top down parsing and Bottom up parsing Compiler construction tools Why FIRST and FOLLOW in Compiler Design? SLR Parser (with Examples) Lex program to count the number of lines, spaces and tabs Bottom Up or Shift Reduce Parsers | Set 2 Parsing | Set 1 (Introduction, Ambiguity and Parsers) Error detection and Recovery in Compiler
[ { "code": null, "e": 24029, "s": 24001, "text": "\n22 May, 2019" }, { "code": null, "e": 24200, "s": 24029, "text": "Prerequisite: Designing Finite AutomataProblem: Design a LEX code to construct a DFA which accepts the language: all the strings ending with “11” over inputs ‘0’ and ‘1’." }, { "code": null, "e": 24210, "s": 24200, "text": "Examples:" }, { "code": null, "e": 24308, "s": 24210, "text": "Input: 100011 \nOutput: Accepted\n\nInput: 100101\nOutput: Not Accepted\n\nInput: asdf\nOutput: Invalid " }, { "code": null, "e": 24787, "s": 24308, "text": "Approach:LEX provides us with an INITIAL state by default. So in order to make a DFA, use this as the initial state of the DFA. Now we define three more states A, B and DEAD where DEAD state would be use if encounter a wrong or invalid input. When user input invalid character, move to DEAD state and print message “INVALID” and if input string ends at state B then display a message “Accepted”. If input string ends at state INITIAL and A then display a message “Not Accepted”." }, { "code": null, "e": 24981, "s": 24787, "text": "Note:To compile a LEX program, user need a UNIX system and flex which can be installed using sudo apt-get install flex. With all the above specification open UNIX terminal and do the following:" }, { "code": null, "e": 25266, "s": 24981, "text": "Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file.Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file." }, { "code": null, "e": 25393, "s": 25266, "text": "Use the lex program to change the specification file into a C language program. The resulting program is in the lex.yy.c file." }, { "code": null, "e": 25552, "s": 25393, "text": "Use the cc command with the -ll flag to compile and link the program with a library of lex subroutines. The resulting executable program is in the a.out file." }, { "code": null, "e": 25582, "s": 25552, "text": "lex lextest\ncc lex.yy.c -lfl " }, { "code": null, "e": 25592, "s": 25582, "text": "LEX Code:" }, { "code": "%{%} %s A B DEAD %%<INITIAL>1 BEGIN A;<INITIAL>0 BEGIN INITIAL;<INITIAL>[^01\\n] BEGIN DEAD;<INITIAL>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");} <A>1 BEGIN B;<A>0 BEGIN INITIAL;<A>[^01\\n] BEGIN DEAD;<A>\\n BEGIN INITIAL; {printf(\"Not Accepted\\n\");} <B>1 BEGIN B;<B>0 BEGIN INITIAL;<B>[^01\\n] BEGIN DEAD;<B>\\n BEGIN INITIAL; {printf(\"Accepted\\n\");} <DEAD>[^\\n] BEGIN DEAD;<DEAD>\\n BEGIN INITIAL; {printf(\"Invalid\\n\");} %% int main(){ printf(\"Enter String\\n\"); yylex();return 0;}", "e": 26085, "s": 25592, "text": null }, { "code": null, "e": 26093, "s": 26085, "text": "Output:" }, { "code": null, "e": 26105, "s": 26093, "text": "Lex program" }, { "code": null, "e": 26121, "s": 26105, "text": "Compiler Design" }, { "code": null, "e": 26219, "s": 26121, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26228, "s": 26219, "text": "Comments" }, { "code": null, "e": 26241, "s": 26228, "text": "Old Comments" }, { "code": null, "e": 26299, "s": 26241, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 26369, "s": 26299, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 26427, "s": 26369, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 26455, "s": 26427, "text": "Compiler construction tools" }, { "code": null, "e": 26496, "s": 26455, "text": "Why FIRST and FOLLOW in Compiler Design?" }, { "code": null, "e": 26523, "s": 26496, "text": "SLR Parser (with Examples)" }, { "code": null, "e": 26581, "s": 26523, "text": "Lex program to count the number of lines, spaces and tabs" }, { "code": null, "e": 26623, "s": 26581, "text": "Bottom Up or Shift Reduce Parsers | Set 2" }, { "code": null, "e": 26677, "s": 26623, "text": "Parsing | Set 1 (Introduction, Ambiguity and Parsers)" } ]
Validate IP Address in C++
This article is serving the purpose of validating the correct IP (internet protocol) address by virtue of C++ code programming. The IP address is a 32-bit dot-decimal-notation, broken into four decimal numbers segments ranging from 0 to 255. Furthermore, these numbers are separated by dots consecutively. The IP address serves the purpose of identifying a host machine in the network in a unique manner in order to establish a connection among them. So, in order to validate the correct IP address input from the user-end, the following algorithm briefs how exactly the code sequence is materialized to identify the correct IP address as follows; START Step-1: Input the IP address Step-2: Spilt the IP into four segments and store in an array Step-3: Check whether it numeric or not using Step-4: Traverse the array list using foreach loop Step-5: Check its range (below 256) and data format Step-6: Call the validate method in the Main() END Thence, as per the algorithm the following c++ drafted to validate the IP address, in which couple of essentials functions are being employed to determine the numeric form, range, and splitting the input data respectively; Live Demo #include <iostream> #include <vector> #include <string> using namespace std; // check if the given string is a numeric string or not bool chkNumber(const string& str){ return !str.empty() && (str.find_first_not_of("[0123456789]") == std::string::npos); } // Function to split string str using given delimiter vector<string> split(const string& str, char delim){ auto i = 0; vector<string> list; auto pos = str.find(delim); while (pos != string::npos){ list.push_back(str.substr(i, pos - i)); i = ++pos; pos = str.find(delim, pos); } list.push_back(str.substr(i, str.length())); return list; } // Function to validate an IP address bool validateIP(string ip){ // split the string into tokens vector<string> slist = split(ip, '.'); // if token size is not equal to four if (slist.size() != 4) return false; for (string str : slist){ // check that string is number, positive, and range if (!chkNumber(str) || stoi(str) < 0 || stoi(str) > 255) return false; } return true; } // Validate an IP address in C++ int main(){ cout<<"Enter the IP Address::"; string ip; cin>>ip; if (validateIP(ip)) cout <<endl<< "***It is a Valid IP Address***"; else cout <<endl<< "***Invalid IP Address***"; return 0; } After the compilation of the above code using a standard c++ editor, the following output is being produced which is duly checking whether the input number 10.10.10.2 is a correct IP address or not as follows; Enter the IP Address:: 10.10.10.2 ***It is a Valid IP Assress***
[ { "code": null, "e": 1513, "s": 1062, "text": "This article is serving the purpose of validating the correct IP (internet protocol) address by virtue of C++ code programming. The IP address is a 32-bit dot-decimal-notation, broken into four decimal numbers segments ranging from 0 to 255. Furthermore, these numbers are separated by\ndots consecutively. The IP address serves the purpose of identifying a host machine in the network in a unique manner in order to establish a connection among them." }, { "code": null, "e": 1710, "s": 1513, "text": "So, in order to validate the correct IP address input from the user-end, the following algorithm briefs how exactly the code sequence is materialized to identify the correct IP address as follows;" }, { "code": null, "e": 2025, "s": 1710, "text": "START\n Step-1: Input the IP address\n Step-2: Spilt the IP into four segments and store in an array\n Step-3: Check whether it numeric or not using\n Step-4: Traverse the array list using foreach loop\n Step-5: Check its range (below 256) and data format\n Step-6: Call the validate method in the Main()\nEND" }, { "code": null, "e": 2248, "s": 2025, "text": "Thence, as per the algorithm the following c++ drafted to validate the IP address, in which couple of essentials functions are being employed to determine the numeric form, range, and splitting the input data respectively;" }, { "code": null, "e": 2259, "s": 2248, "text": " Live Demo" }, { "code": null, "e": 3580, "s": 2259, "text": "#include <iostream>\n#include <vector>\n#include <string>\nusing namespace std;\n// check if the given string is a numeric string or not\nbool chkNumber(const string& str){\n return !str.empty() &&\n (str.find_first_not_of(\"[0123456789]\") == std::string::npos);\n}\n// Function to split string str using given delimiter\nvector<string> split(const string& str, char delim){\n auto i = 0;\n vector<string> list;\n auto pos = str.find(delim);\n while (pos != string::npos){\n list.push_back(str.substr(i, pos - i));\n i = ++pos;\n pos = str.find(delim, pos);\n }\n list.push_back(str.substr(i, str.length()));\n return list;\n}\n// Function to validate an IP address\nbool validateIP(string ip){\n // split the string into tokens\n vector<string> slist = split(ip, '.');\n // if token size is not equal to four\n if (slist.size() != 4)\n return false;\n for (string str : slist){\n // check that string is number, positive, and range\n if (!chkNumber(str) || stoi(str) < 0 || stoi(str) > 255)\n return false;\n }\n return true;\n}\n // Validate an IP address in C++\nint main(){\n cout<<\"Enter the IP Address::\";\n string ip;\n cin>>ip;\n if (validateIP(ip))\n cout <<endl<< \"***It is a Valid IP Address***\";\n else\n cout <<endl<< \"***Invalid IP Address***\";\n return 0;\n}" }, { "code": null, "e": 3790, "s": 3580, "text": "After the compilation of the above code using a standard c++ editor, the following output is being produced which is duly checking whether the input number 10.10.10.2 is a correct IP address or not as follows;" }, { "code": null, "e": 3855, "s": 3790, "text": "Enter the IP Address:: 10.10.10.2\n***It is a Valid IP Assress***" } ]
Looping Techniques in Python - GeeksforGeeks
29 Mar, 2022 Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily very useful in competitive programming and also in various projects which require a specific technique with loops maintaining the overall structure of code. A lot of time and memory space is been saved as there is no need to declare the extra variables which we declare in the traditional approach of loops. Different looping techniques are primarily useful in the places where we don’t need to actually manipulate the structure and order of the overall containers, rather only print the elements for a single-use instance, no in-place change occurs in the container. This can also be used in instances to save time. Using enumerate(): enumerate() is used to loop through the containers printing the index number along with the value present in that particular index. Python3 # python code to demonstrate working of enumerate() for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']): print(key, value) Output: 0 The 1 Big 2 Bang 3 Theory Python3 # python code to demonstrate working of enumerate() for key, value in enumerate(['Geeks', 'for', 'Geeks', 'is', 'the', 'Best', 'Coding', 'Platform']): print(value, end=' ') Output: Geeks for Geeks is the Best Coding Platform Using zip(): zip() is used to combine 2 similar containers(list-list or dict-dict) printing the values sequentially. The loop exists only till the smaller container ends. A detailed explanation of zip() and enumerate() can be found here. Python3 # python code to demonstrate working of zip() # initializing listquestions = ['name', 'colour', 'shape']answers = ['apple', 'red', 'a circle'] # using zip() to combine two containers# and print valuesfor question, answer in zip(questions, answers): print('What is your {0}? I am {1}.'.format(question, answer)) Output: What is your name? I am apple. What is your color? I am red. What is your shape? I am a circle. Using iteritem(): iteritems() is used to loop through the dictionary printing the dictionary key-value pair sequentially which is used before Python 3 version. Using items(): items() performs the similar task on dictionary as iteritems() but have certain disadvantages when compared with iteritems().It is very time-consuming. Calling it on large dictionaries consumes quite a lot of time.It takes a lot of memory. Sometimes takes double the memory when called on a dictionary. It is very time-consuming. Calling it on large dictionaries consumes quite a lot of time. It takes a lot of memory. Sometimes takes double the memory when called on a dictionary. Example 1: Python3 # python code to demonstrate working of items() d = {"geeks": "for", "only": "geeks"} # iteritems() is renamed to items() in python3# using items to print the dictionary key-value pairprint("The key value pair using items is : ")for i, j in d.items(): print(i, j) Output: The key value pair using iteritems is : geeks for only geeks The key value pair using items is : geeks for only geeks Example 2: Python3 # python code to demonstrate working of items() king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya', 'Modi': 'The Changer'} # using items to print the dictionary key-value pairfor key, value in king.items(): print(key, value) Output: Akbar The Great Chandragupta The Maurya Modi The Changer Using sorted(): sorted() is used to print the container is sorted order. It doesn’t sort the container but just prints the container in sorted order for 1 instance. The use of set() can be combined to remove duplicate occurrences. Example 1: Python3 # python code to demonstrate working of sorted() # initializing listlis = [1, 3, 5, 6, 2, 1, 3] # using sorted() to print the list in sorted orderprint("The list in sorted order is : ")for i in sorted(lis): print(i, end=" ") print("\r") # using sorted() and set() to print the list in sorted order# use of set() removes duplicates.print("The list in sorted order (without duplicates) is : ")for i in sorted(set(lis)): print(i, end=" ") Output: The list in sorted order is : 1 1 2 3 3 5 6 The list in sorted order (without duplicates) is : 1 2 3 5 6 Example 2: Python3 # python code to demonstrate working of sorted() # initializing listbasket = ['guave', 'orange', 'apple', 'pear', 'guava', 'banana', 'grape'] # using sorted() and set() to print the list# in sorted orderfor fruit in sorted(set(basket)): print(fruit) Output: apple banana grape guava guave orange pear Using reversed(): reversed() is used to print the values of the container in the reversed order. It does not reflect any changes to the original list Example 1: Python3 # python code to demonstrate working of reversed() # initializing listlis = [1, 3, 5, 6, 2, 1, 3] # using reversed() to print the list in reversed orderprint("The list in reversed order is : ")for i in reversed(lis): print(i, end=" ") Output: The list in reversed order is : 3 1 2 6 5 3 1 Example 2: Python3 # python code to demonstrate working of reversed() # using reversed() to print in reverse orderfor i in reversed(range(1, 10, 3)): print(i) Output: 7 4 1 These techniques are quick to use and reduce coding effort. for, while loops need the entire structure of the container to be changed. These Looping techniques do not require any structural changes to the container. They have keywords that present the exact purpose of usage. Whereas, no pre-predictions or guesses can be made in for, while loop i.e not easily understand the purpose at a glance. Looping technique makes the code more concise than using for & while looping. YouTubeGeeksforGeeks500K subscribersPython Programming Tutorial | Looping Techniques in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:27•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=OwIoSkuuBB8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> raishivamsm PritamDey rutujakawade24 tripathiayushi0110 saurabhsamridh751 subhamagrawal861 simmytarika5 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe 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()
[ { "code": null, "e": 41161, "s": 41133, "text": "\n29 Mar, 2022" }, { "code": null, "e": 41605, "s": 41161, "text": "Python supports various looping techniques by certain inbuilt functions, in various sequential containers. These methods are primarily very useful in competitive programming and also in various projects which require a specific technique with loops maintaining the overall structure of code. A lot of time and memory space is been saved as there is no need to declare the extra variables which we declare in the traditional approach of loops." }, { "code": null, "e": 41914, "s": 41605, "text": "Different looping techniques are primarily useful in the places where we don’t need to actually manipulate the structure and order of the overall containers, rather only print the elements for a single-use instance, no in-place change occurs in the container. This can also be used in instances to save time." }, { "code": null, "e": 42066, "s": 41914, "text": "Using enumerate(): enumerate() is used to loop through the containers printing the index number along with the value present in that particular index." }, { "code": null, "e": 42074, "s": 42066, "text": "Python3" }, { "code": "# python code to demonstrate working of enumerate() for key, value in enumerate(['The', 'Big', 'Bang', 'Theory']): print(key, value)", "e": 42210, "s": 42074, "text": null }, { "code": null, "e": 42218, "s": 42210, "text": "Output:" }, { "code": null, "e": 42246, "s": 42218, "text": "0 The\n1 Big\n2 Bang\n3 Theory" }, { "code": null, "e": 42254, "s": 42246, "text": "Python3" }, { "code": "# python code to demonstrate working of enumerate() for key, value in enumerate(['Geeks', 'for', 'Geeks', 'is', 'the', 'Best', 'Coding', 'Platform']): print(value, end=' ')", "e": 42486, "s": 42254, "text": null }, { "code": null, "e": 42494, "s": 42486, "text": "Output:" }, { "code": null, "e": 42539, "s": 42494, "text": "Geeks for Geeks is the Best Coding Platform " }, { "code": null, "e": 42777, "s": 42539, "text": "Using zip(): zip() is used to combine 2 similar containers(list-list or dict-dict) printing the values sequentially. The loop exists only till the smaller container ends. A detailed explanation of zip() and enumerate() can be found here." }, { "code": null, "e": 42785, "s": 42777, "text": "Python3" }, { "code": "# python code to demonstrate working of zip() # initializing listquestions = ['name', 'colour', 'shape']answers = ['apple', 'red', 'a circle'] # using zip() to combine two containers# and print valuesfor question, answer in zip(questions, answers): print('What is your {0}? I am {1}.'.format(question, answer))", "e": 43100, "s": 42785, "text": null }, { "code": null, "e": 43108, "s": 43100, "text": "Output:" }, { "code": null, "e": 43207, "s": 43108, "text": "What is your name? I am apple.\nWhat is your color? I am red.\nWhat is your shape? I am a circle." }, { "code": null, "e": 43367, "s": 43207, "text": "Using iteritem(): iteritems() is used to loop through the dictionary printing the dictionary key-value pair sequentially which is used before Python 3 version." }, { "code": null, "e": 43685, "s": 43367, "text": "Using items(): items() performs the similar task on dictionary as iteritems() but have certain disadvantages when compared with iteritems().It is very time-consuming. Calling it on large dictionaries consumes quite a lot of time.It takes a lot of memory. Sometimes takes double the memory when called on a dictionary." }, { "code": null, "e": 43775, "s": 43685, "text": "It is very time-consuming. Calling it on large dictionaries consumes quite a lot of time." }, { "code": null, "e": 43864, "s": 43775, "text": "It takes a lot of memory. Sometimes takes double the memory when called on a dictionary." }, { "code": null, "e": 43875, "s": 43864, "text": "Example 1:" }, { "code": null, "e": 43883, "s": 43875, "text": "Python3" }, { "code": "# python code to demonstrate working of items() d = {\"geeks\": \"for\", \"only\": \"geeks\"} # iteritems() is renamed to items() in python3# using items to print the dictionary key-value pairprint(\"The key value pair using items is : \")for i, j in d.items(): print(i, j)", "e": 44150, "s": 43883, "text": null }, { "code": null, "e": 44158, "s": 44150, "text": "Output:" }, { "code": null, "e": 44278, "s": 44158, "text": "The key value pair using iteritems is : \ngeeks for\nonly geeks\nThe key value pair using items is : \ngeeks for\nonly geeks" }, { "code": null, "e": 44289, "s": 44278, "text": "Example 2:" }, { "code": null, "e": 44297, "s": 44289, "text": "Python3" }, { "code": "# python code to demonstrate working of items() king = {'Akbar': 'The Great', 'Chandragupta': 'The Maurya', 'Modi': 'The Changer'} # using items to print the dictionary key-value pairfor key, value in king.items(): print(key, value)", "e": 44540, "s": 44297, "text": null }, { "code": null, "e": 44548, "s": 44540, "text": "Output:" }, { "code": null, "e": 44605, "s": 44548, "text": "Akbar The Great\nChandragupta The Maurya\nModi The Changer" }, { "code": null, "e": 44837, "s": 44605, "text": "Using sorted(): sorted() is used to print the container is sorted order. It doesn’t sort the container but just prints the container in sorted order for 1 instance. The use of set() can be combined to remove duplicate occurrences." }, { "code": null, "e": 44848, "s": 44837, "text": "Example 1:" }, { "code": null, "e": 44856, "s": 44848, "text": "Python3" }, { "code": "# python code to demonstrate working of sorted() # initializing listlis = [1, 3, 5, 6, 2, 1, 3] # using sorted() to print the list in sorted orderprint(\"The list in sorted order is : \")for i in sorted(lis): print(i, end=\" \") print(\"\\r\") # using sorted() and set() to print the list in sorted order# use of set() removes duplicates.print(\"The list in sorted order (without duplicates) is : \")for i in sorted(set(lis)): print(i, end=\" \")", "e": 45298, "s": 44856, "text": null }, { "code": null, "e": 45306, "s": 45298, "text": "Output:" }, { "code": null, "e": 45415, "s": 45306, "text": "The list in sorted order is : \n1 1 2 3 3 5 6 \nThe list in sorted order (without duplicates) is : \n1 2 3 5 6 " }, { "code": null, "e": 45426, "s": 45415, "text": "Example 2:" }, { "code": null, "e": 45434, "s": 45426, "text": "Python3" }, { "code": "# python code to demonstrate working of sorted() # initializing listbasket = ['guave', 'orange', 'apple', 'pear', 'guava', 'banana', 'grape'] # using sorted() and set() to print the list# in sorted orderfor fruit in sorted(set(basket)): print(fruit)", "e": 45697, "s": 45434, "text": null }, { "code": null, "e": 45705, "s": 45697, "text": "Output:" }, { "code": null, "e": 45748, "s": 45705, "text": "apple\nbanana\ngrape\nguava\nguave\norange\npear" }, { "code": null, "e": 45898, "s": 45748, "text": "Using reversed(): reversed() is used to print the values of the container in the reversed order. It does not reflect any changes to the original list" }, { "code": null, "e": 45909, "s": 45898, "text": "Example 1:" }, { "code": null, "e": 45917, "s": 45909, "text": "Python3" }, { "code": "# python code to demonstrate working of reversed() # initializing listlis = [1, 3, 5, 6, 2, 1, 3] # using reversed() to print the list in reversed orderprint(\"The list in reversed order is : \")for i in reversed(lis): print(i, end=\" \")", "e": 46156, "s": 45917, "text": null }, { "code": null, "e": 46164, "s": 46156, "text": "Output:" }, { "code": null, "e": 46212, "s": 46164, "text": "The list in reversed order is : \n3 1 2 6 5 3 1 " }, { "code": null, "e": 46223, "s": 46212, "text": "Example 2:" }, { "code": null, "e": 46231, "s": 46223, "text": "Python3" }, { "code": "# python code to demonstrate working of reversed() # using reversed() to print in reverse orderfor i in reversed(range(1, 10, 3)): print(i)", "e": 46374, "s": 46231, "text": null }, { "code": null, "e": 46382, "s": 46374, "text": "Output:" }, { "code": null, "e": 46388, "s": 46382, "text": "7\n4\n1" }, { "code": null, "e": 46523, "s": 46388, "text": "These techniques are quick to use and reduce coding effort. for, while loops need the entire structure of the container to be changed." }, { "code": null, "e": 46785, "s": 46523, "text": "These Looping techniques do not require any structural changes to the container. They have keywords that present the exact purpose of usage. Whereas, no pre-predictions or guesses can be made in for, while loop i.e not easily understand the purpose at a glance." }, { "code": null, "e": 46863, "s": 46785, "text": "Looping technique makes the code more concise than using for & while looping." }, { "code": null, "e": 47720, "s": 46863, "text": "YouTubeGeeksforGeeks500K subscribersPython Programming Tutorial | Looping Techniques in Python | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:27•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=OwIoSkuuBB8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 47732, "s": 47720, "text": "raishivamsm" }, { "code": null, "e": 47742, "s": 47732, "text": "PritamDey" }, { "code": null, "e": 47757, "s": 47742, "text": "rutujakawade24" }, { "code": null, "e": 47776, "s": 47757, "text": "tripathiayushi0110" }, { "code": null, "e": 47794, "s": 47776, "text": "saurabhsamridh751" }, { "code": null, "e": 47811, "s": 47794, "text": "subhamagrawal861" }, { "code": null, "e": 47824, "s": 47811, "text": "simmytarika5" }, { "code": null, "e": 47831, "s": 47824, "text": "Python" }, { "code": null, "e": 47929, "s": 47831, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 47938, "s": 47929, "text": "Comments" }, { "code": null, "e": 47951, "s": 47938, "text": "Old Comments" }, { "code": null, "e": 47979, "s": 47951, "text": "Read JSON file using Python" }, { "code": null, "e": 48029, "s": 47979, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 48051, "s": 48029, "text": "Python map() function" }, { "code": null, "e": 48095, "s": 48051, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 48130, "s": 48095, "text": "Read a file line by line in Python" }, { "code": null, "e": 48152, "s": 48130, "text": "Enumerate() in Python" }, { "code": null, "e": 48184, "s": 48152, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 48214, "s": 48184, "text": "Iterate over a list in Python" }, { "code": null, "e": 48256, "s": 48214, "text": "Different ways to create Pandas Dataframe" } ]
Angular 4 - Event Binding
In this chapter, we will discuss how Event Binding works in Angular 4. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouseover, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture. Let us consider an example to understand this better. <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable; then condition1 else condition2"> Condition is valid. </span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> <button (click)="myClickFunction($event)"> Click Me </button> In the app.component.html file, we have defined a button and added a function to it using the click event. Following is the syntax to define a button and add a function to it. (click)="myClickFunction($event)" The function is defined in the .ts file: app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; myClickFunction(event) { //just added console.log which will display the event details in browser on click of the button. alert("Button is clicked"); console.log(event); } } Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot − Let us now add the change event to the dropdown. The following line of code will help you add the change event to the dropdown − <!--The content below is only a placeholder and can be replaced.--> <div style = "text-align:center"> <h1> Welcome to {{title}}. </h1> </div> <div> Months : <select (change) = "changemonths($event)"> <option *ngFor = "let i of months">{{i}}</option> </select> </div> <br/> <div> <span *ngIf = "isavailable; then condition1 else condition2"> Condition is valid. </span> <ng-template #condition1>Condition is valid</ng-template> <ng-template #condition2>Condition is invalid</ng-template> </div> <button (click) = "myClickFunction($event)">Click Me</button> The function is declared in the app.component.ts file − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "Feburary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; myClickFunction(event) { alert("Button is clicked"); console.log(event); } changemonths(event) { console.log("Changed month from the Dropdown"); console.log(event); } } The console message “Changed month from the Dropdown” is displayed in the console along with the event. Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below − import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'Angular 4 Project!'; //array of months. months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; isavailable = true; myClickFunction(event) { //just added console.log which will display the event details in browser on click of the button. alert("Button is clicked"); console.log(event); } changemonths(event) { alert("Changed month from the Dropdown"); } } When the value in dropdown is changed, a dialog box will appear and the following message will be displayed - “Changed month from the Dropdown”. 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": 2307, "s": 1992, "text": "In this chapter, we will discuss how Event Binding works in Angular 4. When a user interacts with an application in the form of a keyboard movement, a mouse click, or a mouseover, it generates an event. These events need to be handled to perform some kind of action. This is where event binding comes into picture." }, { "code": null, "e": 2361, "s": 2307, "text": "Let us consider an example to understand this better." }, { "code": null, "e": 2930, "s": 2361, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select>\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>\n<button (click)=\"myClickFunction($event)\">\n Click Me\n</button>" }, { "code": null, "e": 3037, "s": 2930, "text": "In the app.component.html file, we have defined a button and added a function to it using the click event." }, { "code": null, "e": 3106, "s": 3037, "text": "Following is the syntax to define a button and add a function to it." }, { "code": null, "e": 3141, "s": 3106, "text": "(click)=\"myClickFunction($event)\"\n" }, { "code": null, "e": 3200, "s": 3141, "text": "The function is defined in the .ts file: app.component.ts\n" }, { "code": null, "e": 3829, "s": 3200, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = true;\n myClickFunction(event) { \n //just added console.log which will display the event details in browser on click of the button.\n alert(\"Button is clicked\");\n console.log(event);\n }\n}" }, { "code": null, "e": 4015, "s": 3829, "text": "Upon clicking the button, the control will come to the function myClickFunction and a dialog box will appear, which displays the Button is clicked as shown in the following screenshot −" }, { "code": null, "e": 4064, "s": 4015, "text": "Let us now add the change event to the dropdown." }, { "code": null, "e": 4144, "s": 4064, "text": "The following line of code will help you add the change event to the dropdown −" }, { "code": null, "e": 4745, "s": 4144, "text": "<!--The content below is only a placeholder and can be replaced.-->\n<div style = \"text-align:center\">\n <h1>\n Welcome to {{title}}.\n </h1>\n</div>\n\n<div> Months :\n <select (change) = \"changemonths($event)\">\n <option *ngFor = \"let i of months\">{{i}}</option>\n </select>\n</div>\n<br/>\n\n<div>\n <span *ngIf = \"isavailable; then condition1 else condition2\">\n Condition is valid.\n </span>\n <ng-template #condition1>Condition is valid</ng-template>\n <ng-template #condition2>Condition is invalid</ng-template>\n</div>\n\n<button (click) = \"myClickFunction($event)\">Click Me</button>" }, { "code": null, "e": 4801, "s": 4745, "text": "The function is declared in the app.component.ts file −" }, { "code": null, "e": 5436, "s": 4801, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"Feburary\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n isavailable = true;\n myClickFunction(event) {\n alert(\"Button is clicked\");\n console.log(event);\n }\n changemonths(event) {\n console.log(\"Changed month from the Dropdown\");\n console.log(event);\n }\n}" }, { "code": null, "e": 5540, "s": 5436, "text": "The console message “Changed month from the Dropdown” is displayed in the console along with the event." }, { "code": null, "e": 5649, "s": 5540, "text": "Let us add an alert message in app.component.ts when the value from the dropdown is changed as shown below −" }, { "code": null, "e": 6367, "s": 5649, "text": "import { Component } from '@angular/core';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\n\nexport class AppComponent {\n title = 'Angular 4 Project!';\n //array of months.\n months = [\"January\", \"February\", \"March\", \"April\",\n \"May\", \"June\", \"July\", \"August\", \"September\",\n \"October\", \"November\", \"December\"];\n \n isavailable = true;\n myClickFunction(event) { \n //just added console.log which will display the event details in browser \n on click of the button.\n alert(\"Button is clicked\");\n console.log(event);\n }\n changemonths(event) {\n alert(\"Changed month from the Dropdown\");\n }\n}" }, { "code": null, "e": 6512, "s": 6367, "text": "When the value in dropdown is changed, a dialog box will appear and the following message will be displayed - “Changed month from the Dropdown”." }, { "code": null, "e": 6547, "s": 6512, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6561, "s": 6547, "text": " Anadi Sharma" }, { "code": null, "e": 6596, "s": 6561, "text": "\n 28 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6610, "s": 6596, "text": " Anadi Sharma" }, { "code": null, "e": 6645, "s": 6610, "text": "\n 11 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6665, "s": 6645, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6700, "s": 6665, "text": "\n 16 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6717, "s": 6700, "text": " Frahaan Hussain" }, { "code": null, "e": 6750, "s": 6717, "text": "\n 69 Lectures \n 5 hours \n" }, { "code": null, "e": 6762, "s": 6750, "text": " Senol Atac" }, { "code": null, "e": 6797, "s": 6762, "text": "\n 53 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6809, "s": 6797, "text": " Senol Atac" }, { "code": null, "e": 6816, "s": 6809, "text": " Print" }, { "code": null, "e": 6827, "s": 6816, "text": " Add Notes" } ]
Difference between Recursion and Iteration - GeeksforGeeks
31 Jan, 2022 A program is called recursive when an entity calls itself. A program is call iterative when there is a loop (or repetition).Example: Program to find the factorial of a number C++ Java Python3 C# PHP Javascript // C++ program to find factorial of given number#include<bits/stdc++.h>using namespace std; // ----- Recursion -----// method to find factorial of given numberint factorialUsingRecursion(int n){ if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1);} // ----- Iteration -----// Method to find the factorial of a given numberint factorialUsingIteration(int n){ int res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res;} // Driver methodint main(){ int num = 5; cout << "Factorial of " << num << " using Recursion is: " << factorialUsingRecursion(5) << endl; cout << "Factorial of " << num << " using Iteration is: " << factorialUsingIteration(5); return 0;} // This code is contributed by mits // Java program to find factorial of given numberclass GFG { // ----- Recursion ----- // method to find factorial of given number static int factorialUsingRecursion(int n) { if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1); } // ----- Iteration ----- // Method to find the factorial of a given number static int factorialUsingIteration(int n) { int res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res; } // Driver method public static void main(String[] args) { int num = 5; System.out.println("Factorial of " + num + " using Recursion is: " + factorialUsingRecursion(5)); System.out.println("Factorial of " + num + " using Iteration is: " + factorialUsingIteration(5)); }} # Python3 program to find factorial of given number # ----- Recursion -----# method to find factorial of given numberdef factorialUsingRecursion(n): if (n == 0): return 1; # recursion call return n * factorialUsingRecursion(n - 1); # ----- Iteration -----# Method to find the factorial of a given numberdef factorialUsingIteration(n): res = 1; # using iteration for i in range(2, n + 1): res *= i; return res; # Driver methodnum = 5;print("Factorial of",num,"using Recursion is:", factorialUsingRecursion(5)); print("Factorial of",num,"using Iteration is:", factorialUsingIteration(5)); # This code is contributed by mits // C# program to find factorial of// given numberusing System; class GFG{ // ----- Recursion ----- // method to find factorial of // given number static int factorialUsingRecursion(int n) { if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1); } // ----- Iteration ----- // Method to find the factorial of // a given number static int factorialUsingIteration(int n) { int res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res; } // Driver Code public static void Main(String[] args) { int num = 5; Console.WriteLine("Factorial of " + num + " using Recursion is: " + factorialUsingRecursion(5)); Console.WriteLine("Factorial of " + num + " using Iteration is: " + factorialUsingIteration(5)); }} // This code has been contributed by Rajput-Ji <?php// PHP program to find factorial of given number // ----- Recursion ----- // method to find factorial of given number function factorialUsingRecursion($n) { if ($n == 0) return 1; // recursion call return $n * factorialUsingRecursion($n - 1); } // ----- Iteration ----- // Method to find the factorial of a given number function factorialUsingIteration($n) { $res = 1; // using iteration for ($i = 2; $i <= $n; $i++) $res *= $i; return $res; } // Driver method $num = 5; print("Factorial of ".$num." using Recursion is: ". factorialUsingRecursion(5)."\n"); print("Factorial of ".$num." using Iteration is: ". factorialUsingIteration(5)."\n"); // This code is contributed by mits?> <script> // JavaScript program to find factorial of given number// ----- Recursion -----// method to find factorial of given numberfunction factorialUsingRecursion(n) { if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1); } // ----- Iteration ----- // Method to find the factorial of a given number function factorialUsingIteration(n) { var res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res; } // Driver method var num = 5; document.write("Factorial of " + num + " using Recursion is: " + factorialUsingRecursion(5)+"<br>"); document.write("Factorial of " + num + " using Iteration is: " + factorialUsingIteration(5)); // This code is contributed by shivanisinghss2110</script> Factorial of 5 using Recursion is: 120 Factorial of 5 using Iteration is: 120 Below are the detailed example to illustrate the difference between the two: Time Complexity: Finding the Time complexity of Recursion is more difficult than that of Iteration. Recursion: Time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details. Iteration: Time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. Usage: Usage of either of these techniques is a trade-off between time complexity and size of code. If time complexity is the point of focus, and number of recursive calls would be large, it is better to use iteration. However, if time complexity is not an issue and shortness of code is, recursion would be the way to go.Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity. Iteration: Iteration is repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. Overhead: Recursion has a large amount of Overhead as compared to Iteration. Recursion: Recursion has the overhead of repeated function calls, that is due to repetitive calling of the same function, the time complexity of the code increases manyfold. Iteration: Iteration does not involve any such overhead. Infinite Repetition: Infinite Repetition in recursion can lead to CPU crash but in iteration, it will stop when memory is exhausted. Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to system CPU crash. Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. Time Complexity: Finding the Time complexity of Recursion is more difficult than that of Iteration. Recursion: Time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details. Iteration: Time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. Recursion: Time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details. Iteration: Time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. Usage: Usage of either of these techniques is a trade-off between time complexity and size of code. If time complexity is the point of focus, and number of recursive calls would be large, it is better to use iteration. However, if time complexity is not an issue and shortness of code is, recursion would be the way to go.Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity. Iteration: Iteration is repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity. Iteration: Iteration is repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. Overhead: Recursion has a large amount of Overhead as compared to Iteration. Recursion: Recursion has the overhead of repeated function calls, that is due to repetitive calling of the same function, the time complexity of the code increases manyfold. Iteration: Iteration does not involve any such overhead. Recursion: Recursion has the overhead of repeated function calls, that is due to repetitive calling of the same function, the time complexity of the code increases manyfold. Iteration: Iteration does not involve any such overhead. Infinite Repetition: Infinite Repetition in recursion can lead to CPU crash but in iteration, it will stop when memory is exhausted. Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to system CPU crash. Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to system CPU crash. Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. Rajput-Ji Mithun Kumar shivanisinghss2110 vijaykumarsah293 Algorithms-Recursion Picked Technical Scripter 2018 Algorithms Analysis Technical Scripter Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Playfair Cipher with Examples How to write a Pseudo Code? Analysis of Algorithms | Set 1 (Asymptotic Analysis) Practice Questions on Time Complexity Analysis Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
[ { "code": null, "e": 24810, "s": 24782, "text": "\n31 Jan, 2022" }, { "code": null, "e": 24987, "s": 24810, "text": "A program is called recursive when an entity calls itself. A program is call iterative when there is a loop (or repetition).Example: Program to find the factorial of a number " }, { "code": null, "e": 24991, "s": 24987, "text": "C++" }, { "code": null, "e": 24996, "s": 24991, "text": "Java" }, { "code": null, "e": 25004, "s": 24996, "text": "Python3" }, { "code": null, "e": 25007, "s": 25004, "text": "C#" }, { "code": null, "e": 25011, "s": 25007, "text": "PHP" }, { "code": null, "e": 25022, "s": 25011, "text": "Javascript" }, { "code": "// C++ program to find factorial of given number#include<bits/stdc++.h>using namespace std; // ----- Recursion -----// method to find factorial of given numberint factorialUsingRecursion(int n){ if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1);} // ----- Iteration -----// Method to find the factorial of a given numberint factorialUsingIteration(int n){ int res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res;} // Driver methodint main(){ int num = 5; cout << \"Factorial of \" << num << \" using Recursion is: \" << factorialUsingRecursion(5) << endl; cout << \"Factorial of \" << num << \" using Iteration is: \" << factorialUsingIteration(5); return 0;} // This code is contributed by mits", "e": 25863, "s": 25022, "text": null }, { "code": "// Java program to find factorial of given numberclass GFG { // ----- Recursion ----- // method to find factorial of given number static int factorialUsingRecursion(int n) { if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1); } // ----- Iteration ----- // Method to find the factorial of a given number static int factorialUsingIteration(int n) { int res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res; } // Driver method public static void main(String[] args) { int num = 5; System.out.println(\"Factorial of \" + num + \" using Recursion is: \" + factorialUsingRecursion(5)); System.out.println(\"Factorial of \" + num + \" using Iteration is: \" + factorialUsingIteration(5)); }}", "e": 26840, "s": 25863, "text": null }, { "code": "# Python3 program to find factorial of given number # ----- Recursion -----# method to find factorial of given numberdef factorialUsingRecursion(n): if (n == 0): return 1; # recursion call return n * factorialUsingRecursion(n - 1); # ----- Iteration -----# Method to find the factorial of a given numberdef factorialUsingIteration(n): res = 1; # using iteration for i in range(2, n + 1): res *= i; return res; # Driver methodnum = 5;print(\"Factorial of\",num,\"using Recursion is:\", factorialUsingRecursion(5)); print(\"Factorial of\",num,\"using Iteration is:\", factorialUsingIteration(5)); # This code is contributed by mits", "e": 27542, "s": 26840, "text": null }, { "code": "// C# program to find factorial of// given numberusing System; class GFG{ // ----- Recursion ----- // method to find factorial of // given number static int factorialUsingRecursion(int n) { if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1); } // ----- Iteration ----- // Method to find the factorial of // a given number static int factorialUsingIteration(int n) { int res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res; } // Driver Code public static void Main(String[] args) { int num = 5; Console.WriteLine(\"Factorial of \" + num + \" using Recursion is: \" + factorialUsingRecursion(5)); Console.WriteLine(\"Factorial of \" + num + \" using Iteration is: \" + factorialUsingIteration(5)); }} // This code has been contributed by Rajput-Ji", "e": 28583, "s": 27542, "text": null }, { "code": "<?php// PHP program to find factorial of given number // ----- Recursion ----- // method to find factorial of given number function factorialUsingRecursion($n) { if ($n == 0) return 1; // recursion call return $n * factorialUsingRecursion($n - 1); } // ----- Iteration ----- // Method to find the factorial of a given number function factorialUsingIteration($n) { $res = 1; // using iteration for ($i = 2; $i <= $n; $i++) $res *= $i; return $res; } // Driver method $num = 5; print(\"Factorial of \".$num.\" using Recursion is: \". factorialUsingRecursion(5).\"\\n\"); print(\"Factorial of \".$num.\" using Iteration is: \". factorialUsingIteration(5).\"\\n\"); // This code is contributed by mits?>", "e": 29459, "s": 28583, "text": null }, { "code": "<script> // JavaScript program to find factorial of given number// ----- Recursion -----// method to find factorial of given numberfunction factorialUsingRecursion(n) { if (n == 0) return 1; // recursion call return n * factorialUsingRecursion(n - 1); } // ----- Iteration ----- // Method to find the factorial of a given number function factorialUsingIteration(n) { var res = 1, i; // using iteration for (i = 2; i <= n; i++) res *= i; return res; } // Driver method var num = 5; document.write(\"Factorial of \" + num + \" using Recursion is: \" + factorialUsingRecursion(5)+\"<br>\"); document.write(\"Factorial of \" + num + \" using Iteration is: \" + factorialUsingIteration(5)); // This code is contributed by shivanisinghss2110</script>", "e": 30424, "s": 29459, "text": null }, { "code": null, "e": 30502, "s": 30424, "text": "Factorial of 5 using Recursion is: 120\nFactorial of 5 using Iteration is: 120" }, { "code": null, "e": 30582, "s": 30504, "text": "Below are the detailed example to illustrate the difference between the two: " }, { "code": null, "e": 32873, "s": 30582, "text": "Time Complexity: Finding the Time complexity of Recursion is more difficult than that of Iteration. Recursion: Time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details. Iteration: Time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. Usage: Usage of either of these techniques is a trade-off between time complexity and size of code. If time complexity is the point of focus, and number of recursive calls would be large, it is better to use iteration. However, if time complexity is not an issue and shortness of code is, recursion would be the way to go.Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity. Iteration: Iteration is repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. Overhead: Recursion has a large amount of Overhead as compared to Iteration. Recursion: Recursion has the overhead of repeated function calls, that is due to repetitive calling of the same function, the time complexity of the code increases manyfold. Iteration: Iteration does not involve any such overhead. Infinite Repetition: Infinite Repetition in recursion can lead to CPU crash but in iteration, it will stop when memory is exhausted. Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to system CPU crash. Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. " }, { "code": null, "e": 33438, "s": 32873, "text": "Time Complexity: Finding the Time complexity of Recursion is more difficult than that of Iteration. Recursion: Time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details. Iteration: Time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. " }, { "code": null, "e": 33785, "s": 33438, "text": "Recursion: Time complexity of recursion can be found by finding the value of the nth recursive call in terms of the previous calls. Thus, finding the destination case in terms of the base case, and solving in terms of the base case gives us an idea of the time complexity of recursive equations. Please see Solving Recurrences for more details. " }, { "code": null, "e": 33904, "s": 33785, "text": "Iteration: Time complexity of iteration can be found by finding the number of cycles being repeated inside the loop. " }, { "code": null, "e": 34737, "s": 33904, "text": "Usage: Usage of either of these techniques is a trade-off between time complexity and size of code. If time complexity is the point of focus, and number of recursive calls would be large, it is better to use iteration. However, if time complexity is not an issue and shortness of code is, recursion would be the way to go.Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity. Iteration: Iteration is repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. " }, { "code": null, "e": 35085, "s": 34737, "text": "Recursion: Recursion involves calling the same function again, and hence, has a very small length of code. However, as we saw in the analysis, the time complexity of recursion can get to be exponential when there are a considerable number of recursive calls. Hence, usage of recursion is advantageous in shorter code, but higher time complexity. " }, { "code": null, "e": 35249, "s": 35085, "text": "Iteration: Iteration is repetition of a block of code. This involves a larger size of code, but the time complexity is generally lesser than it is for recursion. " }, { "code": null, "e": 35560, "s": 35249, "text": "Overhead: Recursion has a large amount of Overhead as compared to Iteration. Recursion: Recursion has the overhead of repeated function calls, that is due to repetitive calling of the same function, the time complexity of the code increases manyfold. Iteration: Iteration does not involve any such overhead. " }, { "code": null, "e": 35736, "s": 35560, "text": "Recursion: Recursion has the overhead of repeated function calls, that is due to repetitive calling of the same function, the time complexity of the code increases manyfold. " }, { "code": null, "e": 35795, "s": 35736, "text": "Iteration: Iteration does not involve any such overhead. " }, { "code": null, "e": 36380, "s": 35795, "text": "Infinite Repetition: Infinite Repetition in recursion can lead to CPU crash but in iteration, it will stop when memory is exhausted. Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to system CPU crash. Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. " }, { "code": null, "e": 36591, "s": 36380, "text": "Recursion: In Recursion, Infinite recursive calls may occur due to some mistake in specifying the base condition, which on never becoming false, keeps calling the function, which may lead to system CPU crash. " }, { "code": null, "e": 36833, "s": 36591, "text": "Iteration: Infinite iteration due to mistake in iterator assignment or increment, or in the terminating condition, will lead to infinite loops, which may or may not lead to system errors, but will surely stop program execution any further. " }, { "code": null, "e": 36850, "s": 36840, "text": "Rajput-Ji" }, { "code": null, "e": 36863, "s": 36850, "text": "Mithun Kumar" }, { "code": null, "e": 36882, "s": 36863, "text": "shivanisinghss2110" }, { "code": null, "e": 36899, "s": 36882, "text": "vijaykumarsah293" }, { "code": null, "e": 36920, "s": 36899, "text": "Algorithms-Recursion" }, { "code": null, "e": 36927, "s": 36920, "text": "Picked" }, { "code": null, "e": 36951, "s": 36927, "text": "Technical Scripter 2018" }, { "code": null, "e": 36962, "s": 36951, "text": "Algorithms" }, { "code": null, "e": 36971, "s": 36962, "text": "Analysis" }, { "code": null, "e": 36990, "s": 36971, "text": "Technical Scripter" }, { "code": null, "e": 37001, "s": 36990, "text": "Algorithms" }, { "code": null, "e": 37099, "s": 37001, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37108, "s": 37099, "text": "Comments" }, { "code": null, "e": 37121, "s": 37108, "text": "Old Comments" }, { "code": null, "e": 37170, "s": 37121, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 37195, "s": 37170, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37222, "s": 37195, "text": "Introduction to Algorithms" }, { "code": null, "e": 37252, "s": 37222, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 37280, "s": 37252, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 37333, "s": 37280, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 37380, "s": 37333, "text": "Practice Questions on Time Complexity Analysis" }, { "code": null, "e": 37431, "s": 37380, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 37468, "s": 37431, "text": "Time Complexity and Space Complexity" } ]
Get last n records of a Pandas DataFrame - GeeksforGeeks
26 Jul, 2020 Let’s discuss how to get last n records of a Pandas DAtaframe. There can be various methods to get the last n records of a Pandas DataFrame. Lets first make a dataframe:Example: Python3 # Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, np.inf, -np.inf, 22], 'Marks': [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf Output: Method 1: Using tail() method Use pandas.DataFrame.tail(n) to get the last n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the end). By default n = 5, it return the last 5 rows if the value of n is not passed to the method. Syntax: df.tail(n) Example: Python3 # Getting last 3 rows from dfdf_last_3 = df.tail(3) # Printing df_last_3print(df_last_3) Output: Method 2: Using pandas.DataFrame.iloc Use pandas.DataFrame.iloc to get last n rows. It is similar to the list slicing.Syntax: df.iloc[-n:] Example: Python3 # Getting last 3 rows from dfdf_last_3 = df.iloc[-3:] # Printing df_last_3print(df_last_3) Output: Method 3: Display last n records of specific columnsDisplay last n records for the specific column Python3 # Getting last 2 rows of columns # Age and Marks from dfdf_last_2 = df[['Age', 'Marks']].tail(2) # Printing df_last_2print(df_last_2) Output: Method 4: Display last n records from last n columnsDisplay last n records for the last n columns using pandas.DataFrame.iloc Python3 # Getting last n rows and last n columns from dfdf_last_2_row_col = df.iloc[-2:,-2:] # Printing df_last_2print(df_last_2_row_col) Output: pandas-dataframe-program Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24292, "s": 24264, "text": "\n26 Jul, 2020" }, { "code": null, "e": 24470, "s": 24292, "text": "Let’s discuss how to get last n records of a Pandas DAtaframe. There can be various methods to get the last n records of a Pandas DataFrame. Lets first make a dataframe:Example:" }, { "code": null, "e": 24478, "s": 24470, "text": "Python3" }, { "code": "# Import Required Librariesimport pandas as pdimport numpy as np # Create a dictionary for the dataframedict = {'Name': ['Sukritin', 'Sumit Tyagi', 'Akriti Goel', 'Sanskriti', 'Abhishek Jain'], 'Age': [22, 20, np.inf, -np.inf, 22], 'Marks': [90, 84, 33, 87, 82]} # Converting Dictionary to Pandas Dataframedf = pd.DataFrame(dict) # Print Dataframedf", "e": 24862, "s": 24478, "text": null }, { "code": null, "e": 24872, "s": 24862, "text": "Output: " }, { "code": null, "e": 24904, "s": 24874, "text": "Method 1: Using tail() method" }, { "code": null, "e": 25145, "s": 24904, "text": "Use pandas.DataFrame.tail(n) to get the last n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the end). By default n = 5, it return the last 5 rows if the value of n is not passed to the method." }, { "code": null, "e": 25154, "s": 25145, "text": "Syntax: " }, { "code": null, "e": 25166, "s": 25154, "text": "df.tail(n)\n" }, { "code": null, "e": 25175, "s": 25166, "text": "Example:" }, { "code": null, "e": 25183, "s": 25175, "text": "Python3" }, { "code": "# Getting last 3 rows from dfdf_last_3 = df.tail(3) # Printing df_last_3print(df_last_3)", "e": 25273, "s": 25183, "text": null }, { "code": null, "e": 25283, "s": 25273, "text": "Output: " }, { "code": null, "e": 25323, "s": 25285, "text": "Method 2: Using pandas.DataFrame.iloc" }, { "code": null, "e": 25412, "s": 25323, "text": "Use pandas.DataFrame.iloc to get last n rows. It is similar to the list slicing.Syntax: " }, { "code": null, "e": 25426, "s": 25412, "text": "df.iloc[-n:]\n" }, { "code": null, "e": 25435, "s": 25426, "text": "Example:" }, { "code": null, "e": 25443, "s": 25435, "text": "Python3" }, { "code": "# Getting last 3 rows from dfdf_last_3 = df.iloc[-3:] # Printing df_last_3print(df_last_3)", "e": 25535, "s": 25443, "text": null }, { "code": null, "e": 25545, "s": 25535, "text": "Output: " }, { "code": null, "e": 25644, "s": 25545, "text": "Method 3: Display last n records of specific columnsDisplay last n records for the specific column" }, { "code": null, "e": 25652, "s": 25644, "text": "Python3" }, { "code": "# Getting last 2 rows of columns # Age and Marks from dfdf_last_2 = df[['Age', 'Marks']].tail(2) # Printing df_last_2print(df_last_2)", "e": 25787, "s": 25652, "text": null }, { "code": null, "e": 25797, "s": 25787, "text": "Output: " }, { "code": null, "e": 25923, "s": 25797, "text": "Method 4: Display last n records from last n columnsDisplay last n records for the last n columns using pandas.DataFrame.iloc" }, { "code": null, "e": 25931, "s": 25923, "text": "Python3" }, { "code": "# Getting last n rows and last n columns from dfdf_last_2_row_col = df.iloc[-2:,-2:] # Printing df_last_2print(df_last_2_row_col)", "e": 26062, "s": 25931, "text": null }, { "code": null, "e": 26071, "s": 26062, "text": "Output: " }, { "code": null, "e": 26096, "s": 26071, "text": "pandas-dataframe-program" }, { "code": null, "e": 26120, "s": 26096, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26134, "s": 26120, "text": "Python-pandas" }, { "code": null, "e": 26141, "s": 26134, "text": "Python" }, { "code": null, "e": 26239, "s": 26141, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26271, "s": 26239, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26327, "s": 26271, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26369, "s": 26327, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26411, "s": 26369, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26466, "s": 26411, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26488, "s": 26466, "text": "Defaultdict in Python" }, { "code": null, "e": 26527, "s": 26488, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26558, "s": 26527, "text": "Python | os.path.join() method" }, { "code": null, "e": 26587, "s": 26558, "text": "Create a directory in Python" } ]
Machine Learning on Azure with automated predictions | by Saurabh Maheshwari | Towards Data Science
I had a recent opportunity to work as a Data Science Intern at a company that used Microsoft Azure as their AI platform. For one of my projects, I had to recommend an optimal strategy (set-points) to run multiple steam boilers in parallel at a manufacturing plant. For example, given certain conditions, run boiler1 at 100% (full capacity), boiler2 at 50% and so on. The goal was to meet the plant steam demand with minimal cumulative fuel input. Due to the nature of the problem, the boiler set-points were to be updated minute-by-minute, 24/7. To achieve this, I created an end-to-end machine learning (ML) pipeline on Azure. By pipeline, I mean : Getting the data from the on-premises server to cloudCreating predictive models using cloud computing and deploying them as an API endpointAutomating predictions every minute, 24/7 and storing them back to the on-premises server (this proved to be tricky)Creating a dashboard for monitoring the performance Getting the data from the on-premises server to cloud Creating predictive models using cloud computing and deploying them as an API endpoint Automating predictions every minute, 24/7 and storing them back to the on-premises server (this proved to be tricky) Creating a dashboard for monitoring the performance While building this pipeline, I found Microsoft’s documentation to be spread across several products and less than straightforward, so I thought it would be helpful to share my workflow and provide links to appropriate resources. The workflow can be summarized in the figure below. The intent of this blog is not to discuss the ML methodology, but to understand how can one leverage different Microsoft products to create an end-to-end production pipeline. So, let’s get started. Before I start building my ML model, I needed to query relevant historical data from the on-premises SQL server and store it on the cloud. Here, Azure Data Factory v2 (ADF) comes in handy. ADF lets you connect to the on-premises database and write t-SQL queries to store data in the Azure Blob storage (blobs). The copy tool (under Move and Transform activity) of ADF lets you copy the required data. Once you have the required data stored in blob storage, you can use the Machine Learning Service Workspace (ML Services) platform that Azure provides for developing ML models. If you’re familiar with Jupyter Notebook environment, then you’ll be happy to know that ML Services lets you create Notebooks with important libraries pre-installed. So you do not need to worry about setting up the environment. Building a predictive model requires the following steps: Create your Azure Machine Learning workspace, designate the size of Virtual Machine (VM) depending on your data size and computation requirements. I worked with a dataset of dimension 3M by 13 and needed to create multiple ML models. So, I decided to use 28 GB VM with 8 cores (STANDARD_D4_V2)Next, create a Jupyter Notebook and connect to the blob storage. Once you connect, you can easily convert blob data into a pandas dataframeCreate an Azure Machine Learning compute target that will run multiple jobs in parallel to speed up training and hyperparameter tuningCreate a training script that would import libraries, take user-defined arguments, perform data transformation (if any), tune hyperparameters, log metric values, etc. Basically, it is the code that runs on the compute target to train your modelCreate an Estimator that contains the location of training script, user-defined argument values, required conda and/or pip libraries, and compute targetConfigure your hyperparameter tuning experiment using a defined hyperparameter search space, early termination policy, primary metric, maximum hyperparameter runs and maximum concurrent jobs. Additionally, provide the estimator (created in above step) that will be called with the sampled hyperparametersSubmit the experiment and visualize the hyperparameter tuning progress in real-timeLastly, the cluster gives back the best model. Retrain it using the complete dataset and register the final model to be used for deploying Create your Azure Machine Learning workspace, designate the size of Virtual Machine (VM) depending on your data size and computation requirements. I worked with a dataset of dimension 3M by 13 and needed to create multiple ML models. So, I decided to use 28 GB VM with 8 cores (STANDARD_D4_V2) Next, create a Jupyter Notebook and connect to the blob storage. Once you connect, you can easily convert blob data into a pandas dataframe Create an Azure Machine Learning compute target that will run multiple jobs in parallel to speed up training and hyperparameter tuning Create a training script that would import libraries, take user-defined arguments, perform data transformation (if any), tune hyperparameters, log metric values, etc. Basically, it is the code that runs on the compute target to train your model Create an Estimator that contains the location of training script, user-defined argument values, required conda and/or pip libraries, and compute target Configure your hyperparameter tuning experiment using a defined hyperparameter search space, early termination policy, primary metric, maximum hyperparameter runs and maximum concurrent jobs. Additionally, provide the estimator (created in above step) that will be called with the sampled hyperparameters Submit the experiment and visualize the hyperparameter tuning progress in real-time Lastly, the cluster gives back the best model. Retrain it using the complete dataset and register the final model to be used for deploying A good tutorial can be found here. Once the final model is registered with the workspace, we need to deploy it as an API endpoint, which we can query to get predictions almost instantaneously. To create the API, I used Azure Container Instances (ACI). In addition to the final model, you would need the following to successfully deploy models using ACI: Entry script: The script passes the data submitted through the deployed web service to the final model. Then, it returns the output to the clientDependencies: Create a .yml file that contains the packages your model needs to make inferencesDeployment configuration: This describes the compute resources for the API, for example, number of cores and memory Entry script: The script passes the data submitted through the deployed web service to the final model. Then, it returns the output to the client Dependencies: Create a .yml file that contains the packages your model needs to make inferences Deployment configuration: This describes the compute resources for the API, for example, number of cores and memory Once you have the final model, entry script, dependencies, and deployment configuration, you can create a docker image and deploy the model. This is the interesting part. I needed to submit the predictions to the on-premises server database minute-by-minute, 24/7, so I had to automate the prediction part. For this purpose, I created a Databricks notebook (see code examples below) that fetches the input, posts requests to the API and submits the predictions. The flow can be summarized as follows: Copy the data for prediction from on-premises server to cloud using ADFRun the databricks notebook and store predictions in blob storage or SQL database, depending on your requirements (I discuss both below)Copy the predictions from blob to on-premises SQL database using ADF Copy the data for prediction from on-premises server to cloud using ADF Run the databricks notebook and store predictions in blob storage or SQL database, depending on your requirements (I discuss both below) Copy the predictions from blob to on-premises SQL database using ADF To automate this flow every minute, you can schedule a trigger (frequency of triggering, when to start and stop, etc.) in ADF. Follow this for more details on how to add Databricks to ADF. My Databricks notebook looks like this: ## Connect to the storage account containing input datastorage_account_name = 'storage_account_name' storage_account_access_key = 'access_key' spark.conf.set("fs.azure.account.key."+storage_account_name+".blob.core.windows.net", storage_account_access_key) This will let you connect to the blob storage. Next, I connect to the specific blob and convert it to a pandas dataframe. ## To read in the blob as spark dataframedf = spark.read.csv(“wasbs://folder@storage_account_name.blob.core.windows.net/blob_name”, header = True)df_panda = df.toPandas() Now, you have your data in a pandas dataframe. Do the required data transformations, if any. Then, call the API endpoint to get predictions. ## Post requests to API end-point to get predictionsuri = ‘API_end_point’test_samples = json.dumps({‘input data feature’: values})test_samples = bytes(test_samples, encoding=’utf8')fitness_ga = requests.post(uri, test_samples, headers = {‘Content-Type’: ‘application/json’})ng_pred = [fitness_ga.json()]pd_df = spark.createDataFrame(pd.DataFrame(ng_pred)) Here pd_df is the spark dataframe containing the predictions. Finally, you can save these predictions to Azure SQL Server Database or a blob as follows. Connecting Databricks to Azure SQL Server Database ## Connecting to SQL server database from databricksjdbcHostname = ‘your_sql_server_name.database.windows.net’jdbcDatabase = ‘sql_server_database_name’ jdbcPort = 1433jdbcUsername=’your_sql_server_username’jdbcPassword=’your_sql_server_password’jdbcUrl = “jdbc:sqlserver://{0}:{1};database={2}”.format(jdbcHostname, jdbcPort, jdbcDatabase)connectionProperties = { “user” : jdbcUsername, “password” : jdbcPassword, “driver” : “com.microsoft.sqlserver.jdbc.SQLServerDriver”} ## append spark dataframe to SQL databasemode=’append’pd_df.write.jdbc(url=jdbcUrl, table=”sql_table_name”, mode=mode, properties=connectionProperties) Connecting Databricks to Azure Blob Storage ## Connecting Databricks to Azure blob storageoutput_container_path = “wasbs://folder@storage_account_name.blob.core.windows.net”output_blob_folder = output_container_path+”/temporary_blob_name” ## overwrite the blob, this creates a bunch of filespd_df.coalesce(1).write.mode(“overwrite”).option(‘header’, ‘true’).format(‘com.databricks.spark.csv’).save(output_blob_folder) ## move the required data to blob where you want predictions finallyfiles = dbutils.fs.ls(output_blob_folder)output_file = [x for x in files if x.name.startswith(‘part-’)]dbutils.fs.mv(output_file[0].path, output_container_path+’/blob_name’) You can connect the on-premises database with PowerBI once you start populating it with predictions. PowerBI lets you create awesome visualizations just by dragging and dropping fields from the database table. Once you have the required data in PowerBI, you can calculate and visualize key performance indicators (KPI) to gauge the performance of your model. For example, one of the KPI in my case could be output to input (efficiency) ratio over time. Once created, you can automatically update your dashboard as your database gets updated. In fact, while analyzing your data, PowerBI could come really handy, saving you time and coding efforts while creating publication-quality interactive graphs. Cost: There are 2 major costs involved, Virtual Machine (VM) for ML Services and Databricks cluster. Depending on the size of data and complexity of modeling, you must decide the optimum number of VM cores and memory. Similarly, choosing a larger than required Databricks cluster can result in higher costs. Also, make sure to stop your ML Services workspace and Databricks cluster when not in use to save undue additional costsLatency vs complexity of model: In my case, I had multiple ML models and predictions were needed every minute (1 min for getting the data from on-premises server to submitting the predictions back to on-premises server). Thus, I needed to choose a model with minimal prediction time without compromising the prediction accuracy. LightGBM worked well for meWhy Databricks?: I knew that I could automatically trigger a pipeline using ADF, and ADF allowed me to use Databricks notebook as an activity. Since I can write python and spark codes in Databricks, that was a natural path for me to followFrom on-premises to the cloud: It could be time-consuming to query large amounts of data from on-premises SQL database to cloud. Thus, make sure to save the queried data somewhere on the cloud. For example, if you want to retrain your model after 3 months, you would just need to query the last 3 months of additional dataDatabricks to database: I was not able to write predictions to the on-premises database directly from Databricks. But, was able to write the predictions from azure blob storage to on-premises database using ADFOutput error logs: Azure outputs error logs if something goes wrong. For example, if you encounter an error while hyperparameter tuning or deploying the model, reading the error logs could save you a lot of debugging timeXGBoost fans: XGBoost does not come pre-installed with Jupyter Notebooks in ML Services. To get XGBoost, copy-paste the following code in the jupyter notebook and it should work Cost: There are 2 major costs involved, Virtual Machine (VM) for ML Services and Databricks cluster. Depending on the size of data and complexity of modeling, you must decide the optimum number of VM cores and memory. Similarly, choosing a larger than required Databricks cluster can result in higher costs. Also, make sure to stop your ML Services workspace and Databricks cluster when not in use to save undue additional costs Latency vs complexity of model: In my case, I had multiple ML models and predictions were needed every minute (1 min for getting the data from on-premises server to submitting the predictions back to on-premises server). Thus, I needed to choose a model with minimal prediction time without compromising the prediction accuracy. LightGBM worked well for me Why Databricks?: I knew that I could automatically trigger a pipeline using ADF, and ADF allowed me to use Databricks notebook as an activity. Since I can write python and spark codes in Databricks, that was a natural path for me to follow From on-premises to the cloud: It could be time-consuming to query large amounts of data from on-premises SQL database to cloud. Thus, make sure to save the queried data somewhere on the cloud. For example, if you want to retrain your model after 3 months, you would just need to query the last 3 months of additional data Databricks to database: I was not able to write predictions to the on-premises database directly from Databricks. But, was able to write the predictions from azure blob storage to on-premises database using ADF Output error logs: Azure outputs error logs if something goes wrong. For example, if you encounter an error while hyperparameter tuning or deploying the model, reading the error logs could save you a lot of debugging time XGBoost fans: XGBoost does not come pre-installed with Jupyter Notebooks in ML Services. To get XGBoost, copy-paste the following code in the jupyter notebook and it should work import sys!conda install — yes — prefix {sys.prefix} py-xgboost!conda install -y anaconda py-xgboost It could be tough to design such a complicated pipeline from scratch, especially if you are new to Azure. Hopefully, this blog would help you get started. You can create a Microsoft Azure free account and start using most of their services. For more details on how to get started, follow this. Lastly, I would like to sincerely thank my collaborator Radek Rybicki, who helped me define the project and guided me through different stages of it. This is my first data science blog, and I am really excited to continue blogging. Please let me know if you have any comments and/or suggestions. We can discuss each aspect of the pipeline in more detail later.
[ { "code": null, "e": 618, "s": 171, "text": "I had a recent opportunity to work as a Data Science Intern at a company that used Microsoft Azure as their AI platform. For one of my projects, I had to recommend an optimal strategy (set-points) to run multiple steam boilers in parallel at a manufacturing plant. For example, given certain conditions, run boiler1 at 100% (full capacity), boiler2 at 50% and so on. The goal was to meet the plant steam demand with minimal cumulative fuel input." }, { "code": null, "e": 717, "s": 618, "text": "Due to the nature of the problem, the boiler set-points were to be updated minute-by-minute, 24/7." }, { "code": null, "e": 821, "s": 717, "text": "To achieve this, I created an end-to-end machine learning (ML) pipeline on Azure. By pipeline, I mean :" }, { "code": null, "e": 1128, "s": 821, "text": "Getting the data from the on-premises server to cloudCreating predictive models using cloud computing and deploying them as an API endpointAutomating predictions every minute, 24/7 and storing them back to the on-premises server (this proved to be tricky)Creating a dashboard for monitoring the performance" }, { "code": null, "e": 1182, "s": 1128, "text": "Getting the data from the on-premises server to cloud" }, { "code": null, "e": 1269, "s": 1182, "text": "Creating predictive models using cloud computing and deploying them as an API endpoint" }, { "code": null, "e": 1386, "s": 1269, "text": "Automating predictions every minute, 24/7 and storing them back to the on-premises server (this proved to be tricky)" }, { "code": null, "e": 1438, "s": 1386, "text": "Creating a dashboard for monitoring the performance" }, { "code": null, "e": 1668, "s": 1438, "text": "While building this pipeline, I found Microsoft’s documentation to be spread across several products and less than straightforward, so I thought it would be helpful to share my workflow and provide links to appropriate resources." }, { "code": null, "e": 1720, "s": 1668, "text": "The workflow can be summarized in the figure below." }, { "code": null, "e": 1895, "s": 1720, "text": "The intent of this blog is not to discuss the ML methodology, but to understand how can one leverage different Microsoft products to create an end-to-end production pipeline." }, { "code": null, "e": 1918, "s": 1895, "text": "So, let’s get started." }, { "code": null, "e": 2319, "s": 1918, "text": "Before I start building my ML model, I needed to query relevant historical data from the on-premises SQL server and store it on the cloud. Here, Azure Data Factory v2 (ADF) comes in handy. ADF lets you connect to the on-premises database and write t-SQL queries to store data in the Azure Blob storage (blobs). The copy tool (under Move and Transform activity) of ADF lets you copy the required data." }, { "code": null, "e": 2723, "s": 2319, "text": "Once you have the required data stored in blob storage, you can use the Machine Learning Service Workspace (ML Services) platform that Azure provides for developing ML models. If you’re familiar with Jupyter Notebook environment, then you’ll be happy to know that ML Services lets you create Notebooks with important libraries pre-installed. So you do not need to worry about setting up the environment." }, { "code": null, "e": 2781, "s": 2723, "text": "Building a predictive model requires the following steps:" }, { "code": null, "e": 4269, "s": 2781, "text": "Create your Azure Machine Learning workspace, designate the size of Virtual Machine (VM) depending on your data size and computation requirements. I worked with a dataset of dimension 3M by 13 and needed to create multiple ML models. So, I decided to use 28 GB VM with 8 cores (STANDARD_D4_V2)Next, create a Jupyter Notebook and connect to the blob storage. Once you connect, you can easily convert blob data into a pandas dataframeCreate an Azure Machine Learning compute target that will run multiple jobs in parallel to speed up training and hyperparameter tuningCreate a training script that would import libraries, take user-defined arguments, perform data transformation (if any), tune hyperparameters, log metric values, etc. Basically, it is the code that runs on the compute target to train your modelCreate an Estimator that contains the location of training script, user-defined argument values, required conda and/or pip libraries, and compute targetConfigure your hyperparameter tuning experiment using a defined hyperparameter search space, early termination policy, primary metric, maximum hyperparameter runs and maximum concurrent jobs. Additionally, provide the estimator (created in above step) that will be called with the sampled hyperparametersSubmit the experiment and visualize the hyperparameter tuning progress in real-timeLastly, the cluster gives back the best model. Retrain it using the complete dataset and register the final model to be used for deploying" }, { "code": null, "e": 4563, "s": 4269, "text": "Create your Azure Machine Learning workspace, designate the size of Virtual Machine (VM) depending on your data size and computation requirements. I worked with a dataset of dimension 3M by 13 and needed to create multiple ML models. So, I decided to use 28 GB VM with 8 cores (STANDARD_D4_V2)" }, { "code": null, "e": 4703, "s": 4563, "text": "Next, create a Jupyter Notebook and connect to the blob storage. Once you connect, you can easily convert blob data into a pandas dataframe" }, { "code": null, "e": 4838, "s": 4703, "text": "Create an Azure Machine Learning compute target that will run multiple jobs in parallel to speed up training and hyperparameter tuning" }, { "code": null, "e": 5083, "s": 4838, "text": "Create a training script that would import libraries, take user-defined arguments, perform data transformation (if any), tune hyperparameters, log metric values, etc. Basically, it is the code that runs on the compute target to train your model" }, { "code": null, "e": 5236, "s": 5083, "text": "Create an Estimator that contains the location of training script, user-defined argument values, required conda and/or pip libraries, and compute target" }, { "code": null, "e": 5541, "s": 5236, "text": "Configure your hyperparameter tuning experiment using a defined hyperparameter search space, early termination policy, primary metric, maximum hyperparameter runs and maximum concurrent jobs. Additionally, provide the estimator (created in above step) that will be called with the sampled hyperparameters" }, { "code": null, "e": 5625, "s": 5541, "text": "Submit the experiment and visualize the hyperparameter tuning progress in real-time" }, { "code": null, "e": 5764, "s": 5625, "text": "Lastly, the cluster gives back the best model. Retrain it using the complete dataset and register the final model to be used for deploying" }, { "code": null, "e": 5799, "s": 5764, "text": "A good tutorial can be found here." }, { "code": null, "e": 6016, "s": 5799, "text": "Once the final model is registered with the workspace, we need to deploy it as an API endpoint, which we can query to get predictions almost instantaneously. To create the API, I used Azure Container Instances (ACI)." }, { "code": null, "e": 6118, "s": 6016, "text": "In addition to the final model, you would need the following to successfully deploy models using ACI:" }, { "code": null, "e": 6474, "s": 6118, "text": "Entry script: The script passes the data submitted through the deployed web service to the final model. Then, it returns the output to the clientDependencies: Create a .yml file that contains the packages your model needs to make inferencesDeployment configuration: This describes the compute resources for the API, for example, number of cores and memory" }, { "code": null, "e": 6620, "s": 6474, "text": "Entry script: The script passes the data submitted through the deployed web service to the final model. Then, it returns the output to the client" }, { "code": null, "e": 6716, "s": 6620, "text": "Dependencies: Create a .yml file that contains the packages your model needs to make inferences" }, { "code": null, "e": 6832, "s": 6716, "text": "Deployment configuration: This describes the compute resources for the API, for example, number of cores and memory" }, { "code": null, "e": 6973, "s": 6832, "text": "Once you have the final model, entry script, dependencies, and deployment configuration, you can create a docker image and deploy the model." }, { "code": null, "e": 7333, "s": 6973, "text": "This is the interesting part. I needed to submit the predictions to the on-premises server database minute-by-minute, 24/7, so I had to automate the prediction part. For this purpose, I created a Databricks notebook (see code examples below) that fetches the input, posts requests to the API and submits the predictions. The flow can be summarized as follows:" }, { "code": null, "e": 7609, "s": 7333, "text": "Copy the data for prediction from on-premises server to cloud using ADFRun the databricks notebook and store predictions in blob storage or SQL database, depending on your requirements (I discuss both below)Copy the predictions from blob to on-premises SQL database using ADF" }, { "code": null, "e": 7681, "s": 7609, "text": "Copy the data for prediction from on-premises server to cloud using ADF" }, { "code": null, "e": 7818, "s": 7681, "text": "Run the databricks notebook and store predictions in blob storage or SQL database, depending on your requirements (I discuss both below)" }, { "code": null, "e": 7887, "s": 7818, "text": "Copy the predictions from blob to on-premises SQL database using ADF" }, { "code": null, "e": 8076, "s": 7887, "text": "To automate this flow every minute, you can schedule a trigger (frequency of triggering, when to start and stop, etc.) in ADF. Follow this for more details on how to add Databricks to ADF." }, { "code": null, "e": 8116, "s": 8076, "text": "My Databricks notebook looks like this:" }, { "code": null, "e": 8373, "s": 8116, "text": "## Connect to the storage account containing input datastorage_account_name = 'storage_account_name' storage_account_access_key = 'access_key' spark.conf.set(\"fs.azure.account.key.\"+storage_account_name+\".blob.core.windows.net\", storage_account_access_key)" }, { "code": null, "e": 8495, "s": 8373, "text": "This will let you connect to the blob storage. Next, I connect to the specific blob and convert it to a pandas dataframe." }, { "code": null, "e": 8666, "s": 8495, "text": "## To read in the blob as spark dataframedf = spark.read.csv(“wasbs://folder@storage_account_name.blob.core.windows.net/blob_name”, header = True)df_panda = df.toPandas()" }, { "code": null, "e": 8807, "s": 8666, "text": "Now, you have your data in a pandas dataframe. Do the required data transformations, if any. Then, call the API endpoint to get predictions." }, { "code": null, "e": 9163, "s": 8807, "text": "## Post requests to API end-point to get predictionsuri = ‘API_end_point’test_samples = json.dumps({‘input data feature’: values})test_samples = bytes(test_samples, encoding=’utf8')fitness_ga = requests.post(uri, test_samples, headers = {‘Content-Type’: ‘application/json’})ng_pred = [fitness_ga.json()]pd_df = spark.createDataFrame(pd.DataFrame(ng_pred))" }, { "code": null, "e": 9316, "s": 9163, "text": "Here pd_df is the spark dataframe containing the predictions. Finally, you can save these predictions to Azure SQL Server Database or a blob as follows." }, { "code": null, "e": 9367, "s": 9316, "text": "Connecting Databricks to Azure SQL Server Database" }, { "code": null, "e": 9992, "s": 9367, "text": "## Connecting to SQL server database from databricksjdbcHostname = ‘your_sql_server_name.database.windows.net’jdbcDatabase = ‘sql_server_database_name’ jdbcPort = 1433jdbcUsername=’your_sql_server_username’jdbcPassword=’your_sql_server_password’jdbcUrl = “jdbc:sqlserver://{0}:{1};database={2}”.format(jdbcHostname, jdbcPort, jdbcDatabase)connectionProperties = { “user” : jdbcUsername, “password” : jdbcPassword, “driver” : “com.microsoft.sqlserver.jdbc.SQLServerDriver”} ## append spark dataframe to SQL databasemode=’append’pd_df.write.jdbc(url=jdbcUrl, table=”sql_table_name”, mode=mode, properties=connectionProperties)" }, { "code": null, "e": 10036, "s": 9992, "text": "Connecting Databricks to Azure Blob Storage" }, { "code": null, "e": 10659, "s": 10036, "text": "## Connecting Databricks to Azure blob storageoutput_container_path = “wasbs://folder@storage_account_name.blob.core.windows.net”output_blob_folder = output_container_path+”/temporary_blob_name” ## overwrite the blob, this creates a bunch of filespd_df.coalesce(1).write.mode(“overwrite”).option(‘header’, ‘true’).format(‘com.databricks.spark.csv’).save(output_blob_folder) ## move the required data to blob where you want predictions finallyfiles = dbutils.fs.ls(output_blob_folder)output_file = [x for x in files if x.name.startswith(‘part-’)]dbutils.fs.mv(output_file[0].path, output_container_path+’/blob_name’)" }, { "code": null, "e": 11201, "s": 10659, "text": "You can connect the on-premises database with PowerBI once you start populating it with predictions. PowerBI lets you create awesome visualizations just by dragging and dropping fields from the database table. Once you have the required data in PowerBI, you can calculate and visualize key performance indicators (KPI) to gauge the performance of your model. For example, one of the KPI in my case could be output to input (efficiency) ratio over time. Once created, you can automatically update your dashboard as your database gets updated." }, { "code": null, "e": 11360, "s": 11201, "text": "In fact, while analyzing your data, PowerBI could come really handy, saving you time and coding efforts while creating publication-quality interactive graphs." }, { "code": null, "e": 13314, "s": 11360, "text": "Cost: There are 2 major costs involved, Virtual Machine (VM) for ML Services and Databricks cluster. Depending on the size of data and complexity of modeling, you must decide the optimum number of VM cores and memory. Similarly, choosing a larger than required Databricks cluster can result in higher costs. Also, make sure to stop your ML Services workspace and Databricks cluster when not in use to save undue additional costsLatency vs complexity of model: In my case, I had multiple ML models and predictions were needed every minute (1 min for getting the data from on-premises server to submitting the predictions back to on-premises server). Thus, I needed to choose a model with minimal prediction time without compromising the prediction accuracy. LightGBM worked well for meWhy Databricks?: I knew that I could automatically trigger a pipeline using ADF, and ADF allowed me to use Databricks notebook as an activity. Since I can write python and spark codes in Databricks, that was a natural path for me to followFrom on-premises to the cloud: It could be time-consuming to query large amounts of data from on-premises SQL database to cloud. Thus, make sure to save the queried data somewhere on the cloud. For example, if you want to retrain your model after 3 months, you would just need to query the last 3 months of additional dataDatabricks to database: I was not able to write predictions to the on-premises database directly from Databricks. But, was able to write the predictions from azure blob storage to on-premises database using ADFOutput error logs: Azure outputs error logs if something goes wrong. For example, if you encounter an error while hyperparameter tuning or deploying the model, reading the error logs could save you a lot of debugging timeXGBoost fans: XGBoost does not come pre-installed with Jupyter Notebooks in ML Services. To get XGBoost, copy-paste the following code in the jupyter notebook and it should work" }, { "code": null, "e": 13743, "s": 13314, "text": "Cost: There are 2 major costs involved, Virtual Machine (VM) for ML Services and Databricks cluster. Depending on the size of data and complexity of modeling, you must decide the optimum number of VM cores and memory. Similarly, choosing a larger than required Databricks cluster can result in higher costs. Also, make sure to stop your ML Services workspace and Databricks cluster when not in use to save undue additional costs" }, { "code": null, "e": 14100, "s": 13743, "text": "Latency vs complexity of model: In my case, I had multiple ML models and predictions were needed every minute (1 min for getting the data from on-premises server to submitting the predictions back to on-premises server). Thus, I needed to choose a model with minimal prediction time without compromising the prediction accuracy. LightGBM worked well for me" }, { "code": null, "e": 14340, "s": 14100, "text": "Why Databricks?: I knew that I could automatically trigger a pipeline using ADF, and ADF allowed me to use Databricks notebook as an activity. Since I can write python and spark codes in Databricks, that was a natural path for me to follow" }, { "code": null, "e": 14663, "s": 14340, "text": "From on-premises to the cloud: It could be time-consuming to query large amounts of data from on-premises SQL database to cloud. Thus, make sure to save the queried data somewhere on the cloud. For example, if you want to retrain your model after 3 months, you would just need to query the last 3 months of additional data" }, { "code": null, "e": 14874, "s": 14663, "text": "Databricks to database: I was not able to write predictions to the on-premises database directly from Databricks. But, was able to write the predictions from azure blob storage to on-premises database using ADF" }, { "code": null, "e": 15096, "s": 14874, "text": "Output error logs: Azure outputs error logs if something goes wrong. For example, if you encounter an error while hyperparameter tuning or deploying the model, reading the error logs could save you a lot of debugging time" }, { "code": null, "e": 15274, "s": 15096, "text": "XGBoost fans: XGBoost does not come pre-installed with Jupyter Notebooks in ML Services. To get XGBoost, copy-paste the following code in the jupyter notebook and it should work" }, { "code": null, "e": 15375, "s": 15274, "text": "import sys!conda install — yes — prefix {sys.prefix} py-xgboost!conda install -y anaconda py-xgboost" }, { "code": null, "e": 15669, "s": 15375, "text": "It could be tough to design such a complicated pipeline from scratch, especially if you are new to Azure. Hopefully, this blog would help you get started. You can create a Microsoft Azure free account and start using most of their services. For more details on how to get started, follow this." }, { "code": null, "e": 15819, "s": 15669, "text": "Lastly, I would like to sincerely thank my collaborator Radek Rybicki, who helped me define the project and guided me through different stages of it." } ]
Check if any value in an R vector is greater than or less than a certain value.
To check if any value in an R vector is greater than or less than a certain value, we can use any function. For Example, if we have a vector called V and we want to check if any value in V is greater than 100 then we can use the command given below − any(V>100) Similarly, we can check if any value is less than 100 by using the command as follows − any(V<100) Check out the below Examples to understand how it works, Following snippet creates a sample data frame − x1<-rpois(200,5) x1 The following dataframe is created [1] 4 6 5 4 5 4 8 5 4 7 6 3 1 8 7 1 4 4 6 9 3 8 3 6 4 [26] 6 2 7 3 1 3 12 3 4 2 4 1 3 6 6 5 5 5 3 3 10 4 5 2 4 [51] 4 5 5 8 5 2 3 5 3 6 10 7 4 3 4 2 10 5 4 6 4 7 5 4 2 [76] 5 6 6 7 3 5 3 5 2 5 5 4 6 3 6 12 4 6 3 4 3 6 9 3 2 [101] 4 7 4 7 9 6 8 7 5 5 2 3 9 5 4 4 5 8 7 5 5 3 5 4 4 [126] 6 7 3 5 3 5 5 10 5 9 4 3 7 9 6 2 6 10 7 4 7 6 5 2 5 [151] 7 2 0 6 6 3 9 5 3 6 5 8 2 3 9 7 6 7 3 5 4 6 6 4 8 [176] 11 7 6 7 3 1 1 4 5 4 4 2 9 5 6 5 5 0 6 3 8 6 3 3 6 Add the following code to the above snippet − x1<-rpois(200,5) any(x1>10) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x1<-rpois(200,5) any(x1>15) If you execute the above given snippet, it generates the following Output − [1] FALSE Add the following code to the above snippet − x1<-rpois(200,5) any(x1<1) If you execute the above given snippet, it generates the following Output − [1] TRUE Following snippet creates a sample data frame − x2<-rpois(200,50) x2 The following dataframe is created [1] 50 45 50 49 55 51 55 44 54 53 43 44 50 61 52 41 43 47 37 46 59 41 50 48 49 [26] 55 50 56 48 60 53 56 41 64 44 64 47 48 52 50 38 61 56 46 40 45 52 54 46 54 [51] 42 47 47 39 44 49 27 51 55 49 56 56 54 52 48 51 53 42 54 48 46 55 51 42 63 [76] 51 41 46 43 45 49 51 43 49 40 52 59 50 61 54 52 61 50 57 59 50 58 50 47 45 [101] 37 47 52 49 51 49 43 60 63 47 48 46 51 48 66 50 51 40 55 50 53 39 52 43 39 [126] 50 46 64 48 47 46 43 68 45 54 47 44 44 47 40 52 59 48 63 40 42 56 54 48 48 [151] 44 46 49 53 57 44 37 49 49 52 51 54 52 49 54 54 47 58 34 62 57 44 37 47 48 [176] 59 47 31 52 55 45 50 44 57 38 53 55 36 50 52 56 46 51 43 57 54 62 46 43 57 Add the following code to the above snippet − x2<-rpois(200,50) any(x2>70) If you execute the above given snippet, it generates the following Output − [1] FALSE Add the following code to the above snippet − x2<-rpois(200,50) any(x2<30) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x2<-rpois(200,50) any(x2<20) If you execute the above given snippet, it generates the following Output − [1] FALSE Following snippet creates a sample data frame − x3<-round(rnorm(200),0) x3 The following dataframe is created [1] 0 1 0 1 -2 -2 0 2 -3 -1 -1 -1 -1 1 0 1 -1 0 -2 -2 1 -2 -1 -1 0 [26] 0 1 0 0 0 -1 1 1 0 0 -1 -2 0 1 0 0 1 1 0 0 0 -1 0 -1 - 1 [51] 0 0 0 2 0 -1 0 0 -1 0 -2 0 -1 1 1 0 -1 1 0 0 0 0 0 0 0 [76] 1 -1 -1 0 1 0 0 0 1 1 0 0 1 -1 2 -1 0 2 -1 -1 0 1 1 -2 - 1 [101] -1 -1 0 -1 0 0 -1 -1 -1 1 -1 3 0 1 0 1 -1 2 0 -1 0 0 1 0 1 [126] -1 1 0 0 2 0 0 -2 0 -1 0 0 1 -1 0 0 0 1 -2 2 0 1 -1 0 - 1 [151] -2 0 0 -2 0 2 1 0 -3 -1 -2 2 2 1 -1 0 0 0 0 0 -1 0 0 -1 1 [176] 3 1 1 0 0 0 0 -2 1 0 0 0 0 1 -1 0 1 -1 -1 -1 0 1 -1 2 - 1 Add the following code to the above snippet − x3<-round(rnorm(200),0) any(x3>3) If you execute the above given snippet, it generates the following Output − [1] FALSE Following snippet creates a sample data frame − x4<-rpois(200,100) x4 The following dataframe is created [1] 108 107 99 114 104 95 121 83 94 100 103 106 102 99 95 90 93 105 [19] 93 89 115 109 113 109 99 95 90 96 112 104 107 119 107 90 105 87 [37] 92 101 97 108 92 103 98 93 135 88 115 101 106 102 99 106 114 121 [55] 92 116 101 103 93 105 102 94 98 95 103 86 101 111 95 97 102 100 [73] 106 106 90 82 80 129 104 86 103 104 109 97 103 95 107 122 107 91 [91] 81 96 94 94 106 105 100 86 101 99 105 103 89 115 101 97 121 105 [109] 102 101 107 99 101 101 106 110 110 94 117 111 99 103 96 103 90 89 [127] 85 103 113 88 82 102 92 96 100 85 102 102 109 102 99 96 91 104 [145] 114 88 122 111 104 96 98 92 98 100 94 107 92 97 91 109 86 118 [163] 90 98 105 113 100 105 122 94 102 84 97 114 97 117 104 106 108 99 [181] 88 107 117 108 90 117 112 98 88 104 82 100 86 94 94 103 94 98 [199] 101 100 Add the following code to the above snippet − x4<-rpois(200,100) any(x4>125) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x4<-rpois(200,100) any(x4>130) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x4<-rpois(200,100) any(x4>135) If you execute the above given snippet, it generates the following Output − [1] FALSE Add the following code to the above snippet − x4<-rpois(200,100) any(x4<95) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x4<-rpois(200,100) any(x4<85) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x4<-rpois(200,100) any(x4<75) If you execute the above given snippet, it generates the following Output − [1] FALSE Following snippet creates a sample data frame − x5<-rpois(200,1000) x5 The following dataframe is created [1] 1021 1007 1010 968 1029 989 994 946 996 1011 1023 994 985 1005 1013 [16] 1021 930 975 998 984 1030 946 1018 1066 1000 1016 976 979 1023 992 [31] 1005 1004 970 992 978 991 1047 952 979 983 1003 1039 989 986 1026 [46] 986 1013 1017 990 983 953 970 1021 1037 993 986 981 982 1028 1076 [61] 990 1055 1030 998 1015 984 977 940 1067 1015 921 1028 1017 949 993 [76] 979 1024 1052 988 957 1034 949 991 1055 1075 962 985 1008 890 962 [91] 984 1030 967 977 957 968 992 981 958 1022 950 1026 1034 987 1036 [106] 1040 1030 1033 969 991 1022 964 1044 1015 979 960 1013 1039 982 988 [121] 964 985 1005 941 966 985 1009 1060 992 975 1026 980 994 1034 1019 [136] 963 1025 1032 989 1029 998 1033 1037 1068 1002 1031 1064 1025 973 1006 [151] 976 998 1014 999 960 1010 938 999 1015 1007 994 1007 967 1017 966 [166] 1030 967 1002 1036 946 997 973 937 1018 1008 1007 943 1002 1090 981 [181] 949 1028 1003 1056 966 966 1018 967 986 1052 931 1022 1014 970 1012 [196] 991 992 994 1003 992 Add the following code to the above snippet − x5<-rpois(200,1000) any(x5<950) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x5<-rpois(200,1000) any(x5<925) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x5<-rpois(200,1000) any(x5<900) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x5<-rpois(200,1000) any(x5<850) If you execute the above given snippet, it generates the following Output − [1] FALSE Add the following code to the above snippet − x5<-rpois(200,1000) any(x5>1050) If you execute the above given snippet, it generates the following Output − [1] TRUE Add the following code to the above snippet − x5<-rpois(200,1000) any(x5>1100) If you execute the above given snippet, it generates the following Output − [1] FALSE
[ { "code": null, "e": 1170, "s": 1062, "text": "To check if any value in an R vector is greater than or less than a certain value, we can\nuse any function." }, { "code": null, "e": 1313, "s": 1170, "text": "For Example, if we have a vector called V and we want to check if any value in V is\ngreater than 100 then we can use the command given below −" }, { "code": null, "e": 1324, "s": 1313, "text": "any(V>100)" }, { "code": null, "e": 1412, "s": 1324, "text": "Similarly, we can check if any value is less than 100 by using the command as follows −" }, { "code": null, "e": 1424, "s": 1412, "text": "any(V<100)\n" }, { "code": null, "e": 1481, "s": 1424, "text": "Check out the below Examples to understand how it works," }, { "code": null, "e": 1529, "s": 1481, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 1549, "s": 1529, "text": "x1<-rpois(200,5)\nx1" }, { "code": null, "e": 1584, "s": 1549, "text": "The following dataframe is created" }, { "code": null, "e": 2035, "s": 1584, "text": "[1] 4 6 5 4 5 4 8 5 4 7 6 3 1 8 7 1 4 4 6 9 3 8 3 6 4\n[26] 6 2 7 3 1 3 12 3 4 2 4 1 3 6 6 5 5 5 3 3 10 4 5 2\n4\n[51] 4 5 5 8 5 2 3 5 3 6 10 7 4 3 4 2 10 5 4 6 4 7 5 4\n2\n[76] 5 6 6 7 3 5 3 5 2 5 5 4 6 3 6 12 4 6 3 4 3 6 9 3\n2\n[101] 4 7 4 7 9 6 8 7 5 5 2 3 9 5 4 4 5 8 7 5 5 3 5 4\n4\n[126] 6 7 3 5 3 5 5 10 5 9 4 3 7 9 6 2 6 10 7 4 7 6 5 2\n5\n[151] 7 2 0 6 6 3 9 5 3 6 5 8 2 3 9 7 6 7 3 5 4 6 6 4\n8\n[176] 11 7 6 7 3 1 1 4 5 4 4 2 9 5 6 5 5 0 6 3 8 6 3 3\n6" }, { "code": null, "e": 2081, "s": 2035, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 2109, "s": 2081, "text": "x1<-rpois(200,5)\nany(x1>10)" }, { "code": null, "e": 2185, "s": 2109, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 2195, "s": 2185, "text": "[1] TRUE\n" }, { "code": null, "e": 2241, "s": 2195, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 2269, "s": 2241, "text": "x1<-rpois(200,5)\nany(x1>15)" }, { "code": null, "e": 2345, "s": 2269, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 2356, "s": 2345, "text": "[1] FALSE\n" }, { "code": null, "e": 2402, "s": 2356, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 2429, "s": 2402, "text": "x1<-rpois(200,5)\nany(x1<1)" }, { "code": null, "e": 2505, "s": 2429, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 2515, "s": 2505, "text": "[1] TRUE\n" }, { "code": null, "e": 2563, "s": 2515, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 2584, "s": 2563, "text": "x2<-rpois(200,50)\nx2" }, { "code": null, "e": 2619, "s": 2584, "text": "The following dataframe is created" }, { "code": null, "e": 3262, "s": 2619, "text": "[1] 50 45 50 49 55 51 55 44 54 53 43 44 50 61 52 41 43 47 37 46 59 41 50 48\n49\n[26] 55 50 56 48 60 53 56 41 64 44 64 47 48 52 50 38 61 56 46 40 45 52 54 46\n54\n[51] 42 47 47 39 44 49 27 51 55 49 56 56 54 52 48 51 53 42 54 48 46 55 51 42\n63\n[76] 51 41 46 43 45 49 51 43 49 40 52 59 50 61 54 52 61 50 57 59 50 58 50 47\n45\n[101] 37 47 52 49 51 49 43 60 63 47 48 46 51 48 66 50 51 40 55 50 53 39 52 43\n39\n[126] 50 46 64 48 47 46 43 68 45 54 47 44 44 47 40 52 59 48 63 40 42 56 54 48\n48\n[151] 44 46 49 53 57 44 37 49 49 52 51 54 52 49 54 54 47 58 34 62 57 44 37 47\n48\n[176] 59 47 31 52 55 45 50 44 57 38 53 55 36 50 52 56 46 51 43 57 54 62 46 43\n57" }, { "code": null, "e": 3308, "s": 3262, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 3337, "s": 3308, "text": "x2<-rpois(200,50)\nany(x2>70)" }, { "code": null, "e": 3413, "s": 3337, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 3424, "s": 3413, "text": "[1] FALSE\n" }, { "code": null, "e": 3470, "s": 3424, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 3499, "s": 3470, "text": "x2<-rpois(200,50)\nany(x2<30)" }, { "code": null, "e": 3575, "s": 3499, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 3585, "s": 3575, "text": "[1] TRUE\n" }, { "code": null, "e": 3631, "s": 3585, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 3660, "s": 3631, "text": "x2<-rpois(200,50)\nany(x2<20)" }, { "code": null, "e": 3736, "s": 3660, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 3747, "s": 3736, "text": "[1] FALSE\n" }, { "code": null, "e": 3795, "s": 3747, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 3823, "s": 3795, "text": "x3<-round(rnorm(200),0)\nx3\n" }, { "code": null, "e": 3858, "s": 3823, "text": "The following dataframe is created" }, { "code": null, "e": 4368, "s": 3858, "text": "[1] 0 1 0 1 -2 -2 0 2 -3 -1 -1 -1 -1 1 0 1 -1 0 -2 -2 1 -2 -1 -1\n0\n[26] 0 1 0 0 0 -1 1 1 0 0 -1 -2 0 1 0 0 1 1 0 0 0 -1 0 -1 -\n1\n[51] 0 0 0 2 0 -1 0 0 -1 0 -2 0 -1 1 1 0 -1 1 0 0 0 0 0 0\n0\n[76] 1 -1 -1 0 1 0 0 0 1 1 0 0 1 -1 2 -1 0 2 -1 -1 0 1 1 -2 -\n1\n[101] -1 -1 0 -1 0 0 -1 -1 -1 1 -1 3 0 1 0 1 -1 2 0 -1 0 0 1 0\n1\n[126] -1 1 0 0 2 0 0 -2 0 -1 0 0 1 -1 0 0 0 1 -2 2 0 1 -1 0 -\n1\n[151] -2 0 0 -2 0 2 1 0 -3 -1 -2 2 2 1 -1 0 0 0 0 0 -1 0 0 -1\n1\n[176] 3 1 1 0 0 0 0 -2 1 0 0 0 0 1 -1 0 1 -1 -1 -1 0 1 -1 2 -\n1" }, { "code": null, "e": 4414, "s": 4368, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 4448, "s": 4414, "text": "x3<-round(rnorm(200),0)\nany(x3>3)" }, { "code": null, "e": 4524, "s": 4448, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 4535, "s": 4524, "text": "[1] FALSE\n" }, { "code": null, "e": 4583, "s": 4535, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 4605, "s": 4583, "text": "x4<-rpois(200,100)\nx4" }, { "code": null, "e": 4640, "s": 4605, "text": "The following dataframe is created" }, { "code": null, "e": 5417, "s": 4640, "text": "[1] 108 107 99 114 104 95 121 83 94 100 103 106 102 99 95 90 93 105\n[19] 93 89 115 109 113 109 99 95 90 96 112 104 107 119 107 90 105 87\n[37] 92 101 97 108 92 103 98 93 135 88 115 101 106 102 99 106 114 121\n[55] 92 116 101 103 93 105 102 94 98 95 103 86 101 111 95 97 102 100\n[73] 106 106 90 82 80 129 104 86 103 104 109 97 103 95 107 122 107 91\n[91] 81 96 94 94 106 105 100 86 101 99 105 103 89 115 101 97 121 105\n[109] 102 101 107 99 101 101 106 110 110 94 117 111 99 103 96 103 90 89\n[127] 85 103 113 88 82 102 92 96 100 85 102 102 109 102 99 96 91 104\n[145] 114 88 122 111 104 96 98 92 98 100 94 107 92 97 91 109 86 118\n[163] 90 98 105 113 100 105 122 94 102 84 97 114 97 117 104 106 108 99\n[181] 88 107 117 108 90 117 112 98 88 104 82 100 86 94 94 103 94 98\n[199] 101 100" }, { "code": null, "e": 5463, "s": 5417, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 5494, "s": 5463, "text": "x4<-rpois(200,100)\nany(x4>125)" }, { "code": null, "e": 5570, "s": 5494, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 5580, "s": 5570, "text": "[1] TRUE\n" }, { "code": null, "e": 5626, "s": 5580, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 5657, "s": 5626, "text": "x4<-rpois(200,100)\nany(x4>130)" }, { "code": null, "e": 5733, "s": 5657, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 5743, "s": 5733, "text": "[1] TRUE\n" }, { "code": null, "e": 5789, "s": 5743, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 5820, "s": 5789, "text": "x4<-rpois(200,100)\nany(x4>135)" }, { "code": null, "e": 5896, "s": 5820, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 5907, "s": 5896, "text": "[1] FALSE\n" }, { "code": null, "e": 5953, "s": 5907, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 5983, "s": 5953, "text": "x4<-rpois(200,100)\nany(x4<95)" }, { "code": null, "e": 6059, "s": 5983, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 6069, "s": 6059, "text": "[1] TRUE\n" }, { "code": null, "e": 6115, "s": 6069, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 6145, "s": 6115, "text": "x4<-rpois(200,100)\nany(x4<85)" }, { "code": null, "e": 6221, "s": 6145, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 6231, "s": 6221, "text": "[1] TRUE\n" }, { "code": null, "e": 6277, "s": 6231, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 6307, "s": 6277, "text": "x4<-rpois(200,100)\nany(x4<75)" }, { "code": null, "e": 6383, "s": 6307, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 6394, "s": 6383, "text": "[1] FALSE\n" }, { "code": null, "e": 6442, "s": 6394, "text": "Following snippet creates a sample data frame −" }, { "code": null, "e": 6466, "s": 6442, "text": "x5<-rpois(200,1000)\nx5\n" }, { "code": null, "e": 6501, "s": 6466, "text": "The following dataframe is created" }, { "code": null, "e": 7470, "s": 6501, "text": "[1] 1021 1007 1010 968 1029 989 994 946 996 1011 1023 994 985 1005\n1013\n[16] 1021 930 975 998 984 1030 946 1018 1066 1000 1016 976 979 1023\n992\n[31] 1005 1004 970 992 978 991 1047 952 979 983 1003 1039 989 986\n1026\n[46] 986 1013 1017 990 983 953 970 1021 1037 993 986 981 982 1028\n1076\n[61] 990 1055 1030 998 1015 984 977 940 1067 1015 921 1028 1017 949\n993\n[76] 979 1024 1052 988 957 1034 949 991 1055 1075 962 985 1008 890\n962\n[91] 984 1030 967 977 957 968 992 981 958 1022 950 1026 1034 987\n1036\n[106] 1040 1030 1033 969 991 1022 964 1044 1015 979 960 1013 1039 982\n988\n[121] 964 985 1005 941 966 985 1009 1060 992 975 1026 980 994 1034\n1019\n[136] 963 1025 1032 989 1029 998 1033 1037 1068 1002 1031 1064 1025 973\n1006\n[151] 976 998 1014 999 960 1010 938 999 1015 1007 994 1007 967 1017\n966\n[166] 1030 967 1002 1036 946 997 973 937 1018 1008 1007 943 1002 1090\n981\n[181] 949 1028 1003 1056 966 966 1018 967 986 1052 931 1022 1014 970\n1012\n[196] 991 992 994 1003 992" }, { "code": null, "e": 7516, "s": 7470, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 7548, "s": 7516, "text": "x5<-rpois(200,1000)\nany(x5<950)" }, { "code": null, "e": 7624, "s": 7548, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 7634, "s": 7624, "text": "[1] TRUE\n" }, { "code": null, "e": 7680, "s": 7634, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 7712, "s": 7680, "text": "x5<-rpois(200,1000)\nany(x5<925)" }, { "code": null, "e": 7788, "s": 7712, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 7798, "s": 7788, "text": "[1] TRUE\n" }, { "code": null, "e": 7844, "s": 7798, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 7876, "s": 7844, "text": "x5<-rpois(200,1000)\nany(x5<900)" }, { "code": null, "e": 7952, "s": 7876, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 7962, "s": 7952, "text": "[1] TRUE\n" }, { "code": null, "e": 8008, "s": 7962, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 8040, "s": 8008, "text": "x5<-rpois(200,1000)\nany(x5<850)" }, { "code": null, "e": 8116, "s": 8040, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 8127, "s": 8116, "text": "[1] FALSE\n" }, { "code": null, "e": 8173, "s": 8127, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 8206, "s": 8173, "text": "x5<-rpois(200,1000)\nany(x5>1050)" }, { "code": null, "e": 8282, "s": 8206, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 8292, "s": 8282, "text": "[1] TRUE\n" }, { "code": null, "e": 8338, "s": 8292, "text": "Add the following code to the above snippet −" }, { "code": null, "e": 8371, "s": 8338, "text": "x5<-rpois(200,1000)\nany(x5>1100)" }, { "code": null, "e": 8447, "s": 8371, "text": "If you execute the above given snippet, it generates the following Output −" }, { "code": null, "e": 8458, "s": 8447, "text": "[1] FALSE\n" } ]
How to use x-grid-data-generator Module in ReactJS ? - GeeksforGeeks
26 Apr, 2021 Whenever we want to generate some data and build demos for the grid Component, we can use the x-grid-data-generator module. It has a large variety of data set to play around. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can use the following approach in ReactJS to use the x-grid-data-generator module. Approach: Follow these simple steps in order to use the x-grid-data-generator module in ReactJS. In the following example, we have imported the useDemoData function from this module and then used a common data set from this function by passing the DataSet name along with rowLength and maxColumns attribute. And after that, we have passed the data object to our DataGrid Component for displaying it to the user. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid npm install @material-ui/x-grid-data-generator Step 3: After creating the ReactJS application, Install the material-ui module using the following command: npm install @material-ui/data-grid npm install @material-ui/x-grid-data-generator Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import * as React from 'react';import { DataGrid } from '@material-ui/data-grid';import { useDemoData } from '@material-ui/x-grid-data-generator'; export default function App() { const { data } = useDemoData({ dataSet: 'Commodity', rowLength: 1000, maxColumns: 6, }); return ( <div style={{ height: 500, width: '80%' }}> <h4> How to use fetch Random Data Set in DataGrid Component in ReactJS? </h4> <DataGrid {...data}/> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://www.npmjs.com/package/@material-ui/x-grid-data-generator React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set background images in ReactJS ? How to create a table in ReactJS ? ReactJS useNavigate() Hook How to navigate on path by button click in react router ? React-Router Hooks Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 24826, "s": 24798, "text": "\n26 Apr, 2021" }, { "code": null, "e": 25185, "s": 24826, "text": "Whenever we want to generate some data and build demos for the grid Component, we can use the x-grid-data-generator module. It has a large variety of data set to play around. DataGrid Component helps in displaying the information in a grid-like format of rows and columns. We can use the following approach in ReactJS to use the x-grid-data-generator module." }, { "code": null, "e": 25597, "s": 25185, "text": "Approach: Follow these simple steps in order to use the x-grid-data-generator module in ReactJS. In the following example, we have imported the useDemoData function from this module and then used a common data set from this function by passing the DataSet name along with rowLength and maxColumns attribute. And after that, we have passed the data object to our DataGrid Component for displaying it to the user." }, { "code": null, "e": 25647, "s": 25597, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25742, "s": 25647, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 25806, "s": 25742, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25838, "s": 25806, "text": "npx create-react-app foldername" }, { "code": null, "e": 25951, "s": 25838, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 26051, "s": 25951, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 26065, "s": 26051, "text": "cd foldername" }, { "code": null, "e": 26254, "s": 26065, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:npm install @material-ui/data-grid\nnpm install @material-ui/x-grid-data-generator" }, { "code": null, "e": 26362, "s": 26254, "text": "Step 3: After creating the ReactJS application, Install the material-ui module using the following command:" }, { "code": null, "e": 26444, "s": 26362, "text": "npm install @material-ui/data-grid\nnpm install @material-ui/x-grid-data-generator" }, { "code": null, "e": 26496, "s": 26444, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 26514, "s": 26496, "text": "Project Structure" }, { "code": null, "e": 26644, "s": 26514, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26651, "s": 26644, "text": "App.js" }, { "code": "import * as React from 'react';import { DataGrid } from '@material-ui/data-grid';import { useDemoData } from '@material-ui/x-grid-data-generator'; export default function App() { const { data } = useDemoData({ dataSet: 'Commodity', rowLength: 1000, maxColumns: 6, }); return ( <div style={{ height: 500, width: '80%' }}> <h4> How to use fetch Random Data Set in DataGrid Component in ReactJS? </h4> <DataGrid {...data}/> </div> );}", "e": 27125, "s": 26651, "text": null }, { "code": null, "e": 27238, "s": 27125, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 27248, "s": 27238, "text": "npm start" }, { "code": null, "e": 27347, "s": 27248, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27423, "s": 27347, "text": "Reference: https://www.npmjs.com/package/@material-ui/x-grid-data-generator" }, { "code": null, "e": 27439, "s": 27423, "text": "React-Questions" }, { "code": null, "e": 27447, "s": 27439, "text": "ReactJS" }, { "code": null, "e": 27464, "s": 27447, "text": "Web Technologies" }, { "code": null, "e": 27562, "s": 27464, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27604, "s": 27562, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27639, "s": 27604, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27666, "s": 27639, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27724, "s": 27666, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27743, "s": 27724, "text": "React-Router Hooks" }, { "code": null, "e": 27785, "s": 27743, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27818, "s": 27785, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27868, "s": 27818, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27930, "s": 27868, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
5 Examples to Learn Date and Time Manipulation with Python Pandas | by Soner Yıldırım | Towards Data Science
We often deal with dates and times in data science. If you are working with time-series data, they are always a part of your work. Pandas is highly efficient and practical with regard to manipulating dates and times. In this article, we will go over 5 examples for solving some of the common date and time manipulation operations. Don’t forget to subscribe if you’d like to get an email whenever I publish a new article. Let’s start by creating a sample DataFrame that contains dates. import pandas as pddf = pd.DataFrame({ "Date": pd.date_range(start="2021-12-28", periods=5, freq="D"), "Measurement": [1, 10, 25, 7, 12]}) The DateOffset function can be used for adding a specific length of duration to dates. Let’s create a new column by adding 6 months to the existing date column. df["Date2"] = df["Date"] + pd.DateOffset(months=6) The following line of code adds 1 year to the existing date column. df["Date2"] = df["Date"] + pd.DateOffset(years=1) It is important to note that the data type of values in the date column is datetime. Thus, we can also add time intervals. df["Date"] + pd.DateOffset(hours=2)# output0 2021-12-28 02:00:001 2021-12-29 02:00:002 2021-12-30 02:00:003 2021-12-31 02:00:004 2022-01-01 02:00:00Name: Date, dtype: datetime64[ns] If you need to do subtraction, just change the “+” sign to “-” or use a negative value inside the function. We can use the Timedelta function for adding dates and times as well. Its syntax is slightly different than the syntax of the DateOffset function. df["Date"] + pd.Timedelta(3, unit="day")# output0 2021-12-311 2022-01-012 2022-01-023 2022-01-034 2022-01-04Name: Date, dtype: datetime64[ns] The Timedelta function also accepts strings for specifying the duration to be added. The following line of code does the same operation as above. df["Date"] + pd.Timedelta("3 days") A datetime object contains several pieces of information such as year, month, day, week, hour, microsecond, and so on. We sometimes need a particular piece of information. For instance, we can extract month from a date as below: df["Date"].dt.month# output0 121 122 123 124 1Name: Date, dtype: int64 The year and day methods return the year and day part of a date, respectively. In retail analytics, the day of the week is a significant piece of information for analysis and modeling. The dayofweek method can be used to get this information from a date. df["Date"].dt.dayofweek# output0 11 22 33 44 5Name: Date, dtype: int64 All these methods are available under the dt accessor so make sure to write “dt” before the name of the method. The isocalendar function returns a DataFrame with year, week, and day of week. Thus, it is a quick way of extracting multiple pieces of information in a single operation. For instance, we can add the year, week, and day of week columns to our initial DataFrame as below: df = pd.concat([df, df["Date"].dt.isocalendar()], axis=1) The part that creates the additional columns is: df["Date"].dt.isocalendar() We use the concat function to combine these columns with the original DataFrame. The difference between two dates or times can be of great importance in some tasks. For instance, we might need to calculate the time between consecutive measurements in a process. The subtraction operation with two datetime objects gives us the difference in days. df["Diff"] = df["Date2"] - df["Date"] The data type of the diff column is timedelta so we can get the number of days using the days method. df["Diff"].dt.days# output0 3651 3652 3653 3654 365Name: Diff, dtype: int64 We can also divide it by a timedelta object of 1 day to get the number of days. df["Diff"] / pd.Timedelta(days=1)# output0 365.01 365.02 365.03 365.04 365.0Name: Diff, dtype: float64 If you want to convert the difference to months or years, use the timedelta of NumPy because Pandas cannot construct a Timedelta from months or years. import numpy as npdf["Diff"] / np.timedelta64(1, 'M')# output0 11.9920331 11.9920332 11.9920333 11.9920334 11.992033Name: Diff, dtype: float64 We have learned Pandas functions and methods for solving some of the common tasks in date and time manipulation. Don’t forget to subscribe if you’d like to get an email whenever I publish a new article. You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you do so using the following link, I will receive a portion of your membership fee at no additional cost to you. sonery.medium.com Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 303, "s": 172, "text": "We often deal with dates and times in data science. If you are working with time-series data, they are always a part of your work." }, { "code": null, "e": 503, "s": 303, "text": "Pandas is highly efficient and practical with regard to manipulating dates and times. In this article, we will go over 5 examples for solving some of the common date and time manipulation operations." }, { "code": null, "e": 593, "s": 503, "text": "Don’t forget to subscribe if you’d like to get an email whenever I publish a new article." }, { "code": null, "e": 657, "s": 593, "text": "Let’s start by creating a sample DataFrame that contains dates." }, { "code": null, "e": 802, "s": 657, "text": "import pandas as pddf = pd.DataFrame({ \"Date\": pd.date_range(start=\"2021-12-28\", periods=5, freq=\"D\"), \"Measurement\": [1, 10, 25, 7, 12]})" }, { "code": null, "e": 889, "s": 802, "text": "The DateOffset function can be used for adding a specific length of duration to dates." }, { "code": null, "e": 963, "s": 889, "text": "Let’s create a new column by adding 6 months to the existing date column." }, { "code": null, "e": 1014, "s": 963, "text": "df[\"Date2\"] = df[\"Date\"] + pd.DateOffset(months=6)" }, { "code": null, "e": 1082, "s": 1014, "text": "The following line of code adds 1 year to the existing date column." }, { "code": null, "e": 1132, "s": 1082, "text": "df[\"Date2\"] = df[\"Date\"] + pd.DateOffset(years=1)" }, { "code": null, "e": 1255, "s": 1132, "text": "It is important to note that the data type of values in the date column is datetime. Thus, we can also add time intervals." }, { "code": null, "e": 1447, "s": 1255, "text": "df[\"Date\"] + pd.DateOffset(hours=2)# output0 2021-12-28 02:00:001 2021-12-29 02:00:002 2021-12-30 02:00:003 2021-12-31 02:00:004 2022-01-01 02:00:00Name: Date, dtype: datetime64[ns]" }, { "code": null, "e": 1555, "s": 1447, "text": "If you need to do subtraction, just change the “+” sign to “-” or use a negative value inside the function." }, { "code": null, "e": 1702, "s": 1555, "text": "We can use the Timedelta function for adding dates and times as well. Its syntax is slightly different than the syntax of the DateOffset function." }, { "code": null, "e": 1854, "s": 1702, "text": "df[\"Date\"] + pd.Timedelta(3, unit=\"day\")# output0 2021-12-311 2022-01-012 2022-01-023 2022-01-034 2022-01-04Name: Date, dtype: datetime64[ns]" }, { "code": null, "e": 2000, "s": 1854, "text": "The Timedelta function also accepts strings for specifying the duration to be added. The following line of code does the same operation as above." }, { "code": null, "e": 2036, "s": 2000, "text": "df[\"Date\"] + pd.Timedelta(\"3 days\")" }, { "code": null, "e": 2155, "s": 2036, "text": "A datetime object contains several pieces of information such as year, month, day, week, hour, microsecond, and so on." }, { "code": null, "e": 2265, "s": 2155, "text": "We sometimes need a particular piece of information. For instance, we can extract month from a date as below:" }, { "code": null, "e": 2352, "s": 2265, "text": "df[\"Date\"].dt.month# output0 121 122 123 124 1Name: Date, dtype: int64" }, { "code": null, "e": 2431, "s": 2352, "text": "The year and day methods return the year and day part of a date, respectively." }, { "code": null, "e": 2607, "s": 2431, "text": "In retail analytics, the day of the week is a significant piece of information for analysis and modeling. The dayofweek method can be used to get this information from a date." }, { "code": null, "e": 2693, "s": 2607, "text": "df[\"Date\"].dt.dayofweek# output0 11 22 33 44 5Name: Date, dtype: int64" }, { "code": null, "e": 2805, "s": 2693, "text": "All these methods are available under the dt accessor so make sure to write “dt” before the name of the method." }, { "code": null, "e": 2976, "s": 2805, "text": "The isocalendar function returns a DataFrame with year, week, and day of week. Thus, it is a quick way of extracting multiple pieces of information in a single operation." }, { "code": null, "e": 3076, "s": 2976, "text": "For instance, we can add the year, week, and day of week columns to our initial DataFrame as below:" }, { "code": null, "e": 3134, "s": 3076, "text": "df = pd.concat([df, df[\"Date\"].dt.isocalendar()], axis=1)" }, { "code": null, "e": 3183, "s": 3134, "text": "The part that creates the additional columns is:" }, { "code": null, "e": 3211, "s": 3183, "text": "df[\"Date\"].dt.isocalendar()" }, { "code": null, "e": 3292, "s": 3211, "text": "We use the concat function to combine these columns with the original DataFrame." }, { "code": null, "e": 3473, "s": 3292, "text": "The difference between two dates or times can be of great importance in some tasks. For instance, we might need to calculate the time between consecutive measurements in a process." }, { "code": null, "e": 3558, "s": 3473, "text": "The subtraction operation with two datetime objects gives us the difference in days." }, { "code": null, "e": 3596, "s": 3558, "text": "df[\"Diff\"] = df[\"Date2\"] - df[\"Date\"]" }, { "code": null, "e": 3698, "s": 3596, "text": "The data type of the diff column is timedelta so we can get the number of days using the days method." }, { "code": null, "e": 3789, "s": 3698, "text": "df[\"Diff\"].dt.days# output0 3651 3652 3653 3654 365Name: Diff, dtype: int64" }, { "code": null, "e": 3869, "s": 3789, "text": "We can also divide it by a timedelta object of 1 day to get the number of days." }, { "code": null, "e": 3987, "s": 3869, "text": "df[\"Diff\"] / pd.Timedelta(days=1)# output0 365.01 365.02 365.03 365.04 365.0Name: Diff, dtype: float64" }, { "code": null, "e": 4138, "s": 3987, "text": "If you want to convert the difference to months or years, use the timedelta of NumPy because Pandas cannot construct a Timedelta from months or years." }, { "code": null, "e": 4296, "s": 4138, "text": "import numpy as npdf[\"Diff\"] / np.timedelta64(1, 'M')# output0 11.9920331 11.9920332 11.9920333 11.9920334 11.992033Name: Diff, dtype: float64" }, { "code": null, "e": 4409, "s": 4296, "text": "We have learned Pandas functions and methods for solving some of the common tasks in date and time manipulation." }, { "code": null, "e": 4499, "s": 4409, "text": "Don’t forget to subscribe if you’d like to get an email whenever I publish a new article." }, { "code": null, "e": 4709, "s": 4499, "text": "You can become a Medium member to unlock full access to my writing, plus the rest of Medium. If you do so using the following link, I will receive a portion of your membership fee at no additional cost to you." }, { "code": null, "e": 4727, "s": 4709, "text": "sonery.medium.com" } ]
Find Nth term of the series 5, 13, 25, 41, 61... - GeeksforGeeks
15 Mar, 2021 Given a number N. The task is to write a program to find the Nth term in the below series: 5, 13, 25, 41, 61... Examples: Input : 3 Output : 25 For N = 3 Nth term = 3*3 + (3+1)*(3+1) = 25 Input : 5 Output : 61 On observing carefully, the Nth term of the given series can be generalised as: Nth term = N2 + (N+1)2 Below is the implementation of the above approach: C++ Java Python 3 C# PHP Javascript // CPP program to find N-th term of the series:// 5, 13, 25, 41, 61...#include <iostream>using namespace std; // calculate Nth term of seriesint nthTerm(int N){ return N * N + (N + 1) * (N + 1);} // Driver Functionint main(){ int N = 3; cout << nthTerm(N); return 0;} // Java program to calculate Nth term of// the series: 5, 13, 25, 41, 61... import java.io.*; class Nth { public static int nthTerm(int N) { // By using above formula return N * N + (N + 1) * (N + 1); } public static void main(String[] args) { int N = 3; // Nth term is 25 // call and print Nth term System.out.println(nthTerm(N)); } } # Python 3 program to find# N-th term of the series:# 5, 13, 25, 41, 61... # Function to calculate# Nth term of seriesdef nthTerm(N) : return N * N + (N + 1) * (N + 1) # Driver Codeif __name__ == "__main__" : N = 3 # function calling print(nthTerm(N)) # This code is contributed# by ANKITRAI1 // C# program to calculate Nth term of// the series: 5, 13, 25, 41, 61...using System; class GFG{public static int nthTerm(int N){ // By using above formula return N * N + (N + 1) * (N + 1);} // Driver Codepublic static void Main(){ int N = 3; // Nth term is 25 // call and print Nth term Console.Write(nthTerm(N));}} // This code is contributed// by ChitraNayal <?php// PHP program to find N-th// term of the series:// 5, 13, 25, 41, 61... // calculate Nth term of seriesfunction nthTerm($N){ return $N * $N + ($N + 1) * ($N + 1);} // Driver Code$N = 3; echo nthTerm($N); // This code is contributed// by ChitraNayal?> <script> // JavaScript program to find N-th term of the series:// 5, 13, 25, 41, 61... // calculate Nth term of seriesfunction nthTerm( N){ return N * N + (N + 1) * (N + 1);}// Driver Function let N = 3; document.write(nthTerm(N)); // This code contributed by Rajput-Ji </script> 25 Time Complexity: O(1) ankthon ukasp Rajput-Ji math series C++ Programs Java Programs School Programming series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Const keyword in C++ Program to implement Singly Linked List in C++ using class cout in C++ Dynamic _Cast in C++ Initializing a List in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 24552, "s": 24524, "text": "\n15 Mar, 2021" }, { "code": null, "e": 24645, "s": 24552, "text": "Given a number N. The task is to write a program to find the Nth term in the below series: " }, { "code": null, "e": 24666, "s": 24645, "text": "5, 13, 25, 41, 61..." }, { "code": null, "e": 24678, "s": 24666, "text": "Examples: " }, { "code": null, "e": 24775, "s": 24678, "text": "Input : 3\nOutput : 25\nFor N = 3\nNth term = 3*3 + (3+1)*(3+1)\n = 25\nInput : 5\nOutput : 61" }, { "code": null, "e": 24859, "s": 24777, "text": "On observing carefully, the Nth term of the given series can be generalised as: " }, { "code": null, "e": 24882, "s": 24859, "text": "Nth term = N2 + (N+1)2" }, { "code": null, "e": 24934, "s": 24882, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 24938, "s": 24934, "text": "C++" }, { "code": null, "e": 24943, "s": 24938, "text": "Java" }, { "code": null, "e": 24952, "s": 24943, "text": "Python 3" }, { "code": null, "e": 24955, "s": 24952, "text": "C#" }, { "code": null, "e": 24959, "s": 24955, "text": "PHP" }, { "code": null, "e": 24970, "s": 24959, "text": "Javascript" }, { "code": "// CPP program to find N-th term of the series:// 5, 13, 25, 41, 61...#include <iostream>using namespace std; // calculate Nth term of seriesint nthTerm(int N){ return N * N + (N + 1) * (N + 1);} // Driver Functionint main(){ int N = 3; cout << nthTerm(N); return 0;}", "e": 25252, "s": 24970, "text": null }, { "code": "// Java program to calculate Nth term of// the series: 5, 13, 25, 41, 61... import java.io.*; class Nth { public static int nthTerm(int N) { // By using above formula return N * N + (N + 1) * (N + 1); } public static void main(String[] args) { int N = 3; // Nth term is 25 // call and print Nth term System.out.println(nthTerm(N)); } }", "e": 25657, "s": 25252, "text": null }, { "code": "# Python 3 program to find# N-th term of the series:# 5, 13, 25, 41, 61... # Function to calculate# Nth term of seriesdef nthTerm(N) : return N * N + (N + 1) * (N + 1) # Driver Codeif __name__ == \"__main__\" : N = 3 # function calling print(nthTerm(N)) # This code is contributed# by ANKITRAI1", "e": 25964, "s": 25657, "text": null }, { "code": "// C# program to calculate Nth term of// the series: 5, 13, 25, 41, 61...using System; class GFG{public static int nthTerm(int N){ // By using above formula return N * N + (N + 1) * (N + 1);} // Driver Codepublic static void Main(){ int N = 3; // Nth term is 25 // call and print Nth term Console.Write(nthTerm(N));}} // This code is contributed// by ChitraNayal", "e": 26347, "s": 25964, "text": null }, { "code": "<?php// PHP program to find N-th// term of the series:// 5, 13, 25, 41, 61... // calculate Nth term of seriesfunction nthTerm($N){ return $N * $N + ($N + 1) * ($N + 1);} // Driver Code$N = 3; echo nthTerm($N); // This code is contributed// by ChitraNayal?>", "e": 26627, "s": 26347, "text": null }, { "code": "<script> // JavaScript program to find N-th term of the series:// 5, 13, 25, 41, 61... // calculate Nth term of seriesfunction nthTerm( N){ return N * N + (N + 1) * (N + 1);}// Driver Function let N = 3; document.write(nthTerm(N)); // This code contributed by Rajput-Ji </script>", "e": 26921, "s": 26627, "text": null }, { "code": null, "e": 26924, "s": 26921, "text": "25" }, { "code": null, "e": 26949, "s": 26926, "text": "Time Complexity: O(1) " }, { "code": null, "e": 26957, "s": 26949, "text": "ankthon" }, { "code": null, "e": 26963, "s": 26957, "text": "ukasp" }, { "code": null, "e": 26973, "s": 26963, "text": "Rajput-Ji" }, { "code": null, "e": 26978, "s": 26973, "text": "math" }, { "code": null, "e": 26985, "s": 26978, "text": "series" }, { "code": null, "e": 26998, "s": 26985, "text": "C++ Programs" }, { "code": null, "e": 27012, "s": 26998, "text": "Java Programs" }, { "code": null, "e": 27031, "s": 27012, "text": "School Programming" }, { "code": null, "e": 27038, "s": 27031, "text": "series" }, { "code": null, "e": 27136, "s": 27038, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27177, "s": 27136, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 27198, "s": 27177, "text": "Const keyword in C++" }, { "code": null, "e": 27257, "s": 27198, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 27269, "s": 27257, "text": "cout in C++" }, { "code": null, "e": 27290, "s": 27269, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 27318, "s": 27290, "text": "Initializing a List in Java" }, { "code": null, "e": 27362, "s": 27318, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27388, "s": 27362, "text": "Java Programming Examples" }, { "code": null, "e": 27422, "s": 27388, "text": "Convert Double to Integer in Java" } ]
Dynamic subplot layout in Seaborn | by Daniel Deutsch | Towards Data Science
Seaborn is one of the most used visualization libraries and I enjoy working with it. In my latest projects, I wanted to visualize multiple subplots in a dynamic way. To my surprise I didn’t find a straight forward solution anywhere online, so I want to share my way of doing it. It can be quite useful in any data analysis endeavor. The problem The approach The solution Changing it to 2 columns it will look like this Changing it to 4 columns it will look like this About Let’s see the titanic dataset for example: There are multiple categorical variables, which we might like to visualize with countplots. Doing this by copying the code in every new cell is not optimal: There is a FacetGrid option for seaborn: However, I would like to have different subplots, on which I can set each plot for myself. Thankfully there is the subplot functionality: categorical_vars = ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone']fig, axs = plt.subplots(nrows=2, ncols=2)for i, var in enumerate(categorical_vars): row = i//2 pos = i % 2 plot = sns.countplot(x=var, data=titanic, ax=axs[row][pos]) Which leads to: This demonstrates the issues I always encountered. For multiple variables, I always need to set the number of rows and columns manually. (fig, axs = plt.subplots(nrows=2, ncols=2)) To solve this I, changed it to: categorical_vars = ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone']num_plots = len(categorical_vars)total_cols = 3total_rows = num_plots//total_cols + 1fig, axs = plt.subplots(nrows=total_rows, ncols=total_cols, figsize=(7*total_cols, 7*total_rows), constrained_layout=True)for i, var in enumerate(categorical_vars): row = i//total_cols pos = i % total_cols plot = sns.countplot(x=var, data=titanic, ax=axs[row][pos]) Which leads to this: Now I can define the layout of the plots to my wishes and also can decide what to plot. Even though it seems quite easy, I didn’t find anything related online. So maybe this helps some of you ;) Daniel is an entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court. His knowledge and interests currently revolve around programming machine learning applications and all its related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects. Don’t hesitate to get in touch if you have ideas, projects, or problems. You can support me on https://www.buymeacoffee.com/createdd
[ { "code": null, "e": 505, "s": 172, "text": "Seaborn is one of the most used visualization libraries and I enjoy working with it. In my latest projects, I wanted to visualize multiple subplots in a dynamic way. To my surprise I didn’t find a straight forward solution anywhere online, so I want to share my way of doing it. It can be quite useful in any data analysis endeavor." }, { "code": null, "e": 517, "s": 505, "text": "The problem" }, { "code": null, "e": 530, "s": 517, "text": "The approach" }, { "code": null, "e": 543, "s": 530, "text": "The solution" }, { "code": null, "e": 591, "s": 543, "text": "Changing it to 2 columns it will look like this" }, { "code": null, "e": 639, "s": 591, "text": "Changing it to 4 columns it will look like this" }, { "code": null, "e": 645, "s": 639, "text": "About" }, { "code": null, "e": 688, "s": 645, "text": "Let’s see the titanic dataset for example:" }, { "code": null, "e": 845, "s": 688, "text": "There are multiple categorical variables, which we might like to visualize with countplots. Doing this by copying the code in every new cell is not optimal:" }, { "code": null, "e": 886, "s": 845, "text": "There is a FacetGrid option for seaborn:" }, { "code": null, "e": 977, "s": 886, "text": "However, I would like to have different subplots, on which I can set each plot for myself." }, { "code": null, "e": 1024, "s": 977, "text": "Thankfully there is the subplot functionality:" }, { "code": null, "e": 1368, "s": 1024, "text": "categorical_vars = ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone']fig, axs = plt.subplots(nrows=2, ncols=2)for i, var in enumerate(categorical_vars): row = i//2 pos = i % 2 plot = sns.countplot(x=var, data=titanic, ax=axs[row][pos])" }, { "code": null, "e": 1384, "s": 1368, "text": "Which leads to:" }, { "code": null, "e": 1565, "s": 1384, "text": "This demonstrates the issues I always encountered. For multiple variables, I always need to set the number of rows and columns manually. (fig, axs = plt.subplots(nrows=2, ncols=2))" }, { "code": null, "e": 1597, "s": 1565, "text": "To solve this I, changed it to:" }, { "code": null, "e": 2148, "s": 1597, "text": "categorical_vars = ['survived', 'pclass', 'sex', 'age', 'sibsp', 'parch', 'embarked', 'class', 'who', 'adult_male', 'deck', 'embark_town', 'alive', 'alone']num_plots = len(categorical_vars)total_cols = 3total_rows = num_plots//total_cols + 1fig, axs = plt.subplots(nrows=total_rows, ncols=total_cols, figsize=(7*total_cols, 7*total_rows), constrained_layout=True)for i, var in enumerate(categorical_vars): row = i//total_cols pos = i % total_cols plot = sns.countplot(x=var, data=titanic, ax=axs[row][pos])" }, { "code": null, "e": 2169, "s": 2148, "text": "Which leads to this:" }, { "code": null, "e": 2364, "s": 2169, "text": "Now I can define the layout of the plots to my wishes and also can decide what to plot. Even though it seems quite easy, I didn’t find anything related online. So maybe this helps some of you ;)" }, { "code": null, "e": 2541, "s": 2364, "text": "Daniel is an entrepreneur, software developer, and business law graduate. He has worked at various IT companies, tax advisory, management consulting, and at the Austrian court." }, { "code": null, "e": 2785, "s": 2541, "text": "His knowledge and interests currently revolve around programming machine learning applications and all its related aspects. To the core, he considers himself a problem solver of complex environments, which is reflected in his various projects." }, { "code": null, "e": 2858, "s": 2785, "text": "Don’t hesitate to get in touch if you have ideas, projects, or problems." } ]
Difference between HTTP GET and POST Methods - GeeksforGeeks
22 Oct, 2021 HTTP GET: The Hypertext Transfer Protocol(HTTP) Get method is mainly used at the client (Browser) side to send a request to a specified server to get certain data or resources. Using this method the server should only let us receive the data and not change its state. Hence it is only used to view something and not to change it. Get method is one of the most used HTTP method. The request parameter of the get method is appended to the URL. Get request is better for the data which does not need to be secure (It means the data which does not contain images or word documents). Example: In the following HTML code we have created a form with text field as Username and City. we have also included a PHP file getmethod.php where our data would be sent after we click the submit button. index.html <!DOCTYPE html><html> <body> <form action="getmethod.php" method="GET"> Username: <input type="text" name="username" /> <br> City: <input type="text" name="city" /> <br> <input type="submit" /> </form></body> </html> In the following PHP code using the GET method we have displayed the Username and city. getmethod.php <!DOCTYPE html><html> <body> Welcome <?php echo $_GET["username"]; ?> </br> Your City is: <?php echo $_GET["city"]; ?></body> </html> Output: Data passed in GET method is clearly visible in the address bar, which can compromise the security. HTTP POST: The Hypertext Transfer Protocol(HTTP) Post method is mainly used at the client (Browser) side to send data to a Specified server in order to create or rewrite a particular resource/data. This data sent to the server is stored in the request body of the HTTP request. Post method eventually leads to the creation of a new resource or updating an existing one. Due to this dynamic use, it is one of the most used HTTP methods. It is not one of the most secure methods because the data that is been sent is included in the body of the request and not in the URL. Post request is better for the data which needs to be secure (It means the data which contains images or word documents). Example: In the following HTML code we have created a form with text field as Username and Area of study. we have also included a PHP file postmethod.php, where our data would be sent after we click the submit button. index.html <!DOCTYPE html><html> <body> <form action="postmethod.php" method="post"> Username: <input type="text" name="username" /> <br> Area of Study: <input type="text" name="area" /> <br> <input type="submit" /> </form></body> </html> In the following PHP code using the POST method we have displayed the Username and Area of study . postmethod.php <!DOCTYPE html><html> <body> Welcome <?php echo $_POST["username"]; ?> </br> YOur Area of Study is: <?php echo $_POST["area"]; ?></body> </html> Output: Data passed in POST method is not shown in the address bar, which maintains the security. Difference between HTTP GET and HTTP POST HTTP GET HTTP POST GET request is comparatively better than Post so it is used more than the Post request. http PHP-Questions Picked Difference Between PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference Between Method Overloading and Method Overriding in Java Comparison between Adjacency List and Adjacency Matrix representation of Graph Difference between Synchronous and Asynchronous Transmission Difference between LAN, MAN and WAN Difference between Prim's and Kruskal's algorithm for MST How to pop an alert message box using PHP ? PHP in_array() Function How to Upload Image into Database and Display it using PHP ? How to pass a PHP array to a JavaScript function? PHP | Converting string to Date and DateTime
[ { "code": null, "e": 24701, "s": 24673, "text": "\n22 Oct, 2021" }, { "code": null, "e": 25280, "s": 24701, "text": "HTTP GET: The Hypertext Transfer Protocol(HTTP) Get method is mainly used at the client (Browser) side to send a request to a specified server to get certain data or resources. Using this method the server should only let us receive the data and not change its state. Hence it is only used to view something and not to change it. Get method is one of the most used HTTP method. The request parameter of the get method is appended to the URL. Get request is better for the data which does not need to be secure (It means the data which does not contain images or word documents)." }, { "code": null, "e": 25487, "s": 25280, "text": "Example: In the following HTML code we have created a form with text field as Username and City. we have also included a PHP file getmethod.php where our data would be sent after we click the submit button." }, { "code": null, "e": 25498, "s": 25487, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <body> <form action=\"getmethod.php\" method=\"GET\"> Username: <input type=\"text\" name=\"username\" /> <br> City: <input type=\"text\" name=\"city\" /> <br> <input type=\"submit\" /> </form></body> </html>", "e": 25784, "s": 25498, "text": null }, { "code": null, "e": 25872, "s": 25784, "text": "In the following PHP code using the GET method we have displayed the Username and city." }, { "code": null, "e": 25888, "s": 25874, "text": "getmethod.php" }, { "code": "<!DOCTYPE html><html> <body> Welcome <?php echo $_GET[\"username\"]; ?> </br> Your City is: <?php echo $_GET[\"city\"]; ?></body> </html>", "e": 26036, "s": 25888, "text": null }, { "code": null, "e": 26144, "s": 26036, "text": "Output: Data passed in GET method is clearly visible in the address bar, which can compromise the security." }, { "code": null, "e": 26837, "s": 26144, "text": "HTTP POST: The Hypertext Transfer Protocol(HTTP) Post method is mainly used at the client (Browser) side to send data to a Specified server in order to create or rewrite a particular resource/data. This data sent to the server is stored in the request body of the HTTP request. Post method eventually leads to the creation of a new resource or updating an existing one. Due to this dynamic use, it is one of the most used HTTP methods. It is not one of the most secure methods because the data that is been sent is included in the body of the request and not in the URL. Post request is better for the data which needs to be secure (It means the data which contains images or word documents)." }, { "code": null, "e": 27055, "s": 26837, "text": "Example: In the following HTML code we have created a form with text field as Username and Area of study. we have also included a PHP file postmethod.php, where our data would be sent after we click the submit button." }, { "code": null, "e": 27066, "s": 27055, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <body> <form action=\"postmethod.php\" method=\"post\"> Username: <input type=\"text\" name=\"username\" /> <br> Area of Study: <input type=\"text\" name=\"area\" /> <br> <input type=\"submit\" /> </form></body> </html>", "e": 27351, "s": 27066, "text": null }, { "code": null, "e": 27450, "s": 27351, "text": "In the following PHP code using the POST method we have displayed the Username and Area of study ." }, { "code": null, "e": 27467, "s": 27452, "text": "postmethod.php" }, { "code": "<!DOCTYPE html><html> <body> Welcome <?php echo $_POST[\"username\"]; ?> </br> YOur Area of Study is: <?php echo $_POST[\"area\"]; ?></body> </html>", "e": 27626, "s": 27467, "text": null }, { "code": null, "e": 27724, "s": 27626, "text": "Output: Data passed in POST method is not shown in the address bar, which maintains the security." }, { "code": null, "e": 27766, "s": 27724, "text": "Difference between HTTP GET and HTTP POST" }, { "code": null, "e": 27775, "s": 27766, "text": "HTTP GET" }, { "code": null, "e": 27785, "s": 27775, "text": "HTTP POST" }, { "code": null, "e": 27859, "s": 27785, "text": "GET request is comparatively better than Post so it is used more than the" }, { "code": null, "e": 27873, "s": 27859, "text": "Post request." }, { "code": null, "e": 27878, "s": 27873, "text": "http" }, { "code": null, "e": 27892, "s": 27878, "text": "PHP-Questions" }, { "code": null, "e": 27899, "s": 27892, "text": "Picked" }, { "code": null, "e": 27918, "s": 27899, "text": "Difference Between" }, { "code": null, "e": 27922, "s": 27918, "text": "PHP" }, { "code": null, "e": 27939, "s": 27922, "text": "Web Technologies" }, { "code": null, "e": 27943, "s": 27939, "text": "PHP" }, { "code": null, "e": 28041, "s": 27943, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28050, "s": 28041, "text": "Comments" }, { "code": null, "e": 28063, "s": 28050, "text": "Old Comments" }, { "code": null, "e": 28131, "s": 28063, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28210, "s": 28131, "text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph" }, { "code": null, "e": 28271, "s": 28210, "text": "Difference between Synchronous and Asynchronous Transmission" }, { "code": null, "e": 28307, "s": 28271, "text": "Difference between LAN, MAN and WAN" }, { "code": null, "e": 28365, "s": 28307, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 28409, "s": 28365, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 28433, "s": 28409, "text": "PHP in_array() Function" }, { "code": null, "e": 28494, "s": 28433, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 28544, "s": 28494, "text": "How to pass a PHP array to a JavaScript function?" } ]
OBIEE – Repositories
OBIEE repository contains all metadata of the BI Server and is managed through the administration tool. It is used to store information about the application environment such as − Data Modeling Aggregate Navigation Caching Security Connectivity Information SQL Information The BI Server can access multiple repositories. OBIEE Repository can be accessed using the following path − BI_ORACLE_HOME/server/Repository -> Oracle 10g ORACLE_INSTANCE/bifoundation/OracleBIServerComponent/coreapplication_obisn/-> Oracle 11g OBIEE repository database is also known as a RPD because of its file extension. The RPD file is password protected and you can only open or create RPD files using Oracle BI Administration tool. To deploy an OBIEE application, the RPD file must be uploaded to Oracle Enterprise Manager. After uploading the RPD, the RPD password then must be entered into Enterprise Manager. It is a three layer process − starting from Physical Layer (Schema Design), Business Model Layer, Presentation Layer. Following are the common steps involved in creating the Physical Layer − Create physical joins between the Dimension and Fact tables. Change the names in the physical layer if required. The physical layer of repository contains information about the data sources. To create the schema in the physical layer you need to import metadata from databases and other data sources. Note − Physical layer in OBIEE supports multiple data sources in a single repository - i.e. data sets from 2 different data sources can be performed in OBIEE. Go to Start → Programs → Oracle Business Intelligence → BI Administration → Administration Tool → File → New Repository. A new window will open → Enter the name of Repository → Location (It tells the default location of Repository directory) → to import metadata select radio button → Enter Password → Click Next. Select the connection type → Enter Data Source name and User name and password to connect to data source → Click Next. Accept the meta types you want to import → You can select Tables, Keys, Foreign Keys, System tables, Synonyms, Alias, Views, etc. → Click Next. Once you click Next, you will see Data Source view and Repository view. Expand the Schema name and select tables you want to add to Repository using Import Selected button → Click Next. Connection Pool window opens up → Click OK → Importing window → Finish to open the repository as shown in the following image. Expand the Data Source → Schema name to see the list of tables Imported in Physical Layer in the new Repository. Go to tools → Update all rows counts → Once it is completed you can move the cursor on the table and also for individual columns. To see Data of a table, right-click on Table name → View Data. It is advisable that you use table aliases frequently in the Physical layer to eliminate extra joins. Right-click on table name and select New Object → Alias. Once you create an Alias of a table it shows up under the same Physical Layer in the Repository. When you create a repository in OBIEE system, physical join is commonly used in the Physical layer. Physical joins help to understand how two tables should be joined to each other. Physical joins are normally expressed with the use of Equal operator. You can also use a physical join in BMM layer, however, it is very rarely seen. The purpose of using a physical join in BMM layer is to override the physical join in the physical layer. It allows users to define more complex joining logic as compared to physical join in the physical layer so it works similar to complex join in the physical layer. Therefore, if we are using a complex join in the physical layer for applying more join conditions, there is no need to use a physical join in BMM layer again. In the above snapshot, you can see a physical join between two table names − Products and Sales. Physical Join expression tells how the tables should be joined with each other as shown in the snapshot. It is always recommended to use a physical join in the physical layer and complex join in BMM layer as much as possible to keep Repository design simple. Only when there is an actual need for a different join, then use a physical join in BMM layer. Now to join tables while designing Repository, select all the tables in the Physical layer → Right-click → Physical diagram → Selected objects only option or you can also use Physical Diagram button at the top. Physical Diagram box as shown in the following image appears with all the table names added. Select the new foreign key at the top and select Dim and Fact table to join. A Foreign key in the physical layer is used to define Primary key-Foreign key relation between two tables. When you create it in the physical diagram, you have to point first the dimension and then the fact table. Note − When you import tables from schema into RPD Physical Layer, you can also select KEY and FOREIGN KEY along with the table data, then the primary key-foreign key joins are automatically defined, however it is not recommended from performance point of view. The table you click first, it creates one-to-one or one-to-many relationship that joins column in first table with foreign key column in the second table → Click Ok. The join will be visible in Physical Diagram box between two tables. Once tables are joined, close the Physical diagram box using ‘X’ option. To save the new Repository go to File → Save or click the save button at the top. It defines the business or logical model of objects and their mapping between business model and Schema in the physical layer. It simplifies the Physical Schema and maps the user business requirement to physical tables. The Business Model and Mapping layer of OBIEE system administration tool can contain one or more business model objects. A business model object defines the business model definitions and the mappings from logical to physical tables for the business model. Following are the steps to build the Business Model and Mapping layer of a repository − Create a business model Examine logical joins Examine logical columns Examine logical table sources Rename logical table objects manually Rename logical table objects using the rename wizard and deleting unnecessary logical objects Creating measures (Aggregations) Right-click on Business Model and Mapping Space → New Business Model. Enter the name of Business Model → click OK. In the physical layer, select all the tables/alias tables to be added to Business Model and drag to Business Model. You can also add tables one by one. If you drag all the tables simultaneously, it will keep keys and joins between them. Also note the difference in icon of Dimension and Fact tables. Last table is Fact table and top 3 are dimension tables. Now right-click on Business model → select Business Model diagram → Whole diagram → All tables are dragged simultaneously so it will keep all joins and keys. Now double click on any join to open the logical join box. Joins in this layer are logical joins. It doesn’t show expressions and tells the type of join between tables. It helps Oracle BI server to understand the relationships between the various pieces of the business model. When you send a query to Oracle BI server, the server determines how to construct physical queries by examining how the logical model is structured. Click Ok → Click ‘X’ to close the Business model diagram. To examine logical columns and logical table sources, first expand the columns under tables in BMM. Logical columns were created for each table when you dragged all tables from the physical layer. To check logical table sources → Expand the source folder under each table and it points to the table in the physical layer. Double-click the logical table source (not the logical table) to open the logical table source dialog box → General tab → rename the logical table source. Logical table to physical table mapping is defined under "Map to these tables" option. Next, Column mapping tab defines the logical column to physical column mappings. If mappings are not shown, check the option → Show mapped columns. There is no specific explicit complex join like in OBIEE 11g. It only exists in Oracle 10g. Go to Manage → Joins → Actions → New → Complex Join. When complex joins are used in the BMM layer, they act as placeholders. They allow the OBI Server to decide on which are the best joins between fact and dimension logical table source to satisfy the request. To rename logical table objects manually, click the column name under the Logical table in BMM. You can also right-click on column name and select option rename, to rename the object. This is known as manual method to rename objects. Go to Tools → Utilities → Rename Wizard → Execute to open the rename wizard. In the Select Objects screen, click Business Model and Mapping. It will show Business Model name → Expand Business Model name → Expand logical tables. Select all the columns under the logical table to rename using the Shift key → Click Add. Similarly, add columns from all other logical Dim and Fact tables → click Next. It shows all logical columns/tables added to wizard → Click Next to open Rules screen → Add rules from the list to rename like : A;; text lower case and change each occurrence of ‘_’ to space as shown in the following snapshot. Click Next → finish. Now, if you expand Object names under logical tables in Business model and Objects in the physical layer, objects under BMM are renamed as required. In the BMM layer, expand Logical tables → select objects to be deleted → right-click → Delete → Yes. Double-click on the column name in the logical Fact table → Go to Aggregation tab and select the Aggregate function from the dropdown list → Click OK. Measures represent data that is additive, such as total revenue or total quantity. Click on save option at top to save the repository. Right-click on Presentation area → New Subject Area → In the General tab enter the name of subject area (Recommended similar to Business Model) → Click OK. Once subject area is created, right click on subject area → New presentation table → Enter the name of the presentation table → Click OK (Add number of presentation tables equal to number of parameters required in the report). Now, to create columns under Presentation tables → Select the objects under logical tables in BMM and drag them to Presentation tables under subject area (Use Ctrl key to select multiple objects for dragging). Repeat the process and add the logical columns to the remaining presentation tables. You can rename the objects in Presentation tables by a double-click on logical objects under subject area. In General tab → Deselect the check box Use Logical column name → Edit the name field → Click OK. Similarly, you can rename all the objects in the Presentation layer without changing their name in BMM layer. To order the columns in a table, double-click on the table name under Presentation → Columns → Use up and down arrows to change the order → Click OK. Similarly, you can change objects order in all presentation tables under Presentation area. Go to File → Click Save to save the Repository. Go to File → Check Global Consistency → You will receive the following message → Click Yes. Once you click OK → Business model under BMM will change to Green → Click save the repository without checking global consistency again. To improve query performance, it is advised to disable BI server cache option. Open a browser and enter the following URL to open Fusion Middleware Control Enterprise Manager: http://<machine name>:7001/em Enter the user name and password and click Login. On the left side, expand Business Intelligence → coreapplication → Capacity Management tab → Performance. Enable BI Server Cache section is by default checked → Click Lock and Edit Configuration → Click Close. Now deselect cache enabled option → It is used to improve query performance → Apply → Activate Changes → Completed Successfully. Go to Deployment tab → Repository → Lock and Edit Configuration → Completed Successfully. Click Upload BI Server Repository section → Browse to open the Choose file dialog box → Select the Repository .rpd file and click on Open → Enter Repository password → Apply → Activate Changes. Activate Changes → Completed Successfully → Click Restart to apply recent changes option on top of the screen → Click Yes. Repository is successfully created and loaded for query Analysis. Print Add Notes Bookmark this page
[ { "code": null, "e": 2256, "s": 2076, "text": "OBIEE repository contains all metadata of the BI Server and is managed through the administration tool. It is used to store information about the application environment such as −" }, { "code": null, "e": 2270, "s": 2256, "text": "Data Modeling" }, { "code": null, "e": 2291, "s": 2270, "text": "Aggregate Navigation" }, { "code": null, "e": 2299, "s": 2291, "text": "Caching" }, { "code": null, "e": 2308, "s": 2299, "text": "Security" }, { "code": null, "e": 2333, "s": 2308, "text": "Connectivity Information" }, { "code": null, "e": 2349, "s": 2333, "text": "SQL Information" }, { "code": null, "e": 2457, "s": 2349, "text": "The BI Server can access multiple repositories. OBIEE Repository can be accessed using the following path −" }, { "code": null, "e": 2594, "s": 2457, "text": "BI_ORACLE_HOME/server/Repository -> Oracle 10g\nORACLE_INSTANCE/bifoundation/OracleBIServerComponent/coreapplication_obisn/-> Oracle 11g\n" }, { "code": null, "e": 2968, "s": 2594, "text": "OBIEE repository database is also known as a RPD because of its file extension. The RPD file is password protected and you can only open or create RPD files using Oracle BI Administration tool. To deploy an OBIEE application, the RPD file must be uploaded to Oracle Enterprise Manager. After uploading the RPD, the RPD password then must be entered into Enterprise Manager." }, { "code": null, "e": 3086, "s": 2968, "text": "It is a three layer process − starting from Physical Layer (Schema Design), Business Model Layer, Presentation Layer." }, { "code": null, "e": 3159, "s": 3086, "text": "Following are the common steps involved in creating the Physical Layer −" }, { "code": null, "e": 3220, "s": 3159, "text": "Create physical joins between the Dimension and Fact tables." }, { "code": null, "e": 3272, "s": 3220, "text": "Change the names in the physical layer if required." }, { "code": null, "e": 3460, "s": 3272, "text": "The physical layer of repository contains information about the data sources. To create the schema in the physical layer you need to import metadata from databases and other data sources." }, { "code": null, "e": 3619, "s": 3460, "text": "Note − Physical layer in OBIEE supports multiple data sources in a single repository - i.e. data sets from 2 different data sources can be performed in OBIEE." }, { "code": null, "e": 3740, "s": 3619, "text": "Go to Start → Programs → Oracle Business Intelligence → BI Administration → Administration Tool → File → New Repository." }, { "code": null, "e": 3933, "s": 3740, "text": "A new window will open → Enter the name of Repository → Location (It tells the default location of Repository directory) → to import metadata select radio button → Enter Password → Click Next." }, { "code": null, "e": 4052, "s": 3933, "text": "Select the connection type → Enter Data Source name and User name and password to connect to data source → Click Next." }, { "code": null, "e": 4196, "s": 4052, "text": "Accept the meta types you want to import → You can select Tables, Keys, Foreign Keys, System tables, Synonyms, Alias, Views, etc. → Click Next." }, { "code": null, "e": 4382, "s": 4196, "text": "Once you click Next, you will see Data Source view and Repository view. Expand the Schema name and select tables you want to add to Repository using Import Selected button → Click Next." }, { "code": null, "e": 4509, "s": 4382, "text": "Connection Pool window opens up → Click OK → Importing window → Finish to open the repository as shown in the following image." }, { "code": null, "e": 4622, "s": 4509, "text": "Expand the Data Source → Schema name to see the list of tables Imported in Physical Layer in the new Repository." }, { "code": null, "e": 4815, "s": 4622, "text": "Go to tools → Update all rows counts → Once it is completed you can move the cursor on the table and also for individual columns. To see Data of a table, right-click on Table name → View Data." }, { "code": null, "e": 4974, "s": 4815, "text": "It is advisable that you use table aliases frequently in the Physical layer to eliminate extra joins. Right-click on table name and select New Object → Alias." }, { "code": null, "e": 5071, "s": 4974, "text": "Once you create an Alias of a table it shows up under the same Physical Layer in the Repository." }, { "code": null, "e": 5322, "s": 5071, "text": "When you create a repository in OBIEE system, physical join is commonly used in the Physical layer. Physical joins help to understand how two tables should be joined to each other. Physical joins are normally expressed with the use of Equal operator." }, { "code": null, "e": 5830, "s": 5322, "text": "You can also use a physical join in BMM layer, however, it is very rarely seen. The purpose of using a physical join in BMM layer is to override the physical join in the physical layer. It allows users to define more complex joining logic as compared to physical join in the physical layer so it works similar to complex join in the physical layer. Therefore, if we are using a complex join in the physical layer for applying more join conditions, there is no need to use a physical join in BMM layer again." }, { "code": null, "e": 6032, "s": 5830, "text": "In the above snapshot, you can see a physical join between two table names − Products and Sales. Physical Join expression tells how the tables should be joined with each other as shown in the snapshot." }, { "code": null, "e": 6281, "s": 6032, "text": "It is always recommended to use a physical join in the physical layer and complex join in BMM layer as much as possible to keep Repository design simple. Only when there is an actual need for a different join, then use a physical join in BMM layer." }, { "code": null, "e": 6492, "s": 6281, "text": "Now to join tables while designing Repository, select all the tables in the Physical layer → Right-click → Physical diagram → Selected objects only option or you can also use Physical Diagram button at the top." }, { "code": null, "e": 6662, "s": 6492, "text": "Physical Diagram box as shown in the following image appears with all the table names added. Select the new foreign key at the top and select Dim and Fact table to join." }, { "code": null, "e": 6876, "s": 6662, "text": "A Foreign key in the physical layer is used to define Primary key-Foreign key relation between two tables. When you create it in the physical diagram, you have to point first the dimension and then the fact table." }, { "code": null, "e": 7138, "s": 6876, "text": "Note − When you import tables from schema into RPD Physical Layer, you can also select KEY and FOREIGN KEY along with the table data, then the primary key-foreign key joins are automatically defined, however it is not recommended from performance point of view." }, { "code": null, "e": 7446, "s": 7138, "text": "The table you click first, it creates one-to-one or one-to-many relationship that joins column in first table with foreign key column in the second table → Click Ok. The join will be visible in Physical Diagram box between two tables. Once tables are joined, close the Physical diagram box using ‘X’ option." }, { "code": null, "e": 7528, "s": 7446, "text": "To save the new Repository go to File → Save or click the save button at the top." }, { "code": null, "e": 7748, "s": 7528, "text": "It defines the business or logical model of objects and their mapping between business model and Schema in the physical layer. It simplifies the Physical Schema and maps the user business requirement to physical tables." }, { "code": null, "e": 8005, "s": 7748, "text": "The Business Model and Mapping layer of OBIEE system administration tool can contain one or more business model objects. A business model object defines the business model definitions and the mappings from logical to physical tables for the business model." }, { "code": null, "e": 8093, "s": 8005, "text": "Following are the steps to build the Business Model and Mapping layer of a repository −" }, { "code": null, "e": 8117, "s": 8093, "text": "Create a business model" }, { "code": null, "e": 8139, "s": 8117, "text": "Examine logical joins" }, { "code": null, "e": 8163, "s": 8139, "text": "Examine logical columns" }, { "code": null, "e": 8193, "s": 8163, "text": "Examine logical table sources" }, { "code": null, "e": 8231, "s": 8193, "text": "Rename logical table objects manually" }, { "code": null, "e": 8325, "s": 8231, "text": "Rename logical table objects using the rename wizard and deleting unnecessary logical objects" }, { "code": null, "e": 8358, "s": 8325, "text": "Creating measures (Aggregations)" }, { "code": null, "e": 8428, "s": 8358, "text": "Right-click on Business Model and Mapping Space → New Business Model." }, { "code": null, "e": 8473, "s": 8428, "text": "Enter the name of Business Model → click OK." }, { "code": null, "e": 8710, "s": 8473, "text": "In the physical layer, select all the tables/alias tables to be added to Business Model and drag to Business Model. You can also add tables one by one. If you drag all the tables simultaneously, it will keep keys and joins between them." }, { "code": null, "e": 8830, "s": 8710, "text": "Also note the difference in icon of Dimension and Fact tables. Last table is Fact table and top 3 are dimension tables." }, { "code": null, "e": 9047, "s": 8830, "text": "Now right-click on Business model → select Business Model diagram → Whole diagram → All tables are dragged simultaneously so it will keep all joins and keys. Now double click on any join to open the logical join box." }, { "code": null, "e": 9414, "s": 9047, "text": "Joins in this layer are logical joins. It doesn’t show expressions and tells the type of join between tables. It helps Oracle BI server to understand the relationships between the various pieces of the business model. When you send a query to Oracle BI server, the server determines how to construct physical queries by examining how the logical model is structured." }, { "code": null, "e": 9472, "s": 9414, "text": "Click Ok → Click ‘X’ to close the Business model diagram." }, { "code": null, "e": 9794, "s": 9472, "text": "To examine logical columns and logical table sources, first expand the columns under tables in BMM. Logical columns were created for each table when you dragged all tables from the physical layer. To check logical table sources → Expand the source folder under each table and it points to the table in the physical layer." }, { "code": null, "e": 10036, "s": 9794, "text": "Double-click the logical table source (not the logical table) to open the logical table source dialog box → General tab → rename the logical table source. Logical table to physical table mapping is defined under \"Map to these tables\" option." }, { "code": null, "e": 10184, "s": 10036, "text": "Next, Column mapping tab defines the logical column to physical column mappings. If mappings are not shown, check the option → Show mapped columns." }, { "code": null, "e": 10276, "s": 10184, "text": "There is no specific explicit complex join like in OBIEE 11g. It only exists in Oracle 10g." }, { "code": null, "e": 10329, "s": 10276, "text": "Go to Manage → Joins → Actions → New → Complex Join." }, { "code": null, "e": 10537, "s": 10329, "text": "When complex joins are used in the BMM layer, they act as placeholders. They allow the OBI Server to decide on which are the best joins between fact and dimension logical table source to satisfy the request." }, { "code": null, "e": 10721, "s": 10537, "text": "To rename logical table objects manually, click the column name under the Logical table in BMM. You can also right-click on column name and select option rename, to rename the object." }, { "code": null, "e": 10771, "s": 10721, "text": "This is known as manual method to rename objects." }, { "code": null, "e": 10848, "s": 10771, "text": "Go to Tools → Utilities → Rename Wizard → Execute to open the rename wizard." }, { "code": null, "e": 10999, "s": 10848, "text": "In the Select Objects screen, click Business Model and Mapping. It will show Business Model name → Expand Business Model name → Expand logical tables." }, { "code": null, "e": 11169, "s": 10999, "text": "Select all the columns under the logical table to rename using the Shift key → Click Add. Similarly, add columns from all other logical Dim and Fact tables → click Next." }, { "code": null, "e": 11397, "s": 11169, "text": "It shows all logical columns/tables added to wizard → Click Next to open Rules screen → Add rules from the list to rename like : A;; text lower case and change each occurrence of ‘_’ to space as shown in the following snapshot." }, { "code": null, "e": 11567, "s": 11397, "text": "Click Next → finish. Now, if you expand Object names under logical tables in Business model and Objects in the physical layer, objects under BMM are renamed as required." }, { "code": null, "e": 11668, "s": 11567, "text": "In the BMM layer, expand Logical tables → select objects to be deleted → right-click → Delete → Yes." }, { "code": null, "e": 11819, "s": 11668, "text": "Double-click on the column name in the logical Fact table → Go to Aggregation tab and select the Aggregate function from the dropdown list → Click OK." }, { "code": null, "e": 11954, "s": 11819, "text": "Measures represent data that is additive, such as total revenue or total quantity. Click on save option at top to save the repository." }, { "code": null, "e": 12110, "s": 11954, "text": "Right-click on Presentation area → New Subject Area → In the General tab enter the name of subject area (Recommended similar to Business Model) → Click OK." }, { "code": null, "e": 12337, "s": 12110, "text": "Once subject area is created, right click on subject area → New presentation table → Enter the name of the presentation table → Click OK (Add number of presentation tables equal to number of parameters required in the report)." }, { "code": null, "e": 12632, "s": 12337, "text": "Now, to create columns under Presentation tables → Select the objects under logical tables in BMM and drag them to Presentation tables under subject area (Use Ctrl key to select multiple objects for dragging). Repeat the process and add the logical columns to the remaining presentation tables." }, { "code": null, "e": 12739, "s": 12632, "text": "You can rename the objects in Presentation tables by a double-click on logical objects under subject area." }, { "code": null, "e": 12837, "s": 12739, "text": "In General tab → Deselect the check box Use Logical column name → Edit the name field → Click OK." }, { "code": null, "e": 12947, "s": 12837, "text": "Similarly, you can rename all the objects in the Presentation layer without changing their name in BMM layer." }, { "code": null, "e": 13097, "s": 12947, "text": "To order the columns in a table, double-click on the table name under Presentation → Columns → Use up and down arrows to change the order → Click OK." }, { "code": null, "e": 13237, "s": 13097, "text": "Similarly, you can change objects order in all presentation tables under Presentation area. Go to File → Click Save to save the Repository." }, { "code": null, "e": 13329, "s": 13237, "text": "Go to File → Check Global Consistency → You will receive the following message → Click Yes." }, { "code": null, "e": 13466, "s": 13329, "text": "Once you click OK → Business model under BMM will change to Green → Click save the repository without checking global consistency again." }, { "code": null, "e": 13545, "s": 13466, "text": "To improve query performance, it is advised to disable BI server cache option." }, { "code": null, "e": 13672, "s": 13545, "text": "Open a browser and enter the following URL to open Fusion Middleware Control Enterprise Manager: http://<machine name>:7001/em" }, { "code": null, "e": 13722, "s": 13672, "text": "Enter the user name and password and click Login." }, { "code": null, "e": 13828, "s": 13722, "text": "On the left side, expand Business Intelligence → coreapplication → Capacity Management tab → Performance." }, { "code": null, "e": 13932, "s": 13828, "text": "Enable BI Server Cache section is by default checked → Click Lock and Edit Configuration → Click Close." }, { "code": null, "e": 14061, "s": 13932, "text": "Now deselect cache enabled option → It is used to improve query performance → Apply → Activate Changes → Completed Successfully." }, { "code": null, "e": 14151, "s": 14061, "text": "Go to Deployment tab → Repository → Lock and Edit Configuration → Completed Successfully." }, { "code": null, "e": 14345, "s": 14151, "text": "Click Upload BI Server Repository section → Browse to open the Choose file dialog box → Select the Repository .rpd file and click on Open → Enter Repository password → Apply → Activate Changes." }, { "code": null, "e": 14468, "s": 14345, "text": "Activate Changes → Completed Successfully → Click Restart to apply recent changes option on top of the screen → Click Yes." }, { "code": null, "e": 14534, "s": 14468, "text": "Repository is successfully created and loaded for query Analysis." }, { "code": null, "e": 14541, "s": 14534, "text": " Print" }, { "code": null, "e": 14552, "s": 14541, "text": " Add Notes" } ]
Encode and Decode Strings in C++
Suppose we have a list of strings. We have to design an algorithm that can encode the list of strings to a string. We also have to make one decoder that will decode back to the original list of strings. Suppose we have the encoder and decoder installed on these machines, and there are two different functions as follows − string encode(vector<string< strs) { //code to read strings and return encoded_string; } vector<string< decode(string s) { //code to decode encoded_string and returns strs; } So, if the input is like {"hello", "world", "coding", "challenge"}, then the output will be Encoded String 5#hello5#world6#coding9#challenge, decoded form [hello, world, coding, challenge, ] To solve this, we will follow these steps − Define a function encode(), this will take an array strs, Define a function encode(), this will take an array strs, ret := empty string ret := empty string for initialize i := 0, when i < size of strs, update (increase i by 1), do −ret := ret concatenate size of strs[i] for initialize i := 0, when i < size of strs, update (increase i by 1), do − ret := ret concatenate size of strs[i] ret := ret concatenate size of strs[i] return ret return ret Define a function getNext(), this will take x, start, s, Define a function getNext(), this will take x, start, s, idx := size of s idx := size of s for initialize i := start, when i < size of s, update (increase i by 1), do −if s[i] is same as x, then −idx := iCome out from the loop for initialize i := start, when i < size of s, update (increase i by 1), do − if s[i] is same as x, then −idx := iCome out from the loop if s[i] is same as x, then − idx := i idx := i Come out from the loop Come out from the loop return idx return idx Define method decode this will take s Define method decode this will take s Define an array ret Define an array ret i := 0 i := 0 n := size of s n := size of s while i < n, do −hashPos := getNext('#', i, s)len := (substring of s from index (i to hashPos - i - 1) as integeri := hashPos + 1insert substring of s from index (i to len - 1) at the end of reti := i + len while i < n, do − hashPos := getNext('#', i, s) hashPos := getNext('#', i, s) len := (substring of s from index (i to hashPos - i - 1) as integer len := (substring of s from index (i to hashPos - i - 1) as integer i := hashPos + 1 i := hashPos + 1 insert substring of s from index (i to len - 1) at the end of ret insert substring of s from index (i to len - 1) at the end of ret i := i + len i := i + len return ret return ret Let us see the following implementation to get a better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto< v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Codec { public: string encode(vector<string>& strs) { string ret = ""; for (int i = 0; i < strs.size(); i++) { ret += to_string(strs[i].size()) + "#" + strs[i]; } return ret; } int getNext(char x, int start, string s){ int idx = s.size(); for (int i = start; i < s.size(); i++) { if (s[i] == x) { idx = i; break; } } return idx; } vector<string> decode(string s) { vector<string> ret; int i = 0; int n = s.size(); while (i < n) { int hashPos = getNext('#', i, s); int len = stoi(s.substr(i, hashPos - i)); i = hashPos + 1; ret.push_back(s.substr(i, len)); i += len; } return ret; } }; main(){ Codec ob; vector<string> v = {"hello", "world", "coding", "challenge"}; string enc = (ob.encode(v)); cout << "Encoded String " << enc << endl; print_vector(ob.decode(enc)); } {"hello", "world", "coding", "challenge"} Encoded String 5#hello5#world6#coding9#challenge [hello, world, coding, challenge, ]
[ { "code": null, "e": 1385, "s": 1062, "text": "Suppose we have a list of strings. We have to design an algorithm that can encode the list of strings to a string. We also have to make one decoder that will decode back to the original list of strings. Suppose we have the encoder and decoder installed on these machines, and there are two different functions as follows −" }, { "code": null, "e": 1477, "s": 1385, "text": "string encode(vector<string< strs) {\n //code to read strings and return encoded_string;\n}" }, { "code": null, "e": 1566, "s": 1477, "text": "vector<string< decode(string s) {\n //code to decode encoded_string and returns strs;\n}" }, { "code": null, "e": 1757, "s": 1566, "text": "So, if the input is like {\"hello\", \"world\", \"coding\", \"challenge\"}, then the output will be Encoded String 5#hello5#world6#coding9#challenge, decoded form [hello, world, coding, challenge, ]" }, { "code": null, "e": 1801, "s": 1757, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1859, "s": 1801, "text": "Define a function encode(), this will take an array strs," }, { "code": null, "e": 1917, "s": 1859, "text": "Define a function encode(), this will take an array strs," }, { "code": null, "e": 1937, "s": 1917, "text": "ret := empty string" }, { "code": null, "e": 1957, "s": 1937, "text": "ret := empty string" }, { "code": null, "e": 2072, "s": 1957, "text": "for initialize i := 0, when i < size of strs, update (increase i by 1), do −ret := ret concatenate size of strs[i]" }, { "code": null, "e": 2149, "s": 2072, "text": "for initialize i := 0, when i < size of strs, update (increase i by 1), do −" }, { "code": null, "e": 2188, "s": 2149, "text": "ret := ret concatenate size of strs[i]" }, { "code": null, "e": 2227, "s": 2188, "text": "ret := ret concatenate size of strs[i]" }, { "code": null, "e": 2238, "s": 2227, "text": "return ret" }, { "code": null, "e": 2249, "s": 2238, "text": "return ret" }, { "code": null, "e": 2306, "s": 2249, "text": "Define a function getNext(), this will take x, start, s," }, { "code": null, "e": 2363, "s": 2306, "text": "Define a function getNext(), this will take x, start, s," }, { "code": null, "e": 2380, "s": 2363, "text": "idx := size of s" }, { "code": null, "e": 2397, "s": 2380, "text": "idx := size of s" }, { "code": null, "e": 2533, "s": 2397, "text": "for initialize i := start, when i < size of s, update (increase i by 1), do −if s[i] is same as x, then −idx := iCome out from the loop" }, { "code": null, "e": 2611, "s": 2533, "text": "for initialize i := start, when i < size of s, update (increase i by 1), do −" }, { "code": null, "e": 2670, "s": 2611, "text": "if s[i] is same as x, then −idx := iCome out from the loop" }, { "code": null, "e": 2699, "s": 2670, "text": "if s[i] is same as x, then −" }, { "code": null, "e": 2708, "s": 2699, "text": "idx := i" }, { "code": null, "e": 2717, "s": 2708, "text": "idx := i" }, { "code": null, "e": 2740, "s": 2717, "text": "Come out from the loop" }, { "code": null, "e": 2763, "s": 2740, "text": "Come out from the loop" }, { "code": null, "e": 2774, "s": 2763, "text": "return idx" }, { "code": null, "e": 2785, "s": 2774, "text": "return idx" }, { "code": null, "e": 2823, "s": 2785, "text": "Define method decode this will take s" }, { "code": null, "e": 2861, "s": 2823, "text": "Define method decode this will take s" }, { "code": null, "e": 2881, "s": 2861, "text": "Define an array ret" }, { "code": null, "e": 2901, "s": 2881, "text": "Define an array ret" }, { "code": null, "e": 2908, "s": 2901, "text": "i := 0" }, { "code": null, "e": 2915, "s": 2908, "text": "i := 0" }, { "code": null, "e": 2930, "s": 2915, "text": "n := size of s" }, { "code": null, "e": 2945, "s": 2930, "text": "n := size of s" }, { "code": null, "e": 3152, "s": 2945, "text": "while i < n, do −hashPos := getNext('#', i, s)len := (substring of s from index (i to hashPos - i - 1) as integeri := hashPos + 1insert substring of s from index (i to len - 1) at the end of reti := i + len" }, { "code": null, "e": 3170, "s": 3152, "text": "while i < n, do −" }, { "code": null, "e": 3200, "s": 3170, "text": "hashPos := getNext('#', i, s)" }, { "code": null, "e": 3230, "s": 3200, "text": "hashPos := getNext('#', i, s)" }, { "code": null, "e": 3298, "s": 3230, "text": "len := (substring of s from index (i to hashPos - i - 1) as integer" }, { "code": null, "e": 3366, "s": 3298, "text": "len := (substring of s from index (i to hashPos - i - 1) as integer" }, { "code": null, "e": 3383, "s": 3366, "text": "i := hashPos + 1" }, { "code": null, "e": 3400, "s": 3383, "text": "i := hashPos + 1" }, { "code": null, "e": 3466, "s": 3400, "text": "insert substring of s from index (i to len - 1) at the end of ret" }, { "code": null, "e": 3532, "s": 3466, "text": "insert substring of s from index (i to len - 1) at the end of ret" }, { "code": null, "e": 3545, "s": 3532, "text": "i := i + len" }, { "code": null, "e": 3558, "s": 3545, "text": "i := i + len" }, { "code": null, "e": 3569, "s": 3558, "text": "return ret" }, { "code": null, "e": 3580, "s": 3569, "text": "return ret" }, { "code": null, "e": 3652, "s": 3580, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 3663, "s": 3652, "text": " Live Demo" }, { "code": null, "e": 4840, "s": 3663, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto< v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Codec {\npublic:\n string encode(vector<string>& strs) {\n string ret = \"\";\n for (int i = 0; i < strs.size(); i++) {\n ret += to_string(strs[i].size()) + \"#\" + strs[i];\n }\n return ret;\n }\n int getNext(char x, int start, string s){\n int idx = s.size();\n for (int i = start; i < s.size(); i++) {\n if (s[i] == x) {\n idx = i;\n break;\n }\n }\n return idx;\n }\n vector<string> decode(string s) {\n vector<string> ret;\n int i = 0;\n int n = s.size();\n while (i < n) {\n int hashPos = getNext('#', i, s);\n int len = stoi(s.substr(i, hashPos - i));\n i = hashPos + 1;\n ret.push_back(s.substr(i, len));\n i += len;\n }\n return ret;\n }\n};\nmain(){\n Codec ob;\n vector<string> v = {\"hello\", \"world\", \"coding\", \"challenge\"};\n string enc = (ob.encode(v));\n cout << \"Encoded String \" << enc << endl;\n print_vector(ob.decode(enc));\n}" }, { "code": null, "e": 4882, "s": 4840, "text": "{\"hello\", \"world\", \"coding\", \"challenge\"}" }, { "code": null, "e": 4967, "s": 4882, "text": "Encoded String 5#hello5#world6#coding9#challenge\n[hello, world, coding, challenge, ]" } ]
Medical Report Generation Using Deep Learning | by Vysakh Nair | Towards Data Science
Introduction — Understanding the problemPrerequisitesDataObtaining Structured DataPrepare Text Data — Natural Language ProcessingObtaining Image Features — Transfer LearningInput Pipeline — Data GeneratorsEncoder-Decoder Model — Training, Greedy Search, Beam Search, BLEUAttention Mechanism — Training, Greedy Search, Beam Search, BLEUSummaryFuture WorkReferences Introduction — Understanding the problem Prerequisites Data Obtaining Structured Data Prepare Text Data — Natural Language Processing Obtaining Image Features — Transfer Learning Input Pipeline — Data Generators Encoder-Decoder Model — Training, Greedy Search, Beam Search, BLEU Attention Mechanism — Training, Greedy Search, Beam Search, BLEU Summary Future Work References Image Captioning is a challenging artificial intelligence problem which refers to the process of generating textual description from an image based on the image contents. For instance, look at the picture below: A common answer would be “A woman playing a guitar”. We as humans can look at a picture and describe whatever it is in it, in an appropriate language. This is easy. Let me show you another one: For all of us ‘non-radiologists’, a common answer would be “a chest x-ray”. Well, we are not wrong but a radiologist might have some different interpretations. They write textual reports to narrate the findings regarding each area of the body examined in the imaging study, specifically whether each area was found to be normal, abnormal or potentially abnormal. They can derive such valuable information and make medical reports from one such image. For less-experienced radiologists and pathologists, especially those working in the rural areas where the quality of healthcare is relatively low, writing medical-imaging reports is demanding or on the other hand for experienced radiologists and pathologists, writing imaging reports can be tedious and time consuming. So, to address all these matters, wouldn’t it be great if a computer can take a chest x-ray like the one above as input and output the findings as text just like how a radiologist would do? But, can you indeed write such a computer program? Well, if the answer was ‘no’, you wouldn’t be reading this story. This work assumes some deep learning familiarity with topics like Neural Nets, CNNs, RNNs, Transfer Learning, Python programming and Keras library. The two below mentioned models will be used for our problem, which will be explained briefly later in this blog itself: Encoder-Decoder ModelAttention-Mechanism Encoder-Decoder Model Attention-Mechanism Decent knowledge about them will help you understand the models better. You can obtain the data needed for this problem from the below links: Images- Contains all the chest X-rays. Reports- Contains the corresponding reports for the above images. The image dataset contains multiple chest x-rays of a single person. For instance: side-view of the x-ray, multiple frontal views etc. Just as a radiologist uses all these images to write the findings, the models will also use all these images together to generate the corresponding findings. There are 3955 reports present in the dataset, with each report having one or more images associated with it. The reports in the dataset are XML files where each file corresponds to an individual. The image IDs and the corresponding findings associated with that person is contained in these files. An example is shown below: The highlighted info are the things that you need to extract from these files. This can be done with the help of python’s XML library. NOTE: The findings will be also referred to as reports. They will be used interchangeably in the rest of the blog. After extracting the required data from the XML files, the data is converted into a structured format for easy understanding and accessibility. As mentioned before, there are multiple images associated with a single report. Therefore, our model also needs to see these images while generating reports. But some reports have only 1 image associated with it, while some have 2 and the maximum being 4. So the question arises, how many images should we feed into the model at a time to generate a report? To make the model-input consistent, pairs of images i.e two images were chosen at a time as input. If a report only had 1 image, the same image would be replicated as the second input. Now we have a proper and understandable structured data to work with. The images are saved by the names of their absolute address. This will be helpful while loading the data. After the final step, we will have data points of an individual multiple times. For example, if a person has four images associated with the report and since we are taking pairs of images, multiple data points of that person will be generated. Therefore it is necessary to split this dataset w.r.t individuals rather than the generated data points to avoid data leakage problem. Before making pairs of images, make sure you split the data into train, cv and test using the unique ‘person_id’ feature, and then train the model. After obtaining the findings from the XML file, they should be properly cleaned and prepared before we feed it into the model. Below image shows a few examples of how findings would look like before its cleaned. We will clean the text in the following ways: Convert all characters into lowercase.Perform basic decontractions i.e words like won’t, can’t and so on will be converted to will not, cannot and so on respectively.Remove punctuation from text. Note that full stop will not be removed because the findings contain multiple sentences, so we need the model to generate reports in a similar way by identifying sentences.Remove all numbers from the text.Remove all words with length less than or equal to 2. For example, ‘is’, ‘to’ etc are removed. These words don’t provide much information. But the word ‘no’ will not be removed since it adds value. Adding ‘no’ to a sentence changes its meaning entirely. So we have to be careful while performing these kind of cleaning steps. You need to identify which words to keep and which ones to avoid.It was also found that some texts contain multiple full stops or spaces or ‘X’ repeated multiple times. Such characters are also removed. Convert all characters into lowercase. Perform basic decontractions i.e words like won’t, can’t and so on will be converted to will not, cannot and so on respectively. Remove punctuation from text. Note that full stop will not be removed because the findings contain multiple sentences, so we need the model to generate reports in a similar way by identifying sentences. Remove all numbers from the text. Remove all words with length less than or equal to 2. For example, ‘is’, ‘to’ etc are removed. These words don’t provide much information. But the word ‘no’ will not be removed since it adds value. Adding ‘no’ to a sentence changes its meaning entirely. So we have to be careful while performing these kind of cleaning steps. You need to identify which words to keep and which ones to avoid. It was also found that some texts contain multiple full stops or spaces or ‘X’ repeated multiple times. Such characters are also removed. The model we will develop will generate a report given a combination of two images, and the report will be generated one word at a time. The sequence of previously generated words will be provided as input. Therefore, we will need a ‘first word’ to kick-off the generation process and a ‘last word’ to signal the end of the report. We will use the strings ‘startseq’ and ‘endseq’ for this purpose. These strings are added to our findings. It is important to do this now because when we encode the text, we need these strings to be encoded correctly. The major step in encoding text is to create a consistent mapping from words to unique integer values known as tokenization. In order to get our computer to understand any text, we need to break that word or sentence down in a way that our machine can understand. We can’t work with text data if we don’t perform tokenization. Tokenization is a way of separating a piece of text into smaller units called tokens. Tokens can be either words or characters but in our case it’ll be words. Keras provides an inbuilt library for this purpose. from tensorflow.keras.preprocessing.text import Tokenizertokenizer = Tokenizer(filters='!"#$%&()*+,-/:;<=>?@[\\]^_`{|}~\t\n')tokenizer.fit_on_texts(reports) Now the text that we have are properly cleaned and tokenized for future use. The full code for all this is available in my GitHub account whose link is provided at the end of this story. Images along with partial reports are the inputs to our model. We need to convert every image into a fixed sized vector which can then be fed as input to the model. We will use transfer learning for this purpose. “In transfer learning, we first train a base network on a base dataset and task, and then we re-purpose the learned features, or transfer them, to a second target network to be trained on a target dataset and task. This process will tend to work if the features are general, meaning suitable to both base and target tasks, instead of specific to the base task.” VGG16, VGG19 or InceptionV3 are the common CNNs used for transfer learning. These are trained on datasets like Imagenets whose images are completely different from that of a chest x-ray. So logically, they doesn’t seem to be a good choice for our task. So which network should we use for our problem? If you are unfamiliar, let me introduce you to CheXNet. CheXNet, is a 121-layer convolutional neural network trained on ChestX-ray14, currently the largest publicly available chest X-ray dataset, containing over 100,000 frontal-view X-ray images with 14 diseases. However, our purpose here is not to classify the images but just to get the bottleneck features for each image. Therefore the last classification layer of this network is not needed. You can download the trained weights of CheXNet from here. from tensorflow.keras.applications import densenetchex = densenet.DenseNet121(include_top=False, weights = None, input_shape=(224,224,3), pooling="avg")X = chex.outputX = Dense(14, activation="sigmoid", name="predictions")(X)model = Model(inputs=chex.input, outputs=X)model.load_weights('load_the_downloaded_weights.h5')chexnet = Model(inputs = model.input, outputs = model.layers[-2].output) If you forgot, we have 2 images as input to our model. So, here is how the bottleneck features are obtained: Each image is resized to (224,224,3) and is passed through the CheXNet and a 1024 length feature vector is obtained. Later both these feature vectors are concatenated to obtain a 2048 feature vector. If you notice, we have added an average pooling layer as the last layer. There’s a specific reason for this. Since we are concatenating both images, the model might learn some order of concatenation. For example, image1 always comes after image2 or vice-versa, but that isn’t the case here. We are not keeping any order while concatenating them. This problem is solved through pooling which creates location in-variance. The code for this is as follows: These features are stored in a dictionary in pickle format, which can be used for future purposes. Consider a scenario where you have lots of data, so much that you cannot have all of it at once in the RAM. Purchasing more RAM is obviously not an option for everyone. The solution can be to feed mini-batches of our data into the model dynamically. This is exactly what data generators do. They can generate the model input dynamically thus forming a pipeline from the storage to the RAM to load the data as and when it is required. Another advantage of this pipeline is, one can easily apply preprocessing routines on these mini-batches of data as they are prepared to feed into the model. We will be using tf.data for our problem. We will first divide our dataset into two parts, a train dataset and a validation dataset. While dividing, just make sure that you have enough data points for training and a decent amount for validation as well. The proportion that I chose allowed me to have 2560 data points in my train set and 1147 data points in the validation set. Now it’s time for us to create the generator for our dataset. Here we created two data generators, train_dataset for training and cv_dataset for validation. The create_dataset function takes the IDs (which are keys of the dictionary, for the bottleneck features created earlier) and the preprocessed reports, and creates the generator. The generator generates the BATCH_SIZE number of data points at a time. As mentioned earlier the model that we are going to create will be a word by word model. The model takes as input the image features and the partial sequences to generate the next word in the sequence. For example: Let the report corresponding to the ‘Image_features_1’ be — “startseq the cardiac silhouette and mediastinum size are within normal limits endseq”. Then the input sequence would be split into 11 input-output pairs to train the model: Note that we are NOT creating these input-output pairs through the generator. The generator only provides us with the BATCH_SIZE number of image features and their corresponding complete reports at a time. The input-output pairs are generated later during the training process, which will be explained in a short while. A sequence-to-sequence model is a deep learning model that takes a sequence of items (in our case, features of an image) and outputs another sequence of items (reports). The encoder processes each item in the input sequence, it compiles the information it captures into a vector called the context. After processing the entire input sequence, the encoder sends the context over to the decoder, which begins producing the output sequence item by item. The encoder in our case is a CNN which produces a context vector by taking in our image features. The decoder is a Recurrent Neural Network. In his paper, Where to put the Image in an Image Caption Generator, Marc Tanti has introduced many architectures such as, init-inject, par-inject, pre-inject and merge, specifying where an image should be injected while creating an image caption generator. We will use the merge architecture specified in his paper for our problem. In the “Merge” architecture the RNN is not exposed to the image vector (or a vector derived from the image vector) at any point. Instead, the image is introduced into the language model after the prefix has been encoded by the RNN in its entirety. This is a late binding architecture and it does not modify the image representation with every time step. Some important conclusions from his paper were used in our implemented architecture. They are: RNN output needs to be regularized with dropout. The image vector should not have a non-linear activation function or be regularized with dropout. The image input vector must be normalized before being fed to the neural network which was done while obtaining features from the CheXNet. EMBEDDING LAYER: A word embedding is a class of approaches for representing words and documents using a dense vector representation. Keras offers an Embedding layer that can be used for neural networks on text data. It can also use a word embedding learned elsewhere. It is common in the field of Natural Language Processing to learn, save, and make freely available word embeddings. In our model, with the embedding layer, each word has been mapped into a 300 dimensional representation using a pre-trained GLOVE model. While using a pre-trained embedding, keep in mind that the weights of the layer should be frozen by setting the argument ‘trainable=False’ so that the weights don’t get updated while training. Model Code: Model Summary: LOSS FUNCTION: A Masked Loss Function was created for this problem. For eg: If we have a sequence of tokens- [3],[10],[7],[0],[0],[0],[0],[0] We only have 3 words in this sequence, the zeros correspond to the padding which is actually not a part of the report. But the model will think that the zeros are also a part of the sequence and will start learning them. When the model starts to correctly predict the zeros, the loss will decrease because for the model it is learning correctly. But for us the loss should only decrease if the model is predicting the actual words(non-zeros) correctly. Therefore we should mask the zeros in the sequence so that the model don’t give its attention to them and only learns the needed words in the report. The output words are One-Hot-Encoded, therefore CategoricalCrossentropy will be our loss function. optimizer = tf.keras.optimizers.Adam(0.001)encoder_decoder.compile(optimizer, loss = maskedLoss) Remember our data generators? Now it’s time to use them. Here, the batches provided by the generator are not the actual batches of data that we use for training. Remember that they are not word by word input-output pairs. They just return the image and its corresponding whole report. We will retrieve each batch from the generator and will manually create input-output sequences from that set of batches, i.e we will create our own custom batches of data for training. So here, the BATCH_SIZE logically turns out to be the number of image pairs the model will see in a single batch. We can vary it depending on our system capability. I found this method to be way faster than the traditional custom generators mentioned in other blogs. Since we are creating our own batches of data for training, we will be using “train_on_batch” for training our model. The convert function mentioned in the code converts the data from the generator to a word by word input-output pair representation. Then the partial reports were padded to the maximum length of the reports. Convert Function: Adam optimizer was used with a learning rate of 0.001. The model was trained for 40 epochs but the best results were obtained at the 35th epoch. The results you get might vary due to the stochastic nature. NOTE: Above training has been implemented in Tensorflow 2.1. Now that we have trained our model, it’s time to prepare our model to predict reports. For this purpose we have to make some adjustments in our model. This will save us some time during testing. First we will separate the encoder and decoder part from our model. The features predicted by the encoder will be used as the input to our decoder along with the partial reports. By doing this we will only need to predict the encoder features just once while we use that for our greedy search and beam search algorithms. We will implement both these algorithms for generating text and will see which one works best. Greedy search is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious benefit. GREEDY SEARCH STEPS: The encoder outputs the features of our image. The encoder’s job is finished here. We don’t need to attend to the encoder once we have the features we need.This feature vector along with the start token- ‘startseq’(our initial input sequence) is given as the first input to the decoder.The decoder predicts a probability distribution across the whole vocabulary and the word with the maximum probability will be chosen as the next word.This predicted word along with the previous input sequence will be our next input sequence to the decoder.Steps 3-4 are continued till we encounter the end token i.e ‘endseq’. The encoder outputs the features of our image. The encoder’s job is finished here. We don’t need to attend to the encoder once we have the features we need. This feature vector along with the start token- ‘startseq’(our initial input sequence) is given as the first input to the decoder. The decoder predicts a probability distribution across the whole vocabulary and the word with the maximum probability will be chosen as the next word. This predicted word along with the previous input sequence will be our next input sequence to the decoder. Steps 3-4 are continued till we encounter the end token i.e ‘endseq’. Let’s check how our model is performing after using greedysearch for report generation. BLEU Score — Greedy Search : The Bilingual Evaluation Understudy Score, or BLEU for short, is a metric for evaluating a generated sentence to a reference sentence. A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0. The approach works by counting matching n-grams in the candidate text to n-grams in the reference text, where 1-gram or uni-gram would be each token and a bi-gram comparison would be each word pair. A perfect score is not possible in practice as a translation would have to match the reference exactly. This is not even possible by human translators. The number and quality of the references used to calculate the BLEU score means that comparing scores across datasets can be troublesome. To learn more about BLEU, click here. Beam search is an algorithm that expands upon the greedy search and returns a list of most likely output sequences. Each sequence will have a score associated with it. The sequence with the highest score is taken as the final result. Instead of greedily choosing the most likely next step as the sequence is constructed, the beam search expands all possible next steps and keeps the k most likely, where k, known as the beam width, is a user-specified parameter and controls the number of beams or parallel searches through the sequence of probabilities. A beam search with a beam width of 1 is nothing but your greedy search. Common beam width values are 5–10 but even values as high as 1000 or 2000 above are used in researches to squeeze out the best performance from a model. To read more about beam search, click here. But keep in mind that with increasing beam width the time complexity also increases. Therefore these are much slower than greedy search. A beam search doesn’t always guarantee better results but in most cases it gives you one. You can check your BLEU scores for beam search using the function given above. But keep in mind that it takes a while(a few hours) to evaluate them. Now let’s see some predicted reports for our chest X-rays: Original report for Image Pair 1 : “the heart normal size. the mediastinum unremarkable. the lungs are clear.” Predicted report for Image Pair 1 : “the heart normal size. the mediastinum unremarkable. the lungs are clear.” The model is predicting the exact same report for this example. Original report for Image Pair 2 : “heart size and pulmonary vascularity within normal limits. no focal infiltrate pneumothora pleural effusion identified.” Predicted report for Image Pair 2 : “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.” Though not exactly same, the predicted is almost similar to the original report. Original report for Image Pair 3 : “lungs are hyperinflated but clear. no focal infiltrate effusion. heart and mediastinal contours within normal limits. calcified mediastinal identified.” Predicted report for Image Pair 3 : “the heart size normal. the mediastinal contour within normal limits. the lungs are free any focal infiltrates. there are no nodules masses. no visible pneumothora. no visible pleural fluid. the are grossly normal. there no visible free intraperitoneal air under the diaphragm.” Well you didn’t expect the model to work flawlessly, did you? No model is perfect, this one ain’t either. Although there are some details which are correctly identified from the image pair 3, there are a lot of extra details produced which may or may not be correct. The model we created is in no way a perfect one, but it does generate decent reports for our images. Let’s now look at an advanced model and see whether it improves the current performance or not!! The attention mechanism was proposed as an improvement to the encoder-decoder models. The context vector turned out to be a bottleneck for these types of models. It made it challenging for them to deal with long sentences. A solution was proposed in Bahdanau et al., 2014 and Luong et al., 2015. These papers introduced and refined a technique called “Attention”, which highly improved the quality of machine translation systems. Attention allows the model to focus on the relevant parts of the input sequence as needed. Later this idea was implemented for image captioning in the paper, Show, Attend and Tell: Neural Image Caption Generation with Visual Attention. So, how do we model an attention mechanism for images? In the case of text, we have a representation for every location of the input sequence. But for images we typically use representation from one of the fully connected layers of a network, but this representation do not contain any location information(Just think about it, they are fully connected). We need to look at specific portions (locations) of an image to describe what’s there. For example, to describe the size of a person’s heart from the x-ray, we need to look at only his heart area and not his arms or any other part. So what should be the input to the Attention Mechanism? Well, instead of the fully connected representation, we use the output from one of the convolution layers(transfer learning) which has spatial information. For example, let the output of the last convolutional layer be a (7*14*1024) size feature map. Here, the ‘7*14’ are the actual locations which corresponds to certain portions in the image and 1024 are the channels. We are not paying attention to the channels but to the locations of the image. Therefore, here we have 7*14 = 98 such locations. We can think of it as 98 locations each having a 1024 dimensional representation. Now we have 98 time steps with 1024 dimensional representations each. We need to now decide how the model should pay attention to these 98 time steps or locations. A simple way is to assign some weights to each location and get a weighted sum of all these 98 locations. If a particular time step is very important in predicting an output, that time step will have a higher weight. Let these weights be denoted as alphas. Now we know that, the alphas determine the importance of a particular location. Higher the alpha, higher the importance. But how do we find the values of alpha? No one is going to give us these values, the model itself should learn these values from the data. To enable this we define a function: This quantity captures the importance of the j_th input for decoding the t_th output. h_j is the j_th location represention and s_t-1 is the state of the decoder till that point. We need these two mentioned quantities to determine e_jt. f_ATT is just a function which we will define later. Across all the inputs, now we want this quantity(e_jt) to sum to 1. It’s just like taking a probability distribution over which input is important by how much. The e_jt is converted into a probability distribution by taking softmax. Now we have our alphas.! Alphas are our softmax of e_jts. Alpha_jt denotes the probability of focusing on the j_th input to produce the t_th output. Its time to define our function f_ATT. One among many other possible choices is the following: V, U and W are the parameters which will be learned during the training to determine the value of e_jt. We have the alphas, we have the inputs, now we just need to get the weighted sum to produce the new context vector which will be fed to the decoder. In practice these models work better than the encoder decoder models. Like the encoder-decoder model mentioned above, this model will also consist of 2 parts, an encoder and a decoder but this time the decoder will have an extra component of attention in it, i.e a one-step attention decoder. Let’s now write the above explained steps of attention in code for better understanding: The onestep attention layer will consist of the attention part whichwill be calculated for each time step of the decoder.# Calculating e_jtsscore = self.Vattn(tf.nn.tanh(self.Uattn(features) + self.Wattn(hidden_with_time_axis)))# Converting our scores to probability distributions using softmaxattention_weights = tf.nn.softmax(score, axis=1)# Calculating the context vector(weighted sum)context_vector = attention_weights * features We will be using the sub-classing API of keras which gives us more customisability and control over our architecture. You can read more about the sub class API here from the documentation itself. We will be implementing teacher forcing to train our model and this time we won’t have to convert our text into a word by word model. But for image features, we’ll be taking the features from the last conv layer of the CheXNet network. The final output shape after combining our 2 images will be (None, 7, 14, 1024). So the input to the encoder after reshaping will be (None, 98, 1024). Why reshaping? Well, this has been explained in the attention intro, if you have any doubts, make sure you read the explanation once more. Model: Encoder Encoder The encoder layer just performs some operations on our image and outputs the features which will be fed as input to the decoder. 2. Decoder The decoder calls the one-step attention layer for each of the decoder time-steps and computes the scores and attention-weights. All the outputs of each time-steps are stored in ‘all-outputs’ variable. The outputs from the each decoder steps are the next word in the sequence. ‘all-outputs’ will be our final output. 3. OneStepDecoder 4. Creating the Model model1 = Attention_Model(vocab_size, units, max_capt_len, att_units, BATCH_SIZE) As mentioned before we will be using teacher forcing to train our model. Therefore we won’t be needing the extra functions that we used for encoder decoder model. We can directly use our custom reports from the generator. The ‘train_dataset’ is our generator which gives us the image features and the corresponding 155 dimensional padded reports. # teacher forcingres = model1.train_on_batch([img, rep[:,:-1]], rep[:,1:]) As you can see the input to the decoder is one time-step behind the output. We don’t want the model to predict the same input as output. We want it to predict the next word in the sequence. For attention too, Adam optimizer was used with a learning rate of 0.001. The model was giving decent results with just 10 epochs of training. The results you get might vary due to the stochastic nature. Sparse_Categorical_crossentropy was the loss function used in this case since we are not converting the output to OHE vectors. The code for everything can be accessed from my GitHub. It’s link has been provided at the end of this blog. Now that we have build our model, let’s check if the BLEU scores obtained is actually an improvement over the previous model or not: We can see that it has better performance than the encoder-decoder model with greedy search. Hence it’s definitely an improvement over the previous one. Now let’s see some scores for beam search: The BLEU scores are lower than that of greedy but they are not far-off. But it’s noticeable that with increasing beam_width the scores are actually increasing. So, there might be some value of beam_width where the scores actually do cross the greedy values. Below are some reports generated by the model using greedy search: Original report for Image Pair 1: “heart size and pulmonary vascularity within normal limits. no focal infiltrate pneumothora pleural effusion identified.” Predicted report for Image Pair 1: “the heart size and mediastinal contours are within normal limits. the lungs are clear. there no pneumothora pleural effusion. there are no acute bony findings.” The predictions are almost similar to the original report. Original report for Image Pair 2: “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.” Predicted report for Image Pair 2: “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.” The predicted report is exactly the same!! Original report for Image Pair 3: “the heart normal size. the mediastinum unremarkable. the lungs are clear.” Predicted report for Image Pair 3: “the heart normal size. the mediastinum unremarkable. the lungs are clear .” In this example too, the model is doing a really good job. Original report for Image Pair 4: “the lungs are clear bilaterally. specifically no evidence focal consolidation pneumothora pleural effusion. cardio mediastinal silhouette unremarkable. visualized osseous structures the thora are without acute abnormality.” Predicted report for Image Pair 4: “the heart size and mediastinal contours are within normal limits. the lungs are clear. there no pneumothora pleural effusion.” You can see that this prediction is not really convincing. “But the beam search for this example was predicting the exact same report even though it was producing lower BLEU scores for the whole test data combined!!!” So, which one to choose? Well, it’s up to us. Just pick a method that generalizes well. Here, even our attention model can’t predict each and every image accurately. As we can see from the example, this pair do not have a side view image or if we look at the words in the original report there are some complex words which through some EDA can be found that it doesn’t occur that often. These might be some of the reasons we do not have a good prediction in some of the cases. Keep in mind that we are just training this model on 2560 data points. To learn more complex features, the model will need more data. Now that we have come to an end to this project, let’s summarize what all we’ve done: We just saw an application of image captioning in the medical field. We understood the problem and the need for such an application. We saw how to use data generators for the input pipeline. Created an Encoder-Decoder model which gave us decent results. Improved the base results by building an Attention model. As we mentioned we didn’t have a big dataset for this task. A larger dataset will produce better results. No major hyperparameter tuning were done for any of the models. Therefore, a better hyperparameter tuning might produce better results. Making use of little more advanced techniques like transformers or BERT, might yield better results. https://www.appliedaicourse.com/https://arxiv.org/abs/1502.03044https://www.aclweb.org/anthology/P18-1240/https://arxiv.org/abs/1703.09137https://arxiv.org/abs/1409.0473https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/ https://www.appliedaicourse.com/ https://arxiv.org/abs/1502.03044 https://www.aclweb.org/anthology/P18-1240/ https://arxiv.org/abs/1703.09137 https://arxiv.org/abs/1409.0473 https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/ The entire code for this project can be accessed from my GitHub. You can also connect with me on my LinkedIn. Hope you enjoyed this project. Thanks for reading :)
[ { "code": null, "e": 536, "s": 172, "text": "Introduction — Understanding the problemPrerequisitesDataObtaining Structured DataPrepare Text Data — Natural Language ProcessingObtaining Image Features — Transfer LearningInput Pipeline — Data GeneratorsEncoder-Decoder Model — Training, Greedy Search, Beam Search, BLEUAttention Mechanism — Training, Greedy Search, Beam Search, BLEUSummaryFuture WorkReferences" }, { "code": null, "e": 577, "s": 536, "text": "Introduction — Understanding the problem" }, { "code": null, "e": 591, "s": 577, "text": "Prerequisites" }, { "code": null, "e": 596, "s": 591, "text": "Data" }, { "code": null, "e": 622, "s": 596, "text": "Obtaining Structured Data" }, { "code": null, "e": 670, "s": 622, "text": "Prepare Text Data — Natural Language Processing" }, { "code": null, "e": 715, "s": 670, "text": "Obtaining Image Features — Transfer Learning" }, { "code": null, "e": 748, "s": 715, "text": "Input Pipeline — Data Generators" }, { "code": null, "e": 815, "s": 748, "text": "Encoder-Decoder Model — Training, Greedy Search, Beam Search, BLEU" }, { "code": null, "e": 880, "s": 815, "text": "Attention Mechanism — Training, Greedy Search, Beam Search, BLEU" }, { "code": null, "e": 888, "s": 880, "text": "Summary" }, { "code": null, "e": 900, "s": 888, "text": "Future Work" }, { "code": null, "e": 911, "s": 900, "text": "References" }, { "code": null, "e": 1123, "s": 911, "text": "Image Captioning is a challenging artificial intelligence problem which refers to the process of generating textual description from an image based on the image contents. For instance, look at the picture below:" }, { "code": null, "e": 1317, "s": 1123, "text": "A common answer would be “A woman playing a guitar”. We as humans can look at a picture and describe whatever it is in it, in an appropriate language. This is easy. Let me show you another one:" }, { "code": null, "e": 1768, "s": 1317, "text": "For all of us ‘non-radiologists’, a common answer would be “a chest x-ray”. Well, we are not wrong but a radiologist might have some different interpretations. They write textual reports to narrate the findings regarding each area of the body examined in the imaging study, specifically whether each area was found to be normal, abnormal or potentially abnormal. They can derive such valuable information and make medical reports from one such image." }, { "code": null, "e": 2087, "s": 1768, "text": "For less-experienced radiologists and pathologists, especially those working in the rural areas where the quality of healthcare is relatively low, writing medical-imaging reports is demanding or on the other hand for experienced radiologists and pathologists, writing imaging reports can be tedious and time consuming." }, { "code": null, "e": 2277, "s": 2087, "text": "So, to address all these matters, wouldn’t it be great if a computer can take a chest x-ray like the one above as input and output the findings as text just like how a radiologist would do?" }, { "code": null, "e": 2394, "s": 2277, "text": "But, can you indeed write such a computer program? Well, if the answer was ‘no’, you wouldn’t be reading this story." }, { "code": null, "e": 2662, "s": 2394, "text": "This work assumes some deep learning familiarity with topics like Neural Nets, CNNs, RNNs, Transfer Learning, Python programming and Keras library. The two below mentioned models will be used for our problem, which will be explained briefly later in this blog itself:" }, { "code": null, "e": 2703, "s": 2662, "text": "Encoder-Decoder ModelAttention-Mechanism" }, { "code": null, "e": 2725, "s": 2703, "text": "Encoder-Decoder Model" }, { "code": null, "e": 2745, "s": 2725, "text": "Attention-Mechanism" }, { "code": null, "e": 2817, "s": 2745, "text": "Decent knowledge about them will help you understand the models better." }, { "code": null, "e": 2887, "s": 2817, "text": "You can obtain the data needed for this problem from the below links:" }, { "code": null, "e": 2926, "s": 2887, "text": "Images- Contains all the chest X-rays." }, { "code": null, "e": 2992, "s": 2926, "text": "Reports- Contains the corresponding reports for the above images." }, { "code": null, "e": 3395, "s": 2992, "text": "The image dataset contains multiple chest x-rays of a single person. For instance: side-view of the x-ray, multiple frontal views etc. Just as a radiologist uses all these images to write the findings, the models will also use all these images together to generate the corresponding findings. There are 3955 reports present in the dataset, with each report having one or more images associated with it." }, { "code": null, "e": 3611, "s": 3395, "text": "The reports in the dataset are XML files where each file corresponds to an individual. The image IDs and the corresponding findings associated with that person is contained in these files. An example is shown below:" }, { "code": null, "e": 3746, "s": 3611, "text": "The highlighted info are the things that you need to extract from these files. This can be done with the help of python’s XML library." }, { "code": null, "e": 3861, "s": 3746, "text": "NOTE: The findings will be also referred to as reports. They will be used interchangeably in the rest of the blog." }, { "code": null, "e": 4261, "s": 3861, "text": "After extracting the required data from the XML files, the data is converted into a structured format for easy understanding and accessibility. As mentioned before, there are multiple images associated with a single report. Therefore, our model also needs to see these images while generating reports. But some reports have only 1 image associated with it, while some have 2 and the maximum being 4." }, { "code": null, "e": 4548, "s": 4261, "text": "So the question arises, how many images should we feed into the model at a time to generate a report? To make the model-input consistent, pairs of images i.e two images were chosen at a time as input. If a report only had 1 image, the same image would be replicated as the second input." }, { "code": null, "e": 4724, "s": 4548, "text": "Now we have a proper and understandable structured data to work with. The images are saved by the names of their absolute address. This will be helpful while loading the data." }, { "code": null, "e": 5103, "s": 4724, "text": "After the final step, we will have data points of an individual multiple times. For example, if a person has four images associated with the report and since we are taking pairs of images, multiple data points of that person will be generated. Therefore it is necessary to split this dataset w.r.t individuals rather than the generated data points to avoid data leakage problem." }, { "code": null, "e": 5251, "s": 5103, "text": "Before making pairs of images, make sure you split the data into train, cv and test using the unique ‘person_id’ feature, and then train the model." }, { "code": null, "e": 5463, "s": 5251, "text": "After obtaining the findings from the XML file, they should be properly cleaned and prepared before we feed it into the model. Below image shows a few examples of how findings would look like before its cleaned." }, { "code": null, "e": 5509, "s": 5463, "text": "We will clean the text in the following ways:" }, { "code": null, "e": 6439, "s": 5509, "text": "Convert all characters into lowercase.Perform basic decontractions i.e words like won’t, can’t and so on will be converted to will not, cannot and so on respectively.Remove punctuation from text. Note that full stop will not be removed because the findings contain multiple sentences, so we need the model to generate reports in a similar way by identifying sentences.Remove all numbers from the text.Remove all words with length less than or equal to 2. For example, ‘is’, ‘to’ etc are removed. These words don’t provide much information. But the word ‘no’ will not be removed since it adds value. Adding ‘no’ to a sentence changes its meaning entirely. So we have to be careful while performing these kind of cleaning steps. You need to identify which words to keep and which ones to avoid.It was also found that some texts contain multiple full stops or spaces or ‘X’ repeated multiple times. Such characters are also removed." }, { "code": null, "e": 6478, "s": 6439, "text": "Convert all characters into lowercase." }, { "code": null, "e": 6607, "s": 6478, "text": "Perform basic decontractions i.e words like won’t, can’t and so on will be converted to will not, cannot and so on respectively." }, { "code": null, "e": 6810, "s": 6607, "text": "Remove punctuation from text. Note that full stop will not be removed because the findings contain multiple sentences, so we need the model to generate reports in a similar way by identifying sentences." }, { "code": null, "e": 6844, "s": 6810, "text": "Remove all numbers from the text." }, { "code": null, "e": 7236, "s": 6844, "text": "Remove all words with length less than or equal to 2. For example, ‘is’, ‘to’ etc are removed. These words don’t provide much information. But the word ‘no’ will not be removed since it adds value. Adding ‘no’ to a sentence changes its meaning entirely. So we have to be careful while performing these kind of cleaning steps. You need to identify which words to keep and which ones to avoid." }, { "code": null, "e": 7374, "s": 7236, "text": "It was also found that some texts contain multiple full stops or spaces or ‘X’ repeated multiple times. Such characters are also removed." }, { "code": null, "e": 7924, "s": 7374, "text": "The model we will develop will generate a report given a combination of two images, and the report will be generated one word at a time. The sequence of previously generated words will be provided as input. Therefore, we will need a ‘first word’ to kick-off the generation process and a ‘last word’ to signal the end of the report. We will use the strings ‘startseq’ and ‘endseq’ for this purpose. These strings are added to our findings. It is important to do this now because when we encode the text, we need these strings to be encoded correctly." }, { "code": null, "e": 8462, "s": 7924, "text": "The major step in encoding text is to create a consistent mapping from words to unique integer values known as tokenization. In order to get our computer to understand any text, we need to break that word or sentence down in a way that our machine can understand. We can’t work with text data if we don’t perform tokenization. Tokenization is a way of separating a piece of text into smaller units called tokens. Tokens can be either words or characters but in our case it’ll be words. Keras provides an inbuilt library for this purpose." }, { "code": null, "e": 8619, "s": 8462, "text": "from tensorflow.keras.preprocessing.text import Tokenizertokenizer = Tokenizer(filters='!\"#$%&()*+,-/:;<=>?@[\\\\]^_`{|}~\\t\\n')tokenizer.fit_on_texts(reports)" }, { "code": null, "e": 8806, "s": 8619, "text": "Now the text that we have are properly cleaned and tokenized for future use. The full code for all this is available in my GitHub account whose link is provided at the end of this story." }, { "code": null, "e": 9019, "s": 8806, "text": "Images along with partial reports are the inputs to our model. We need to convert every image into a fixed sized vector which can then be fed as input to the model. We will use transfer learning for this purpose." }, { "code": null, "e": 9381, "s": 9019, "text": "“In transfer learning, we first train a base network on a base dataset and task, and then we re-purpose the learned features, or transfer them, to a second target network to be trained on a target dataset and task. This process will tend to work if the features are general, meaning suitable to both base and target tasks, instead of specific to the base task.”" }, { "code": null, "e": 9682, "s": 9381, "text": "VGG16, VGG19 or InceptionV3 are the common CNNs used for transfer learning. These are trained on datasets like Imagenets whose images are completely different from that of a chest x-ray. So logically, they doesn’t seem to be a good choice for our task. So which network should we use for our problem?" }, { "code": null, "e": 10129, "s": 9682, "text": "If you are unfamiliar, let me introduce you to CheXNet. CheXNet, is a 121-layer convolutional neural network trained on ChestX-ray14, currently the largest publicly available chest X-ray dataset, containing over 100,000 frontal-view X-ray images with 14 diseases. However, our purpose here is not to classify the images but just to get the bottleneck features for each image. Therefore the last classification layer of this network is not needed." }, { "code": null, "e": 10188, "s": 10129, "text": "You can download the trained weights of CheXNet from here." }, { "code": null, "e": 10583, "s": 10188, "text": "from tensorflow.keras.applications import densenetchex = densenet.DenseNet121(include_top=False, weights = None, input_shape=(224,224,3), pooling=\"avg\")X = chex.outputX = Dense(14, activation=\"sigmoid\", name=\"predictions\")(X)model = Model(inputs=chex.input, outputs=X)model.load_weights('load_the_downloaded_weights.h5')chexnet = Model(inputs = model.input, outputs = model.layers[-2].output)" }, { "code": null, "e": 10692, "s": 10583, "text": "If you forgot, we have 2 images as input to our model. So, here is how the bottleneck features are obtained:" }, { "code": null, "e": 11313, "s": 10692, "text": "Each image is resized to (224,224,3) and is passed through the CheXNet and a 1024 length feature vector is obtained. Later both these feature vectors are concatenated to obtain a 2048 feature vector. If you notice, we have added an average pooling layer as the last layer. There’s a specific reason for this. Since we are concatenating both images, the model might learn some order of concatenation. For example, image1 always comes after image2 or vice-versa, but that isn’t the case here. We are not keeping any order while concatenating them. This problem is solved through pooling which creates location in-variance." }, { "code": null, "e": 11346, "s": 11313, "text": "The code for this is as follows:" }, { "code": null, "e": 11445, "s": 11346, "text": "These features are stored in a dictionary in pickle format, which can be used for future purposes." }, { "code": null, "e": 11614, "s": 11445, "text": "Consider a scenario where you have lots of data, so much that you cannot have all of it at once in the RAM. Purchasing more RAM is obviously not an option for everyone." }, { "code": null, "e": 12037, "s": 11614, "text": "The solution can be to feed mini-batches of our data into the model dynamically. This is exactly what data generators do. They can generate the model input dynamically thus forming a pipeline from the storage to the RAM to load the data as and when it is required. Another advantage of this pipeline is, one can easily apply preprocessing routines on these mini-batches of data as they are prepared to feed into the model." }, { "code": null, "e": 12079, "s": 12037, "text": "We will be using tf.data for our problem." }, { "code": null, "e": 12415, "s": 12079, "text": "We will first divide our dataset into two parts, a train dataset and a validation dataset. While dividing, just make sure that you have enough data points for training and a decent amount for validation as well. The proportion that I chose allowed me to have 2560 data points in my train set and 1147 data points in the validation set." }, { "code": null, "e": 12477, "s": 12415, "text": "Now it’s time for us to create the generator for our dataset." }, { "code": null, "e": 12823, "s": 12477, "text": "Here we created two data generators, train_dataset for training and cv_dataset for validation. The create_dataset function takes the IDs (which are keys of the dictionary, for the bottleneck features created earlier) and the preprocessed reports, and creates the generator. The generator generates the BATCH_SIZE number of data points at a time." }, { "code": null, "e": 13025, "s": 12823, "text": "As mentioned earlier the model that we are going to create will be a word by word model. The model takes as input the image features and the partial sequences to generate the next word in the sequence." }, { "code": null, "e": 13186, "s": 13025, "text": "For example: Let the report corresponding to the ‘Image_features_1’ be — “startseq the cardiac silhouette and mediastinum size are within normal limits endseq”." }, { "code": null, "e": 13272, "s": 13186, "text": "Then the input sequence would be split into 11 input-output pairs to train the model:" }, { "code": null, "e": 13592, "s": 13272, "text": "Note that we are NOT creating these input-output pairs through the generator. The generator only provides us with the BATCH_SIZE number of image features and their corresponding complete reports at a time. The input-output pairs are generated later during the training process, which will be explained in a short while." }, { "code": null, "e": 13762, "s": 13592, "text": "A sequence-to-sequence model is a deep learning model that takes a sequence of items (in our case, features of an image) and outputs another sequence of items (reports)." }, { "code": null, "e": 14043, "s": 13762, "text": "The encoder processes each item in the input sequence, it compiles the information it captures into a vector called the context. After processing the entire input sequence, the encoder sends the context over to the decoder, which begins producing the output sequence item by item." }, { "code": null, "e": 14184, "s": 14043, "text": "The encoder in our case is a CNN which produces a context vector by taking in our image features. The decoder is a Recurrent Neural Network." }, { "code": null, "e": 14516, "s": 14184, "text": "In his paper, Where to put the Image in an Image Caption Generator, Marc Tanti has introduced many architectures such as, init-inject, par-inject, pre-inject and merge, specifying where an image should be injected while creating an image caption generator. We will use the merge architecture specified in his paper for our problem." }, { "code": null, "e": 14870, "s": 14516, "text": "In the “Merge” architecture the RNN is not exposed to the image vector (or a vector derived from the image vector) at any point. Instead, the image is introduced into the language model after the prefix has been encoded by the RNN in its entirety. This is a late binding architecture and it does not modify the image representation with every time step." }, { "code": null, "e": 14965, "s": 14870, "text": "Some important conclusions from his paper were used in our implemented architecture. They are:" }, { "code": null, "e": 15014, "s": 14965, "text": "RNN output needs to be regularized with dropout." }, { "code": null, "e": 15112, "s": 15014, "text": "The image vector should not have a non-linear activation function or be regularized with dropout." }, { "code": null, "e": 15251, "s": 15112, "text": "The image input vector must be normalized before being fed to the neural network which was done while obtaining features from the CheXNet." }, { "code": null, "e": 15268, "s": 15251, "text": "EMBEDDING LAYER:" }, { "code": null, "e": 15635, "s": 15268, "text": "A word embedding is a class of approaches for representing words and documents using a dense vector representation. Keras offers an Embedding layer that can be used for neural networks on text data. It can also use a word embedding learned elsewhere. It is common in the field of Natural Language Processing to learn, save, and make freely available word embeddings." }, { "code": null, "e": 15965, "s": 15635, "text": "In our model, with the embedding layer, each word has been mapped into a 300 dimensional representation using a pre-trained GLOVE model. While using a pre-trained embedding, keep in mind that the weights of the layer should be frozen by setting the argument ‘trainable=False’ so that the weights don’t get updated while training." }, { "code": null, "e": 15977, "s": 15965, "text": "Model Code:" }, { "code": null, "e": 15992, "s": 15977, "text": "Model Summary:" }, { "code": null, "e": 16007, "s": 15992, "text": "LOSS FUNCTION:" }, { "code": null, "e": 16068, "s": 16007, "text": "A Masked Loss Function was created for this problem. For eg:" }, { "code": null, "e": 16134, "s": 16068, "text": "If we have a sequence of tokens- [3],[10],[7],[0],[0],[0],[0],[0]" }, { "code": null, "e": 16587, "s": 16134, "text": "We only have 3 words in this sequence, the zeros correspond to the padding which is actually not a part of the report. But the model will think that the zeros are also a part of the sequence and will start learning them. When the model starts to correctly predict the zeros, the loss will decrease because for the model it is learning correctly. But for us the loss should only decrease if the model is predicting the actual words(non-zeros) correctly." }, { "code": null, "e": 16737, "s": 16587, "text": "Therefore we should mask the zeros in the sequence so that the model don’t give its attention to them and only learns the needed words in the report." }, { "code": null, "e": 16836, "s": 16737, "text": "The output words are One-Hot-Encoded, therefore CategoricalCrossentropy will be our loss function." }, { "code": null, "e": 16933, "s": 16836, "text": "optimizer = tf.keras.optimizers.Adam(0.001)encoder_decoder.compile(optimizer, loss = maskedLoss)" }, { "code": null, "e": 16990, "s": 16933, "text": "Remember our data generators? Now it’s time to use them." }, { "code": null, "e": 17218, "s": 16990, "text": "Here, the batches provided by the generator are not the actual batches of data that we use for training. Remember that they are not word by word input-output pairs. They just return the image and its corresponding whole report." }, { "code": null, "e": 17670, "s": 17218, "text": "We will retrieve each batch from the generator and will manually create input-output sequences from that set of batches, i.e we will create our own custom batches of data for training. So here, the BATCH_SIZE logically turns out to be the number of image pairs the model will see in a single batch. We can vary it depending on our system capability. I found this method to be way faster than the traditional custom generators mentioned in other blogs." }, { "code": null, "e": 17788, "s": 17670, "text": "Since we are creating our own batches of data for training, we will be using “train_on_batch” for training our model." }, { "code": null, "e": 17995, "s": 17788, "text": "The convert function mentioned in the code converts the data from the generator to a word by word input-output pair representation. Then the partial reports were padded to the maximum length of the reports." }, { "code": null, "e": 18013, "s": 17995, "text": "Convert Function:" }, { "code": null, "e": 18219, "s": 18013, "text": "Adam optimizer was used with a learning rate of 0.001. The model was trained for 40 epochs but the best results were obtained at the 35th epoch. The results you get might vary due to the stochastic nature." }, { "code": null, "e": 18280, "s": 18219, "text": "NOTE: Above training has been implemented in Tensorflow 2.1." }, { "code": null, "e": 18367, "s": 18280, "text": "Now that we have trained our model, it’s time to prepare our model to predict reports." }, { "code": null, "e": 18475, "s": 18367, "text": "For this purpose we have to make some adjustments in our model. This will save us some time during testing." }, { "code": null, "e": 18654, "s": 18475, "text": "First we will separate the encoder and decoder part from our model. The features predicted by the encoder will be used as the input to our decoder along with the partial reports." }, { "code": null, "e": 18796, "s": 18654, "text": "By doing this we will only need to predict the encoder features just once while we use that for our greedy search and beam search algorithms." }, { "code": null, "e": 18891, "s": 18796, "text": "We will implement both these algorithms for generating text and will see which one works best." }, { "code": null, "e": 19043, "s": 18891, "text": "Greedy search is an algorithmic paradigm that builds up a solution piece by piece, always choosing the next piece that offers the most obvious benefit." }, { "code": null, "e": 19064, "s": 19043, "text": "GREEDY SEARCH STEPS:" }, { "code": null, "e": 19676, "s": 19064, "text": "The encoder outputs the features of our image. The encoder’s job is finished here. We don’t need to attend to the encoder once we have the features we need.This feature vector along with the start token- ‘startseq’(our initial input sequence) is given as the first input to the decoder.The decoder predicts a probability distribution across the whole vocabulary and the word with the maximum probability will be chosen as the next word.This predicted word along with the previous input sequence will be our next input sequence to the decoder.Steps 3-4 are continued till we encounter the end token i.e ‘endseq’." }, { "code": null, "e": 19833, "s": 19676, "text": "The encoder outputs the features of our image. The encoder’s job is finished here. We don’t need to attend to the encoder once we have the features we need." }, { "code": null, "e": 19964, "s": 19833, "text": "This feature vector along with the start token- ‘startseq’(our initial input sequence) is given as the first input to the decoder." }, { "code": null, "e": 20115, "s": 19964, "text": "The decoder predicts a probability distribution across the whole vocabulary and the word with the maximum probability will be chosen as the next word." }, { "code": null, "e": 20222, "s": 20115, "text": "This predicted word along with the previous input sequence will be our next input sequence to the decoder." }, { "code": null, "e": 20292, "s": 20222, "text": "Steps 3-4 are continued till we encounter the end token i.e ‘endseq’." }, { "code": null, "e": 20380, "s": 20292, "text": "Let’s check how our model is performing after using greedysearch for report generation." }, { "code": null, "e": 20409, "s": 20380, "text": "BLEU Score — Greedy Search :" }, { "code": null, "e": 20544, "s": 20409, "text": "The Bilingual Evaluation Understudy Score, or BLEU for short, is a metric for evaluating a generated sentence to a reference sentence." }, { "code": null, "e": 20840, "s": 20544, "text": "A perfect match results in a score of 1.0, whereas a perfect mismatch results in a score of 0.0. The approach works by counting matching n-grams in the candidate text to n-grams in the reference text, where 1-gram or uni-gram would be each token and a bi-gram comparison would be each word pair." }, { "code": null, "e": 21130, "s": 20840, "text": "A perfect score is not possible in practice as a translation would have to match the reference exactly. This is not even possible by human translators. The number and quality of the references used to calculate the BLEU score means that comparing scores across datasets can be troublesome." }, { "code": null, "e": 21168, "s": 21130, "text": "To learn more about BLEU, click here." }, { "code": null, "e": 21402, "s": 21168, "text": "Beam search is an algorithm that expands upon the greedy search and returns a list of most likely output sequences. Each sequence will have a score associated with it. The sequence with the highest score is taken as the final result." }, { "code": null, "e": 21723, "s": 21402, "text": "Instead of greedily choosing the most likely next step as the sequence is constructed, the beam search expands all possible next steps and keeps the k most likely, where k, known as the beam width, is a user-specified parameter and controls the number of beams or parallel searches through the sequence of probabilities." }, { "code": null, "e": 21992, "s": 21723, "text": "A beam search with a beam width of 1 is nothing but your greedy search. Common beam width values are 5–10 but even values as high as 1000 or 2000 above are used in researches to squeeze out the best performance from a model. To read more about beam search, click here." }, { "code": null, "e": 22129, "s": 21992, "text": "But keep in mind that with increasing beam width the time complexity also increases. Therefore these are much slower than greedy search." }, { "code": null, "e": 22219, "s": 22129, "text": "A beam search doesn’t always guarantee better results but in most cases it gives you one." }, { "code": null, "e": 22368, "s": 22219, "text": "You can check your BLEU scores for beam search using the function given above. But keep in mind that it takes a while(a few hours) to evaluate them." }, { "code": null, "e": 22427, "s": 22368, "text": "Now let’s see some predicted reports for our chest X-rays:" }, { "code": null, "e": 22538, "s": 22427, "text": "Original report for Image Pair 1 : “the heart normal size. the mediastinum unremarkable. the lungs are clear.”" }, { "code": null, "e": 22650, "s": 22538, "text": "Predicted report for Image Pair 1 : “the heart normal size. the mediastinum unremarkable. the lungs are clear.”" }, { "code": null, "e": 22714, "s": 22650, "text": "The model is predicting the exact same report for this example." }, { "code": null, "e": 22871, "s": 22714, "text": "Original report for Image Pair 2 : “heart size and pulmonary vascularity within normal limits. no focal infiltrate pneumothora pleural effusion identified.”" }, { "code": null, "e": 23060, "s": 22871, "text": "Predicted report for Image Pair 2 : “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.”" }, { "code": null, "e": 23141, "s": 23060, "text": "Though not exactly same, the predicted is almost similar to the original report." }, { "code": null, "e": 23330, "s": 23141, "text": "Original report for Image Pair 3 : “lungs are hyperinflated but clear. no focal infiltrate effusion. heart and mediastinal contours within normal limits. calcified mediastinal identified.”" }, { "code": null, "e": 23645, "s": 23330, "text": "Predicted report for Image Pair 3 : “the heart size normal. the mediastinal contour within normal limits. the lungs are free any focal infiltrates. there are no nodules masses. no visible pneumothora. no visible pleural fluid. the are grossly normal. there no visible free intraperitoneal air under the diaphragm.”" }, { "code": null, "e": 23912, "s": 23645, "text": "Well you didn’t expect the model to work flawlessly, did you? No model is perfect, this one ain’t either. Although there are some details which are correctly identified from the image pair 3, there are a lot of extra details produced which may or may not be correct." }, { "code": null, "e": 24013, "s": 23912, "text": "The model we created is in no way a perfect one, but it does generate decent reports for our images." }, { "code": null, "e": 24110, "s": 24013, "text": "Let’s now look at an advanced model and see whether it improves the current performance or not!!" }, { "code": null, "e": 24776, "s": 24110, "text": "The attention mechanism was proposed as an improvement to the encoder-decoder models. The context vector turned out to be a bottleneck for these types of models. It made it challenging for them to deal with long sentences. A solution was proposed in Bahdanau et al., 2014 and Luong et al., 2015. These papers introduced and refined a technique called “Attention”, which highly improved the quality of machine translation systems. Attention allows the model to focus on the relevant parts of the input sequence as needed. Later this idea was implemented for image captioning in the paper, Show, Attend and Tell: Neural Image Caption Generation with Visual Attention." }, { "code": null, "e": 24831, "s": 24776, "text": "So, how do we model an attention mechanism for images?" }, { "code": null, "e": 25419, "s": 24831, "text": "In the case of text, we have a representation for every location of the input sequence. But for images we typically use representation from one of the fully connected layers of a network, but this representation do not contain any location information(Just think about it, they are fully connected). We need to look at specific portions (locations) of an image to describe what’s there. For example, to describe the size of a person’s heart from the x-ray, we need to look at only his heart area and not his arms or any other part. So what should be the input to the Attention Mechanism?" }, { "code": null, "e": 25575, "s": 25419, "text": "Well, instead of the fully connected representation, we use the output from one of the convolution layers(transfer learning) which has spatial information." }, { "code": null, "e": 26001, "s": 25575, "text": "For example, let the output of the last convolutional layer be a (7*14*1024) size feature map. Here, the ‘7*14’ are the actual locations which corresponds to certain portions in the image and 1024 are the channels. We are not paying attention to the channels but to the locations of the image. Therefore, here we have 7*14 = 98 such locations. We can think of it as 98 locations each having a 1024 dimensional representation." }, { "code": null, "e": 26422, "s": 26001, "text": "Now we have 98 time steps with 1024 dimensional representations each. We need to now decide how the model should pay attention to these 98 time steps or locations. A simple way is to assign some weights to each location and get a weighted sum of all these 98 locations. If a particular time step is very important in predicting an output, that time step will have a higher weight. Let these weights be denoted as alphas." }, { "code": null, "e": 26719, "s": 26422, "text": "Now we know that, the alphas determine the importance of a particular location. Higher the alpha, higher the importance. But how do we find the values of alpha? No one is going to give us these values, the model itself should learn these values from the data. To enable this we define a function:" }, { "code": null, "e": 27009, "s": 26719, "text": "This quantity captures the importance of the j_th input for decoding the t_th output. h_j is the j_th location represention and s_t-1 is the state of the decoder till that point. We need these two mentioned quantities to determine e_jt. f_ATT is just a function which we will define later." }, { "code": null, "e": 27242, "s": 27009, "text": "Across all the inputs, now we want this quantity(e_jt) to sum to 1. It’s just like taking a probability distribution over which input is important by how much. The e_jt is converted into a probability distribution by taking softmax." }, { "code": null, "e": 27391, "s": 27242, "text": "Now we have our alphas.! Alphas are our softmax of e_jts. Alpha_jt denotes the probability of focusing on the j_th input to produce the t_th output." }, { "code": null, "e": 27486, "s": 27391, "text": "Its time to define our function f_ATT. One among many other possible choices is the following:" }, { "code": null, "e": 27590, "s": 27486, "text": "V, U and W are the parameters which will be learned during the training to determine the value of e_jt." }, { "code": null, "e": 27809, "s": 27590, "text": "We have the alphas, we have the inputs, now we just need to get the weighted sum to produce the new context vector which will be fed to the decoder. In practice these models work better than the encoder decoder models." }, { "code": null, "e": 28121, "s": 27809, "text": "Like the encoder-decoder model mentioned above, this model will also consist of 2 parts, an encoder and a decoder but this time the decoder will have an extra component of attention in it, i.e a one-step attention decoder. Let’s now write the above explained steps of attention in code for better understanding:" }, { "code": null, "e": 28555, "s": 28121, "text": "The onestep attention layer will consist of the attention part whichwill be calculated for each time step of the decoder.# Calculating e_jtsscore = self.Vattn(tf.nn.tanh(self.Uattn(features) + self.Wattn(hidden_with_time_axis)))# Converting our scores to probability distributions using softmaxattention_weights = tf.nn.softmax(score, axis=1)# Calculating the context vector(weighted sum)context_vector = attention_weights * features" }, { "code": null, "e": 28751, "s": 28555, "text": "We will be using the sub-classing API of keras which gives us more customisability and control over our architecture. You can read more about the sub class API here from the documentation itself." }, { "code": null, "e": 28987, "s": 28751, "text": "We will be implementing teacher forcing to train our model and this time we won’t have to convert our text into a word by word model. But for image features, we’ll be taking the features from the last conv layer of the CheXNet network." }, { "code": null, "e": 29277, "s": 28987, "text": "The final output shape after combining our 2 images will be (None, 7, 14, 1024). So the input to the encoder after reshaping will be (None, 98, 1024). Why reshaping? Well, this has been explained in the attention intro, if you have any doubts, make sure you read the explanation once more." }, { "code": null, "e": 29284, "s": 29277, "text": "Model:" }, { "code": null, "e": 29292, "s": 29284, "text": "Encoder" }, { "code": null, "e": 29300, "s": 29292, "text": "Encoder" }, { "code": null, "e": 29429, "s": 29300, "text": "The encoder layer just performs some operations on our image and outputs the features which will be fed as input to the decoder." }, { "code": null, "e": 29440, "s": 29429, "text": "2. Decoder" }, { "code": null, "e": 29757, "s": 29440, "text": "The decoder calls the one-step attention layer for each of the decoder time-steps and computes the scores and attention-weights. All the outputs of each time-steps are stored in ‘all-outputs’ variable. The outputs from the each decoder steps are the next word in the sequence. ‘all-outputs’ will be our final output." }, { "code": null, "e": 29775, "s": 29757, "text": "3. OneStepDecoder" }, { "code": null, "e": 29797, "s": 29775, "text": "4. Creating the Model" }, { "code": null, "e": 29878, "s": 29797, "text": "model1 = Attention_Model(vocab_size, units, max_capt_len, att_units, BATCH_SIZE)" }, { "code": null, "e": 30100, "s": 29878, "text": "As mentioned before we will be using teacher forcing to train our model. Therefore we won’t be needing the extra functions that we used for encoder decoder model. We can directly use our custom reports from the generator." }, { "code": null, "e": 30225, "s": 30100, "text": "The ‘train_dataset’ is our generator which gives us the image features and the corresponding 155 dimensional padded reports." }, { "code": null, "e": 30300, "s": 30225, "text": "# teacher forcingres = model1.train_on_batch([img, rep[:,:-1]], rep[:,1:])" }, { "code": null, "e": 30490, "s": 30300, "text": "As you can see the input to the decoder is one time-step behind the output. We don’t want the model to predict the same input as output. We want it to predict the next word in the sequence." }, { "code": null, "e": 30821, "s": 30490, "text": "For attention too, Adam optimizer was used with a learning rate of 0.001. The model was giving decent results with just 10 epochs of training. The results you get might vary due to the stochastic nature. Sparse_Categorical_crossentropy was the loss function used in this case since we are not converting the output to OHE vectors." }, { "code": null, "e": 30930, "s": 30821, "text": "The code for everything can be accessed from my GitHub. It’s link has been provided at the end of this blog." }, { "code": null, "e": 31063, "s": 30930, "text": "Now that we have build our model, let’s check if the BLEU scores obtained is actually an improvement over the previous model or not:" }, { "code": null, "e": 31216, "s": 31063, "text": "We can see that it has better performance than the encoder-decoder model with greedy search. Hence it’s definitely an improvement over the previous one." }, { "code": null, "e": 31259, "s": 31216, "text": "Now let’s see some scores for beam search:" }, { "code": null, "e": 31517, "s": 31259, "text": "The BLEU scores are lower than that of greedy but they are not far-off. But it’s noticeable that with increasing beam_width the scores are actually increasing. So, there might be some value of beam_width where the scores actually do cross the greedy values." }, { "code": null, "e": 31584, "s": 31517, "text": "Below are some reports generated by the model using greedy search:" }, { "code": null, "e": 31740, "s": 31584, "text": "Original report for Image Pair 1: “heart size and pulmonary vascularity within normal limits. no focal infiltrate pneumothora pleural effusion identified.”" }, { "code": null, "e": 31937, "s": 31740, "text": "Predicted report for Image Pair 1: “the heart size and mediastinal contours are within normal limits. the lungs are clear. there no pneumothora pleural effusion. there are no acute bony findings.”" }, { "code": null, "e": 31996, "s": 31937, "text": "The predictions are almost similar to the original report." }, { "code": null, "e": 32183, "s": 31996, "text": "Original report for Image Pair 2: “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.”" }, { "code": null, "e": 32371, "s": 32183, "text": "Predicted report for Image Pair 2: “the heart size and pulmonary vascularity appear within normal limits. the lungs are free focal airspace disease. no pleural effusion pneumothora seen.”" }, { "code": null, "e": 32414, "s": 32371, "text": "The predicted report is exactly the same!!" }, { "code": null, "e": 32524, "s": 32414, "text": "Original report for Image Pair 3: “the heart normal size. the mediastinum unremarkable. the lungs are clear.”" }, { "code": null, "e": 32636, "s": 32524, "text": "Predicted report for Image Pair 3: “the heart normal size. the mediastinum unremarkable. the lungs are clear .”" }, { "code": null, "e": 32695, "s": 32636, "text": "In this example too, the model is doing a really good job." }, { "code": null, "e": 32954, "s": 32695, "text": "Original report for Image Pair 4: “the lungs are clear bilaterally. specifically no evidence focal consolidation pneumothora pleural effusion. cardio mediastinal silhouette unremarkable. visualized osseous structures the thora are without acute abnormality.”" }, { "code": null, "e": 33117, "s": 32954, "text": "Predicted report for Image Pair 4: “the heart size and mediastinal contours are within normal limits. the lungs are clear. there no pneumothora pleural effusion.”" }, { "code": null, "e": 33176, "s": 33117, "text": "You can see that this prediction is not really convincing." }, { "code": null, "e": 33335, "s": 33176, "text": "“But the beam search for this example was predicting the exact same report even though it was producing lower BLEU scores for the whole test data combined!!!”" }, { "code": null, "e": 33423, "s": 33335, "text": "So, which one to choose? Well, it’s up to us. Just pick a method that generalizes well." }, { "code": null, "e": 33946, "s": 33423, "text": "Here, even our attention model can’t predict each and every image accurately. As we can see from the example, this pair do not have a side view image or if we look at the words in the original report there are some complex words which through some EDA can be found that it doesn’t occur that often. These might be some of the reasons we do not have a good prediction in some of the cases. Keep in mind that we are just training this model on 2560 data points. To learn more complex features, the model will need more data." }, { "code": null, "e": 34032, "s": 33946, "text": "Now that we have come to an end to this project, let’s summarize what all we’ve done:" }, { "code": null, "e": 34165, "s": 34032, "text": "We just saw an application of image captioning in the medical field. We understood the problem and the need for such an application." }, { "code": null, "e": 34223, "s": 34165, "text": "We saw how to use data generators for the input pipeline." }, { "code": null, "e": 34286, "s": 34223, "text": "Created an Encoder-Decoder model which gave us decent results." }, { "code": null, "e": 34344, "s": 34286, "text": "Improved the base results by building an Attention model." }, { "code": null, "e": 34450, "s": 34344, "text": "As we mentioned we didn’t have a big dataset for this task. A larger dataset will produce better results." }, { "code": null, "e": 34586, "s": 34450, "text": "No major hyperparameter tuning were done for any of the models. Therefore, a better hyperparameter tuning might produce better results." }, { "code": null, "e": 34687, "s": 34586, "text": "Making use of little more advanced techniques like transformers or BERT, might yield better results." }, { "code": null, "e": 34951, "s": 34687, "text": "https://www.appliedaicourse.com/https://arxiv.org/abs/1502.03044https://www.aclweb.org/anthology/P18-1240/https://arxiv.org/abs/1703.09137https://arxiv.org/abs/1409.0473https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/" }, { "code": null, "e": 34984, "s": 34951, "text": "https://www.appliedaicourse.com/" }, { "code": null, "e": 35017, "s": 34984, "text": "https://arxiv.org/abs/1502.03044" }, { "code": null, "e": 35060, "s": 35017, "text": "https://www.aclweb.org/anthology/P18-1240/" }, { "code": null, "e": 35093, "s": 35060, "text": "https://arxiv.org/abs/1703.09137" }, { "code": null, "e": 35125, "s": 35093, "text": "https://arxiv.org/abs/1409.0473" }, { "code": null, "e": 35220, "s": 35125, "text": "https://machinelearningmastery.com/develop-a-deep-learning-caption-generation-model-in-python/" }, { "code": null, "e": 35285, "s": 35220, "text": "The entire code for this project can be accessed from my GitHub." }, { "code": null, "e": 35330, "s": 35285, "text": "You can also connect with me on my LinkedIn." } ]
How can I get android device screen height, width?
This example demonstrates how do I get android device screen height, width. 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" tools:context=".MainActivity"> <TextView android:id="@+id/getScreenHeight" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20sp" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/getScreenWidth" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:textStyle="bold" /> <TextView android:id="@+id/getScreenInches" android:layout_marginTop="10dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="16sp" android:textStyle="bold" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView height, width, inches; DisplayMetrics displayMetrics; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); height = findViewById(R.id.getScreenHeight); width = findViewById(R.id.getScreenWidth); inches = findViewById(R.id.getScreenInches); displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); int screenHeight = displayMetrics.heightPixels; int screenWidth = displayMetrics.widthPixels; double y = Math.pow(screenHeight /displayMetrics.xdpi, 2); double x = Math.pow(screenWidth /displayMetrics.xdpi, 2); double screenInches = Math.sqrt(x + y); screenInches = (double) Math.round(screenInches *10)/10; height.setText("Screen Height: " + screenHeight); width.setText("Screen Height: " + screenWidth); inches.setText("Screen Inches: " + screenInches); } } 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": 1138, "s": 1062, "text": "This example demonstrates how do I get android device screen height, width." }, { "code": null, "e": 1267, "s": 1138, "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": 1332, "s": 1267, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2450, "s": 1332, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center_horizontal\"\n android:layout_marginTop=\"30dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/getScreenHeight\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"20sp\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/getScreenWidth\"\n android:layout_marginTop=\"10dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:id=\"@+id/getScreenInches\"\n android:layout_marginTop=\"10dp\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>" }, { "code": null, "e": 2507, "s": 2450, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3716, "s": 2507, "text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.DisplayMetrics;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n TextView height, width, inches;\n DisplayMetrics displayMetrics;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n height = findViewById(R.id.getScreenHeight);\n width = findViewById(R.id.getScreenWidth);\n inches = findViewById(R.id.getScreenInches);\n displayMetrics = new DisplayMetrics();\n getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);\n int screenHeight = displayMetrics.heightPixels;\n int screenWidth = displayMetrics.widthPixels;\n double y = Math.pow(screenHeight /displayMetrics.xdpi, 2);\n double x = Math.pow(screenWidth /displayMetrics.xdpi, 2);\n double screenInches = Math.sqrt(x + y);\n screenInches = (double) Math.round(screenInches *10)/10;\n height.setText(\"Screen Height: \" + screenHeight);\n width.setText(\"Screen Height: \" + screenWidth);\n inches.setText(\"Screen Inches: \" + screenInches);\n }\n}" }, { "code": null, "e": 3771, "s": 3716, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4441, "s": 3771, "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": 4788, "s": 4441, "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": 4829, "s": 4788, "text": "Click here to download the project code." } ]
Java program to print Pascal's triangle
Pascal's triangle is one of the classic example taught to engineering students. It has many interpretations. One of the famous one is its use with binomial equations. All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire a space in Pascal’s triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0). The output is sandwiched between two zeroes. The process continues till the required level is achieved. Take a number of rows to be printed, n. Make outer iteration I for n times to print rows. Make inner iteration for J to (N - 1). Print single blank space " ". Close inner loop. Make inner iteration for J to I. Print nCr of I and J. Close inner loop. Print NEWLINE character after each inner iteration. Live Demo public class PascalsTriangle { static int factorial(int n) { int f; for(f = 1; n > 1; n--){ f *= n; } return f; } static int ncr(int n,int r) { return factorial(n) / ( factorial(n-r) * factorial(r) ); } public static void main(String args[]){ System.out.println(); int n, i, j; n = 5; for(i = 0; i <= n; i++) { for(j = 0; j <= n-i; j++){ System.out.print(" "); } for(j = 0; j <= i; j++){ System.out.print(" "+ncr(i, j)); } System.out.println(); } } } 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1
[ { "code": null, "e": 1229, "s": 1062, "text": "Pascal's triangle is one of the classic example taught to engineering students. It has many interpretations. One of the famous one is its use with binomial equations." }, { "code": null, "e": 1534, "s": 1229, "text": "All values outside the triangle are considered zero (0). The first row is 0 1 0 whereas only 1 acquire a space in Pascal’s triangle, 0s are invisible. Second row is acquired by adding (0+1) and (1+0). The output is sandwiched between two zeroes. The process continues till the required level is achieved." }, { "code": null, "e": 1574, "s": 1534, "text": "Take a number of rows to be printed, n." }, { "code": null, "e": 1624, "s": 1574, "text": "Make outer iteration I for n times to print rows." }, { "code": null, "e": 1663, "s": 1624, "text": "Make inner iteration for J to (N - 1)." }, { "code": null, "e": 1693, "s": 1663, "text": "Print single blank space \" \"." }, { "code": null, "e": 1711, "s": 1693, "text": "Close inner loop." }, { "code": null, "e": 1744, "s": 1711, "text": "Make inner iteration for J to I." }, { "code": null, "e": 1766, "s": 1744, "text": "Print nCr of I and J." }, { "code": null, "e": 1784, "s": 1766, "text": "Close inner loop." }, { "code": null, "e": 1836, "s": 1784, "text": "Print NEWLINE character after each inner iteration." }, { "code": null, "e": 1846, "s": 1836, "text": "Live Demo" }, { "code": null, "e": 2455, "s": 1846, "text": "public class PascalsTriangle {\n static int factorial(int n) {\n int f;\n\n for(f = 1; n > 1; n--){\n f *= n;\n }\n return f;\n }\n static int ncr(int n,int r) {\n return factorial(n) / ( factorial(n-r) * factorial(r) );\n }\n public static void main(String args[]){\n System.out.println();\n int n, i, j;\n n = 5;\n\n for(i = 0; i <= n; i++) {\n for(j = 0; j <= n-i; j++){\n System.out.print(\" \");\n }\n for(j = 0; j <= i; j++){\n System.out.print(\" \"+ncr(i, j));\n }\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 2616, "s": 2455, "text": " 1\n 1 1\n 1 2 1\n 1 3 3 1\n 1 4 6 4 1\n1 5 10 10 5 1 " } ]
Event Driven Architecture Pattern | by Anuradha Wickramarachchi | Towards Data Science
This is the most common distributed asynchronous architecture used to develop highly scalable system. The architecture consists of single-purpose event processing components that listen on events and process them asynchronously. There are two main topologies in the event-driven architecture. Mediator TopologyBroker Topology Mediator Topology Broker Topology Mediator topology has a single event queue and a mediator which directs each of the events to relevant event processors. Usually events are fed into the event processors passing through an event channel to filter or pre-process events. The implementation of the event queue could be in the form of a simple message queue or even a message passing interface in a large distributed system which involves complex messaging protocols such as Rabbit MQ. The diagram below demonstrate the architectural implementation of the mediator topology. This topology involves no event queue. Event processors are responsible for obtaining events, processing and publishing another event indicating the end. As the name of the topology implies event processors act as brokers to chain events. Once an event is processed by a processor another event is published so that another processor can proceed. Consider the below diagram. As the diagram demonstrates, some event processors just process and leave no trace and some tend to publish new events. This is quite similar to what we see in a NodeJS application. Steps of certain tasks are chained in the manner of callbacks, when one task ends, the callback is triggered. And all the tasks remain asynchronous in nature. The following illustration demonstrates the NodeJS architecture as represented in the official documentation. ┌───────────────────────┐┌─>│ timers ││ └──────────┬────────────┘│ ┌──────────┴────────────┐│ │ I/O callbacks ││ └──────────┬────────────┘│ ┌──────────┴────────────┐│ │ idle, prepare ││ └──────────┬────────────┘ ┌───────────────┐│ ┌──────────┴────────────┐ │ incoming: ││ │ poll │<─────┤ connections, ││ └──────────┬────────────┘ │ data, etc. ││ ┌──────────┴────────────┐ └───────────────┘│ │ check ││ └──────────┬────────────┘│ ┌──────────┴────────────┐└──┤ close callbacks │ └───────────────────────┘ All the incoming connections are pushed into the poll and they will be treated asynchronously. This does not block the other calls being processed. Thus the architecture provides a greater scalability still being single threaded. We can run several Node processes and balance load on top of them and direct requests accordingly. Further reading: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/ Netty (JAVA) — https://netty.io Vert.X (JVM Languages) — http://vertx.io Spring Reactor (JAVA) — https://spring.io/guides/gs/messaging-reactor/ ReactPHP (PHP) — http://reactphp.org The pattern lacks atomicity of transactions since there is no guarantee of the execution sequence of the events. This is because event processors are implemented to be highly distributed, decoupled and asynchronous. The results are expected to be provided at a future time, mostly in the manner of a callback. Testing of the systems with event driven architecture is not easy due to the asynchronous nature of the processing Since the tasks are asynchronous and non blocking in nature the executions are parallel. Thus this outweigh the cost of queueing mechanisms providing great perofrmance. Even though the systems are highly scalable the development effort is great. This is because unit testing and component testing is difficult due to asynchronous nature, which makes the system scalable. The systems can be made to run parallelly due to the decoupled nature of event processors, improving the scalability and parallelism.
[ { "code": null, "e": 401, "s": 172, "text": "This is the most common distributed asynchronous architecture used to develop highly scalable system. The architecture consists of single-purpose event processing components that listen on events and process them asynchronously." }, { "code": null, "e": 465, "s": 401, "text": "There are two main topologies in the event-driven architecture." }, { "code": null, "e": 498, "s": 465, "text": "Mediator TopologyBroker Topology" }, { "code": null, "e": 516, "s": 498, "text": "Mediator Topology" }, { "code": null, "e": 532, "s": 516, "text": "Broker Topology" }, { "code": null, "e": 768, "s": 532, "text": "Mediator topology has a single event queue and a mediator which directs each of the events to relevant event processors. Usually events are fed into the event processors passing through an event channel to filter or pre-process events." }, { "code": null, "e": 1070, "s": 768, "text": "The implementation of the event queue could be in the form of a simple message queue or even a message passing interface in a large distributed system which involves complex messaging protocols such as Rabbit MQ. The diagram below demonstrate the architectural implementation of the mediator topology." }, { "code": null, "e": 1417, "s": 1070, "text": "This topology involves no event queue. Event processors are responsible for obtaining events, processing and publishing another event indicating the end. As the name of the topology implies event processors act as brokers to chain events. Once an event is processed by a processor another event is published so that another processor can proceed." }, { "code": null, "e": 1445, "s": 1417, "text": "Consider the below diagram." }, { "code": null, "e": 1786, "s": 1445, "text": "As the diagram demonstrates, some event processors just process and leave no trace and some tend to publish new events. This is quite similar to what we see in a NodeJS application. Steps of certain tasks are chained in the manner of callbacks, when one task ends, the callback is triggered. And all the tasks remain asynchronous in nature." }, { "code": null, "e": 1896, "s": 1786, "text": "The following illustration demonstrates the NodeJS architecture as represented in the official documentation." }, { "code": null, "e": 2517, "s": 1896, "text": " ┌───────────────────────┐┌─>│ timers ││ └──────────┬────────────┘│ ┌──────────┴────────────┐│ │ I/O callbacks ││ └──────────┬────────────┘│ ┌──────────┴────────────┐│ │ idle, prepare ││ └──────────┬────────────┘ ┌───────────────┐│ ┌──────────┴────────────┐ │ incoming: ││ │ poll │<─────┤ connections, ││ └──────────┬────────────┘ │ data, etc. ││ ┌──────────┴────────────┐ └───────────────┘│ │ check ││ └──────────┬────────────┘│ ┌──────────┴────────────┐└──┤ close callbacks │ └───────────────────────┘ " }, { "code": null, "e": 2846, "s": 2517, "text": "All the incoming connections are pushed into the poll and they will be treated asynchronously. This does not block the other calls being processed. Thus the architecture provides a greater scalability still being single threaded. We can run several Node processes and balance load on top of them and direct requests accordingly." }, { "code": null, "e": 2929, "s": 2846, "text": "Further reading: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/" }, { "code": null, "e": 2961, "s": 2929, "text": "Netty (JAVA) — https://netty.io" }, { "code": null, "e": 3002, "s": 2961, "text": "Vert.X (JVM Languages) — http://vertx.io" }, { "code": null, "e": 3073, "s": 3002, "text": "Spring Reactor (JAVA) — https://spring.io/guides/gs/messaging-reactor/" }, { "code": null, "e": 3110, "s": 3073, "text": "ReactPHP (PHP) — http://reactphp.org" }, { "code": null, "e": 3420, "s": 3110, "text": "The pattern lacks atomicity of transactions since there is no guarantee of the execution sequence of the events. This is because event processors are implemented to be highly distributed, decoupled and asynchronous. The results are expected to be provided at a future time, mostly in the manner of a callback." }, { "code": null, "e": 3535, "s": 3420, "text": "Testing of the systems with event driven architecture is not easy due to the asynchronous nature of the processing" }, { "code": null, "e": 3704, "s": 3535, "text": "Since the tasks are asynchronous and non blocking in nature the executions are parallel. Thus this outweigh the cost of queueing mechanisms providing great perofrmance." } ]
Flattening a Linked List | Practice | GeeksforGeeks
Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers: (i) a next pointer to the next node, (ii) a bottom pointer to a linked list where this node is head. Each of the sub-linked-list is in sorted order. Flatten the Link List such that all the nodes appear in a single level while maintaining the sorted order. Note: The flattened list will be printed using the bottom pointer instead of next pointer. Example 1: Input: 5 -> 10 -> 19 -> 28 | | | | 7 20 22 35 | | | 8 50 40 | | 30 45 Output: 5-> 7-> 8- > 10 -> 19-> 20-> 22-> 28-> 30-> 35-> 40-> 45-> 50. Explanation: The resultant linked lists has every node in a single level. (Note: | represents the bottom pointer.) Example 2: Input: 5 -> 10 -> 19 -> 28 | | 7 22 | | 8 50 | 30 Output: 5->7->8->10->19->22->28->30->50 Explanation: The resultant linked lists has every node in a single level. (Note: | represents the bottom pointer.) Your Task: You do not need to read input or print anything. Complete the function flatten() that takes the head of the linked list as input parameter and returns the head of flattened link list. Expected Time Complexity: O(N*M*M) Expected Auxiliary Space: O(1) Constraints: 0 <= N <= 50 1 <= Mi <= 20 1 <= Element of linked list <= 103 0 rajparmar2380110 hours ago JAVA Solution class GfG { ArrayList<Integer> al=new ArrayList<>(); Node flatten(Node root) { // Your code here while(root!=null){ Node temp=root; while(temp!=null){ al.add(temp.data); temp=temp.bottom; } root=root.next; } Collections.sort(al); Node dummy=new Node(0); Node first_node=new Node(al.get(0)); dummy.bottom=first_node; Node last=first_node; for(int i=1;i<al.size();i++){ Node new_node=new Node(al.get(i)); last.bottom=new_node; last=last.bottom; } return dummy.bottom; } } 0 akshatjain231 day ago Java - Explained - Easy Solution class GfG { Node flatten(Node root) { // If current sub list is null or it's last sub list // then there is nothing to flatten, return root. if( root == null || root.next == null ) { return root; } // Flattening will be done from the end of the list // Keep calling flatten until we reach the second last sublist Node nextSublistRoot = flatten( root.next ); // Merge current sublist with the next sorted sublist // using Merge Sort technique return merge(root, nextSublistRoot); } Node merge(Node list1, Node list2) { // We don't yet know which list's first node will going // to be the head of the sorted list // Dummy node's bottom will point to the head of the merged list Node dummy = new Node(-1); // Pointer to the last merged node Node tail = dummy; // Repeat until there are nodes in both the list while( list1 != null && list2 != null ) { // Append the node to the bottom of the tail // from the list which has smaller value if( list1.data > list2.data ) { tail.bottom = list2; list2 = list2.bottom; } else { tail.bottom = list1; list1 = list1.bottom; } // Move pointer to latest merged node tail = tail.bottom; } // Merge list1 to the sorted list if list1 is not traversed completely if( list1 != null ) { tail.bottom = list1; } // Merge list2 to the sorted list if list2 is not traversed completely if( list2 != null ) { tail.bottom = list2; } // Return head of merged list return dummy.bottom; } } +2 prathamvaishya1231 week ago public Node merge(Node fir, Node sec){ Node dummy = new Node(-1); Node prev = dummy; while(fir != null && sec != null){ if(fir.data < sec.data){ prev.bottom = fir; prev = fir; fir = fir.bottom; }else { prev.bottom =sec; prev = sec; sec = sec.bottom; } } while(fir != null){ prev.bottom = fir; prev = fir; fir = fir.bottom; } while(sec != null){ prev.bottom = sec; prev = sec; sec = sec.bottom; } return dummy.bottom; } Node flatten(Node root) { if(root == null || root.next == null) return root; Node first = root; Node sec = flatten(first.next); return merge(first,sec); } 0 vishalsavade2 weeks ago //Easiest Way to Solve this problem static bool cmp(Node *a, Node *b){ return a->data < b->data; } Node *flatten(Node *root) { vector<Node *> v; Node *t = root; while(t!=NULL){ v.push_back(t); if(t->bottom != NULL){ Node *p = t->bottom; while(p != NULL){ v.push_back(p); p = p->bottom; } } t = t->next; } sort(v.begin(), v.end(), cmp); Node *q = new Node(0); Node *l = q; for(auto x: v){ l->bottom = new Node(x->data); l = l->bottom; } return q->bottom; } //This code is contributed by Vishal Savade 0 harshscode2 weeks ago Node* mergesort(Node *a,Node *b){ Node *ans; if(!a) return b; else if(!b) return a; if(a->data<b->data) { ans=a; ans->bottom=mergesort(a->bottom,b); } else { ans=b; ans->bottom=mergesort(a,b->bottom); } ans->next=NULL; return ans;} Node *flatten(Node *root){ if(!root or !root->next) return root; return mergesort(root,flatten(root->next)); } 0 deathcloud2 weeks ago Easy Solution Using Merge Node *merge(Node *first, Node *second){ if(!second) return first; if(!first) return second; Node *p = first; Node *q = second; Node *prev = NULL; while(p && q){ if(p->data <= q->data){ prev = p; p = p->bottom; }else if(q->data < p->data){ if(prev == NULL){ Node *temp = q->bottom; q->bottom = p; first = q; p = q; q= temp; }else{ Node *temp = q->bottom; prev->bottom = q; q->bottom = p; prev = q; q = temp; } } } if(p == NULL){ prev->bottom = q; } return first; } Node *flatten(Node *root) { // Your code here Node *curr = root->next; while(curr){ root = merge(root,curr); root->next = curr->next; curr = curr->next; } return root; } 0 akshatdalmia0072 weeks ago def flatten(root): l = [] if not root: return root while root: temp = root l.append(root.data) while root.bottom: l.append(root.bottom.data) root = root.bottom temp = temp.next root = temp l.sort() head = Node(l[0]) curr = t = head for i in range(1,len(l)): head = Node(l[i]) curr.bottom = head curr = head return t 0 tthakare732 weeks ago //java Solution -> TC -> 0.64 // hint -> use priorityQueue class GfG{ PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); void triv(Node root){ if(root == null){ return; } pq.add(new Integer(root.data)); triv(root.bottom); triv(root.next); } Node flatten(Node root){ triv(root); Node dummy = null; while(!pq.isEmpty()){ int current = pq.poll(); Node newNode = new Node(current); if(dummy == null){ root = newNode; dummy = root; } else { dummy.bottom = newNode; dummy = dummy.bottom; } } return root; } } +1 adityagagtiwari3 weeks ago Simple solution! Time Complexity: O(N*M*M)Auxiliary Space: O(1) class GfG { Node flatten(Node root) { // Your code here if(root==null) { return null; } ArrayList<Node> list = new ArrayList<>(); Node head = root; Node temp = root; Node resultant = null; while(head!=null) { resultant = mergeLL(head,resultant); head = head.next; } return resultant; } Node mergeLL(Node head1,Node head2) { if(head2==null) return head1; if(head1==null) return head1; Node dummy = new Node(-1); Node temp = dummy; while(head1!=null && head2!=null) { if(head1.data<head2.data) { temp.bottom = head1; head1 = head1.bottom; } else { temp.bottom = head2; head2 = head2.bottom; } temp = temp.bottom; } if(head1!=null) temp.bottom = head1; if(head2!=null) temp.bottom = head2; return dummy.bottom; } } 0 harshpandeyalfa23 weeks ago C++ (0.01sec) void add(Node* p , vector<int>& v){ while(p) { v.push_back(p->data); p=p->bottom; }} Node *flatten(Node *root){ vector<int> v; Node*it=root; while(it) { v.push_back(it->data); if(it->bottom) { add(it->bottom, v); } it=it->next; } sort(v.begin(), v.end()); int i=0; Node* head=new Node(v[i]); it=head; Node* s; while(i < v.size()-1) { i++; s=new Node(v[i]); it->bottom=s; it=s; } return head;} 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": 690, "s": 238, "text": "Given a Linked List of size N, where every node represents a sub-linked-list and contains two pointers:\n(i) a next pointer to the next node,\n(ii) a bottom pointer to a linked list where this node is head.\nEach of the sub-linked-list is in sorted order.\nFlatten the Link List such that all the nodes appear in a single level while maintaining the sorted order. \nNote: The flattened list will be printed using the bottom pointer instead of next pointer." }, { "code": null, "e": 703, "s": 692, "text": "Example 1:" }, { "code": null, "e": 1042, "s": 703, "text": "Input:\n5 -> 10 -> 19 -> 28\n| | | | \n7 20 22 35\n| | | \n8 50 40\n| | \n30 45\nOutput: 5-> 7-> 8- > 10 -> 19-> 20->\n22-> 28-> 30-> 35-> 40-> 45-> 50.\nExplanation:\nThe resultant linked lists has every \nnode in a single level.\n(Note: | represents the bottom pointer.)\n" }, { "code": null, "e": 1055, "s": 1044, "text": "Example 2:" }, { "code": null, "e": 1375, "s": 1055, "text": "Input:\n5 -> 10 -> 19 -> 28\n| | \n7 22 \n| | \n8 50 \n| \n30 \nOutput: 5->7->8->10->19->22->28->30->50\nExplanation:\nThe resultant linked lists has every\nnode in a single level.\n\n(Note: | represents the bottom pointer.)" }, { "code": null, "e": 1572, "s": 1377, "text": "Your Task:\nYou do not need to read input or print anything. Complete the function flatten() that takes the head of the linked list as input parameter and returns the head of flattened link list." }, { "code": null, "e": 1640, "s": 1574, "text": "Expected Time Complexity: O(N*M*M)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1717, "s": 1642, "text": "Constraints:\n0 <= N <= 50\n1 <= Mi <= 20\n1 <= Element of linked list <= 103" }, { "code": null, "e": 1719, "s": 1717, "text": "0" }, { "code": null, "e": 1746, "s": 1719, "text": "rajparmar2380110 hours ago" }, { "code": null, "e": 1760, "s": 1746, "text": "JAVA Solution" }, { "code": null, "e": 2378, "s": 1762, "text": "class GfG\n{\n ArrayList<Integer> al=new ArrayList<>();\n \n Node flatten(Node root)\n {\n\t// Your code here\n\t\n\twhile(root!=null){\n\t Node temp=root;\n\t while(temp!=null){\n al.add(temp.data);\n temp=temp.bottom;\n }\n\t root=root.next;\n\t}\n\n \n Collections.sort(al); \n\n Node dummy=new Node(0);\n \n Node first_node=new Node(al.get(0));\n dummy.bottom=first_node;\n Node last=first_node;\n for(int i=1;i<al.size();i++){\n \n Node new_node=new Node(al.get(i));\n \n last.bottom=new_node;\n last=last.bottom;\n }\n return dummy.bottom;\n }\n}" }, { "code": null, "e": 2382, "s": 2380, "text": "0" }, { "code": null, "e": 2404, "s": 2382, "text": "akshatjain231 day ago" }, { "code": null, "e": 2437, "s": 2404, "text": "Java - Explained - Easy Solution" }, { "code": null, "e": 4226, "s": 2439, "text": "class GfG\n{\n\tNode flatten(Node root)\n {\n // If current sub list is null or it's last sub list\n // then there is nothing to flatten, return root.\n\t if( root == null || root.next == null ) {\n\t return root;\n\t }\n\t \n\t // Flattening will be done from the end of the list \n\t // Keep calling flatten until we reach the second last sublist\n\t Node nextSublistRoot = flatten( root.next );\n\t \n\t // Merge current sublist with the next sorted sublist\n\t // using Merge Sort technique\n\t return merge(root, nextSublistRoot);\n }\n \n Node merge(Node list1, Node list2) \n {\n // We don't yet know which list's first node will going \n // to be the head of the sorted list\n // Dummy node's bottom will point to the head of the merged list\n Node dummy = new Node(-1);\n \n // Pointer to the last merged node\n\t Node tail = dummy;\n\t \n\t // Repeat until there are nodes in both the list\n\t while( list1 != null && list2 != null ) {\n\t \n\t // Append the node to the bottom of the tail \n\t // from the list which has smaller value\n\t if( list1.data > list2.data ) {\n\t tail.bottom = list2;\n\t list2 = list2.bottom;\n\t } else {\n\t tail.bottom = list1;\n\t list1 = list1.bottom;\n\t }\n\t // Move pointer to latest merged node\n\t tail = tail.bottom;\n\t }\n\t \n\t // Merge list1 to the sorted list if list1 is not traversed completely\n\t if( list1 != null ) {\n\t tail.bottom = list1;\n\t }\n\t // Merge list2 to the sorted list if list2 is not traversed completely\n\t if( list2 != null ) {\n\t tail.bottom = list2;\n\t }\n\t \n\t // Return head of merged list\n\t return dummy.bottom;\n }\n}" }, { "code": null, "e": 4229, "s": 4226, "text": "+2" }, { "code": null, "e": 4257, "s": 4229, "text": "prathamvaishya1231 week ago" }, { "code": null, "e": 5093, "s": 4257, "text": "public Node merge(Node fir, Node sec){ Node dummy = new Node(-1); Node prev = dummy; while(fir != null && sec != null){ if(fir.data < sec.data){ prev.bottom = fir; prev = fir; fir = fir.bottom; }else { prev.bottom =sec; prev = sec; sec = sec.bottom; } } while(fir != null){ prev.bottom = fir; prev = fir; fir = fir.bottom; } while(sec != null){ prev.bottom = sec; prev = sec; sec = sec.bottom; } return dummy.bottom; } Node flatten(Node root) { if(root == null || root.next == null) return root; Node first = root; Node sec = flatten(first.next); return merge(first,sec); }" }, { "code": null, "e": 5095, "s": 5093, "text": "0" }, { "code": null, "e": 5119, "s": 5095, "text": "vishalsavade2 weeks ago" }, { "code": null, "e": 5758, "s": 5119, "text": "//Easiest Way to Solve this problem\nstatic bool cmp(Node *a, Node *b){\n return a->data < b->data;\n}\n\nNode *flatten(Node *root)\n{\n vector<Node *> v;\n Node *t = root;\n while(t!=NULL){\n v.push_back(t);\n if(t->bottom != NULL){\n Node *p = t->bottom;\n while(p != NULL){\n v.push_back(p);\n p = p->bottom;\n }\n }\n t = t->next;\n }\n sort(v.begin(), v.end(), cmp);\n Node *q = new Node(0);\n Node *l = q;\n\n for(auto x: v){\n l->bottom = new Node(x->data);\n l = l->bottom;\n }\n return q->bottom;\n}\n//This code is contributed by Vishal Savade" }, { "code": null, "e": 5762, "s": 5760, "text": "0" }, { "code": null, "e": 5784, "s": 5762, "text": "harshscode2 weeks ago" }, { "code": null, "e": 6187, "s": 5784, "text": "Node* mergesort(Node *a,Node *b){ Node *ans; if(!a) return b; else if(!b) return a; if(a->data<b->data) { ans=a; ans->bottom=mergesort(a->bottom,b); } else { ans=b; ans->bottom=mergesort(a,b->bottom); } ans->next=NULL; return ans;} Node *flatten(Node *root){ if(!root or !root->next) return root; return mergesort(root,flatten(root->next)); } " }, { "code": null, "e": 6189, "s": 6187, "text": "0" }, { "code": null, "e": 6211, "s": 6189, "text": "deathcloud2 weeks ago" }, { "code": null, "e": 6237, "s": 6211, "text": "Easy Solution Using Merge" }, { "code": null, "e": 7250, "s": 6239, "text": " \nNode *merge(Node *first, Node *second){\n if(!second)\n return first;\n if(!first)\n return second;\n Node *p = first;\n Node *q = second;\n Node *prev = NULL;\n\n while(p && q){\n if(p->data <= q->data){\n prev = p;\n p = p->bottom;\n }else if(q->data < p->data){\n if(prev == NULL){\n Node *temp = q->bottom; \n q->bottom = p;\n first = q;\n p = q;\n q= temp;\n }else{\n Node *temp = q->bottom;\n prev->bottom = q;\n q->bottom = p;\n prev = q;\n q = temp;\n }\n }\n }\n \n if(p == NULL){\n prev->bottom = q;\n }\n \n return first;\n \n}\n\nNode *flatten(Node *root)\n{\n // Your code here\n Node *curr = root->next;\n while(curr){\n root = merge(root,curr);\n root->next = curr->next;\n curr = curr->next;\n }\n \n return root;\n}\n\n" }, { "code": null, "e": 7252, "s": 7250, "text": "0" }, { "code": null, "e": 7279, "s": 7252, "text": "akshatdalmia0072 weeks ago" }, { "code": null, "e": 7692, "s": 7279, "text": "def flatten(root): l = [] if not root: return root while root: temp = root l.append(root.data) while root.bottom: l.append(root.bottom.data) root = root.bottom temp = temp.next root = temp l.sort() head = Node(l[0]) curr = t = head for i in range(1,len(l)): head = Node(l[i]) curr.bottom = head curr = head return t" }, { "code": null, "e": 7694, "s": 7692, "text": "0" }, { "code": null, "e": 7716, "s": 7694, "text": "tthakare732 weeks ago" }, { "code": null, "e": 8426, "s": 7716, "text": "//java Solution -> TC -> 0.64\n// hint -> use priorityQueue\nclass GfG{\n PriorityQueue<Integer> pq = new PriorityQueue<Integer>();\n void triv(Node root){\n if(root == null){\n return;\n } \n pq.add(new Integer(root.data));\n triv(root.bottom);\n triv(root.next);\n }\n \n Node flatten(Node root){\n\t triv(root);\n\t Node dummy = null;\n\t while(!pq.isEmpty()){\n\t int current = pq.poll();\n\t Node newNode = new Node(current);\n\t if(dummy == null){\n\t root = newNode;\n\t dummy = root;\n\t } else {\n\t dummy.bottom = newNode;\n\t dummy = dummy.bottom;\n\t }\n\t }\n\t return root;\n }\n}" }, { "code": null, "e": 8429, "s": 8426, "text": "+1" }, { "code": null, "e": 8456, "s": 8429, "text": "adityagagtiwari3 weeks ago" }, { "code": null, "e": 8473, "s": 8456, "text": "Simple solution!" }, { "code": null, "e": 8520, "s": 8473, "text": "Time Complexity: O(N*M*M)Auxiliary Space: O(1)" }, { "code": null, "e": 9546, "s": 8520, "text": "class GfG\n{\n Node flatten(Node root)\n {\n// Your code here\nif(root==null)\n{\n return null;\n}\n ArrayList<Node> list = new ArrayList<>();\n Node head = root;\n Node temp = root;\n Node resultant = null;\n while(head!=null)\n {\n resultant = mergeLL(head,resultant);\n head = head.next;\n }\n return resultant;\n } \n Node mergeLL(Node head1,Node head2)\n {\n if(head2==null)\n return head1;\n if(head1==null)\n return head1;\n Node dummy = new Node(-1);\n Node temp = dummy;\n while(head1!=null && head2!=null)\n {\n if(head1.data<head2.data)\n {\n temp.bottom = head1;\n head1 = head1.bottom;\n }\n else\n {\n temp.bottom = head2;\n head2 = head2.bottom;\n }\n temp = temp.bottom;\n }\n if(head1!=null)\n temp.bottom = head1;\n if(head2!=null)\n temp.bottom = head2;\n \n return dummy.bottom;\n }\n}" }, { "code": null, "e": 9548, "s": 9546, "text": "0" }, { "code": null, "e": 9576, "s": 9548, "text": "harshpandeyalfa23 weeks ago" }, { "code": null, "e": 9580, "s": 9576, "text": "C++" }, { "code": null, "e": 9590, "s": 9580, "text": "(0.01sec)" }, { "code": null, "e": 9693, "s": 9590, "text": "void add(Node* p , vector<int>& v){ while(p) { v.push_back(p->data); p=p->bottom; }}" }, { "code": null, "e": 10071, "s": 9693, "text": "Node *flatten(Node *root){ vector<int> v; Node*it=root; while(it) { v.push_back(it->data); if(it->bottom) { add(it->bottom, v); } it=it->next; } sort(v.begin(), v.end()); int i=0; Node* head=new Node(v[i]); it=head; Node* s; while(i < v.size()-1) { i++; s=new Node(v[i]); it->bottom=s; it=s; } return head;}" }, { "code": null, "e": 10217, "s": 10071, "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": 10253, "s": 10217, "text": " Login to access your submissions. " }, { "code": null, "e": 10263, "s": 10253, "text": "\nProblem\n" }, { "code": null, "e": 10273, "s": 10263, "text": "\nContest\n" }, { "code": null, "e": 10336, "s": 10273, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10484, "s": 10336, "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": 10692, "s": 10484, "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": 10798, "s": 10692, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Convert list to array in R - GeeksforGeeks
01 Sep, 2021 A list can be converted to array in R by calling unlist( ) function with created list as parameter. Now pass the unlist() function into array() function as parameter, and use dim attribute for specifying number of rows, columns and matrices. unlist() converts list to vector. Syntax : array( unlist( list_variable ) , dim = ( rows ,columns , matrices )) Given below are various implementation for the same: Example 1 : R lst1=list(1:10) arr=array(unlist(lst1),dim=c(3,3,3))print(arr) Output : Example 2 : R lst1=list(c("karthik","nikhil","sravan")) arr=array(unlist(lst1),dim=c(1,3,3))print(arr) Output: Example 3 : R lst1=list(c("karthik","chandu","nandu")) arr=array(unlist(lst1),dim=c(1,3,2))print(arr) Output: gulshankumarar231 R Array-Programs R List-Programs R-Arrays R-List R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to import an Excel File into R ? How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? How to change the order of bars in bar chart in R ? R - if statement Replace Specific Characters in String in R
[ { "code": null, "e": 25242, "s": 25214, "text": "\n01 Sep, 2021" }, { "code": null, "e": 25518, "s": 25242, "text": "A list can be converted to array in R by calling unlist( ) function with created list as parameter. Now pass the unlist() function into array() function as parameter, and use dim attribute for specifying number of rows, columns and matrices. unlist() converts list to vector." }, { "code": null, "e": 25529, "s": 25518, "text": " Syntax : " }, { "code": null, "e": 25598, "s": 25529, "text": "array( unlist( list_variable ) , dim = ( rows ,columns , matrices ))" }, { "code": null, "e": 25651, "s": 25598, "text": "Given below are various implementation for the same:" }, { "code": null, "e": 25663, "s": 25651, "text": "Example 1 :" }, { "code": null, "e": 25665, "s": 25663, "text": "R" }, { "code": "lst1=list(1:10) arr=array(unlist(lst1),dim=c(3,3,3))print(arr)", "e": 25728, "s": 25665, "text": null }, { "code": null, "e": 25737, "s": 25728, "text": "Output :" }, { "code": null, "e": 25749, "s": 25737, "text": "Example 2 :" }, { "code": null, "e": 25751, "s": 25749, "text": "R" }, { "code": "lst1=list(c(\"karthik\",\"nikhil\",\"sravan\")) arr=array(unlist(lst1),dim=c(1,3,3))print(arr)", "e": 25840, "s": 25751, "text": null }, { "code": null, "e": 25848, "s": 25840, "text": "Output:" }, { "code": null, "e": 25860, "s": 25848, "text": "Example 3 :" }, { "code": null, "e": 25862, "s": 25860, "text": "R" }, { "code": "lst1=list(c(\"karthik\",\"chandu\",\"nandu\")) arr=array(unlist(lst1),dim=c(1,3,2))print(arr)", "e": 25950, "s": 25862, "text": null }, { "code": null, "e": 25958, "s": 25950, "text": "Output:" }, { "code": null, "e": 25976, "s": 25958, "text": "gulshankumarar231" }, { "code": null, "e": 25993, "s": 25976, "text": "R Array-Programs" }, { "code": null, "e": 26009, "s": 25993, "text": "R List-Programs" }, { "code": null, "e": 26018, "s": 26009, "text": "R-Arrays" }, { "code": null, "e": 26025, "s": 26018, "text": "R-List" }, { "code": null, "e": 26036, "s": 26025, "text": "R Language" }, { "code": null, "e": 26134, "s": 26036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26143, "s": 26134, "text": "Comments" }, { "code": null, "e": 26156, "s": 26143, "text": "Old Comments" }, { "code": null, "e": 26208, "s": 26156, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26246, "s": 26208, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26281, "s": 26246, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26339, "s": 26281, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26376, "s": 26339, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 26425, "s": 26376, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26475, "s": 26425, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26527, "s": 26475, "text": "How to change the order of bars in bar chart in R ?" }, { "code": null, "e": 26544, "s": 26527, "text": "R - if statement" } ]
How to Add Legends to charts in Python?
The main purpose of charts is to make understand data easily. "A picture is worth a thousand words" means complex ideas that cannot be expressed in words can be conveyed by a single image/chart. When drawing graphs with lot of information, a legend may be pleasing to display relevant information to improve the understanding of the data presented. In matplotlib, legends can be presented in multiple ways. Annotations to draw attention to specific points are also useful to help the reader understand the information displayed on the graph. 1. Install matplotlib by opening up the python command prompt and firing pip install matplotlib. 2. Prepare the data to be displayed. import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),) 3. Split the data into arrays for each company company's mobile units. # data prep - splitting the data IPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold] Galaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold] Pixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold] # data prep - Labels Years = [Year for Year, Iphones, Galaxy,Pixel in units_sold] # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2 4. Creating a Bar graph with the data prepared.Each product sales gets a call to .bar, specifying its position and sales. Annotation is added using the xy and xytext attributes. Looking at the data, the Google Pixel mobile sales have dropped by 50% i.e. from 10Million units sold in 2019 to just 5Million in 2022. So we are going to set the text and annotation to out last bar. Finally, we will add the legend using the legend parameter.By default, matplotlib will draw the legend over an area where there's the least overlap of data. plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green') plt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue') plt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow') # Set X-axis as years plt.xticks(Position, Years) # Set the Y axis label plt.xlabel('Yearly Sales') plt.ylabel('Unit Sales In Millions') # Set the annotation Use the xy and xytext to change the arrow plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12), horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05)) # Set the legent plt.legend(mobile, title='Manufacturers') <matplotlib.legend.Legend at 0x19826618400> If you feel adding the legend inside the chart is noisy, you can use the bbox_to_anchor option to plot the legend outside. bbox_to_anchor have (X, Y) positions, where 0 is the bottom-left corner of the graph and 1 is the upper-right corner. If you feel adding the legend inside the chart is noisy, you can use the bbox_to_anchor option to plot the legend outside. bbox_to_anchor have (X, Y) positions, where 0 is the bottom-left corner of the graph and 1 is the upper-right corner. NOTE: - Use .subplots_adjust to adjust the legend where the graph starts and ends. E.g. right=0.50 value means it leave 50% of the screen on the right of the plot. The default value for left is 0.125, meaning it leaves 12.5% of the space on the left. plt.legend(mobile, title='Manufacturers', bbox_to_anchor=(1, 0.8)) plt.subplots_adjust(right=1.2) 6. Finally let us save the figure. import matplotlib.pyplot as plt # data prep (I made up data no accuracy in these stats) mobile = ['Iphone','Galaxy','Pixel'] # Data for the mobile units sold for 4 Quaters in Million units_sold = (('2016',12,8,6), ('2017',14,10,7), ('2018',16,12,8), ('2019',18,14,10), ('2020',20,16,5),) # data prep - splitting the data IPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold] Galaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold] Pixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold] # data prep - Labels Years = [Year for Year, Iphones, Galaxy,Pixel in units_sold] # set the position Position = list(range(len(units_sold))) # set the width Width = 0.2 plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green') plt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue') plt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow') # Set X-axis as years plt.xticks(Position, Years) # Set the Y axis label plt.xlabel('Yearly Sales') plt.ylabel('Unit Sales In Millions') # Set the annotation Use the xy and xytext to change the arrow plt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12), horizontalalignment='center', arrowprops=dict(facecolor='red', shrink=0.05)) # Set the legent plt.legend(mobile, title='Manufacturers') plt.legend(mobile, title='Manufacturers') plt.subplots_adjust(right=1.2) # plt.show() plt.savefig('MobileSales.png')
[ { "code": null, "e": 1257, "s": 1062, "text": "The main purpose of charts is to make understand data easily. \"A picture is worth a thousand words\" means complex ideas that cannot be expressed in words can be conveyed by a single image/chart." }, { "code": null, "e": 1411, "s": 1257, "text": "When drawing graphs with lot of information, a legend may be pleasing to display relevant information to improve the understanding of the data presented." }, { "code": null, "e": 1604, "s": 1411, "text": "In matplotlib, legends can be presented in multiple ways. Annotations to draw attention to specific points are also useful to help the reader understand the information displayed on the graph." }, { "code": null, "e": 1701, "s": 1604, "text": "1.\nInstall matplotlib by opening up the python command prompt and firing pip install matplotlib." }, { "code": null, "e": 1738, "s": 1701, "text": "2.\nPrepare the data to be displayed." }, { "code": null, "e": 2028, "s": 1738, "text": "import matplotlib.pyplot as plt\n\n# data prep (I made up data no accuracy in these stats)\nmobile = ['Iphone','Galaxy','Pixel']\n\n# Data for the mobile units sold for 4 Quaters in Million\nunits_sold = (('2016',12,8,6),\n('2017',14,10,7),\n('2018',16,12,8),\n('2019',18,14,10),\n('2020',20,16,5),)" }, { "code": null, "e": 2099, "s": 2028, "text": "3.\nSplit the data into arrays for each company company's mobile units." }, { "code": null, "e": 2516, "s": 2099, "text": "# data prep - splitting the data\nIPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold]\nGalaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold]\nPixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold]\n\n# data prep - Labels\nYears = [Year for Year, Iphones, Galaxy,Pixel in units_sold]\n\n# set the position\nPosition = list(range(len(units_sold)))\n\n# set the width\nWidth = 0.2" }, { "code": null, "e": 2638, "s": 2516, "text": "4.\nCreating a Bar graph with the data prepared.Each product sales gets a call to .bar, specifying its position and sales." }, { "code": null, "e": 2894, "s": 2638, "text": "Annotation is added using the xy and xytext attributes. Looking at the data, the Google Pixel mobile sales have dropped by 50% i.e. from 10Million units sold in 2019 to just 5Million in 2022. So we are going to set the text and annotation to out last bar." }, { "code": null, "e": 3051, "s": 2894, "text": "Finally, we will add the legend using the legend parameter.By default, matplotlib will draw the legend over an area where there's the least overlap of data." }, { "code": null, "e": 3688, "s": 3051, "text": "plt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green')\nplt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue')\nplt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow')\n\n# Set X-axis as years\nplt.xticks(Position, Years)\n\n# Set the Y axis label\nplt.xlabel('Yearly Sales')\nplt.ylabel('Unit Sales In Millions')\n\n# Set the annotation Use the xy and xytext to change the arrow\nplt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12),\nhorizontalalignment='center',\narrowprops=dict(facecolor='red', shrink=0.05))\n\n# Set the legent\nplt.legend(mobile, title='Manufacturers')" }, { "code": null, "e": 3732, "s": 3688, "text": "<matplotlib.legend.Legend at 0x19826618400>" }, { "code": null, "e": 3973, "s": 3732, "text": "If you feel adding the legend inside the chart is noisy, you can use the bbox_to_anchor option to plot the legend outside. bbox_to_anchor have (X, Y) positions, where 0 is the bottom-left corner of the graph and 1 is the upper-right corner." }, { "code": null, "e": 4214, "s": 3973, "text": "If you feel adding the legend inside the chart is noisy, you can use the bbox_to_anchor option to plot the legend outside. bbox_to_anchor have (X, Y) positions, where 0 is the bottom-left corner of the graph and 1 is the upper-right corner." }, { "code": null, "e": 4297, "s": 4214, "text": "NOTE: - Use .subplots_adjust to adjust the legend where the graph starts and ends." }, { "code": null, "e": 4465, "s": 4297, "text": "E.g. right=0.50 value means it leave 50% of the screen on the right of the plot. The default value for left is 0.125, meaning it leaves 12.5% of the space on the left." }, { "code": null, "e": 4563, "s": 4465, "text": "plt.legend(mobile, title='Manufacturers', bbox_to_anchor=(1, 0.8))\nplt.subplots_adjust(right=1.2)" }, { "code": null, "e": 4598, "s": 4563, "text": "6.\nFinally let us save the figure." }, { "code": null, "e": 6063, "s": 4598, "text": "import matplotlib.pyplot as plt\n\n# data prep (I made up data no accuracy in these stats)\nmobile = ['Iphone','Galaxy','Pixel']\n\n# Data for the mobile units sold for 4 Quaters in Million\nunits_sold = (('2016',12,8,6),\n('2017',14,10,7),\n('2018',16,12,8),\n('2019',18,14,10),\n('2020',20,16,5),)\n\n# data prep - splitting the data\nIPhone_Sales = [Iphones for Year, Iphones, Galaxy, Pixel in units_sold]\nGalaxy_Sales = [Galaxy for Year, Iphones, Galaxy, Pixel in units_sold]\nPixel_Sales = [Pixel for Year, Iphones, Galaxy, Pixel in units_sold]\n\n# data prep - Labels\nYears = [Year for Year, Iphones, Galaxy,Pixel in units_sold]\n\n# set the position\nPosition = list(range(len(units_sold)))\n\n# set the width\nWidth = 0.2\n\nplt.bar([p - Width for p in Position], IPhone_Sales, width=Width,color='green')\nplt.bar([p for p in Position], Galaxy_Sales , width=Width,color='blue')\nplt.bar([p + Width for p in Position], Pixel_Sales, width=Width,color='yellow')\n\n# Set X-axis as years\nplt.xticks(Position, Years)\n\n# Set the Y axis label\nplt.xlabel('Yearly Sales')\nplt.ylabel('Unit Sales In Millions')\n\n# Set the annotation Use the xy and xytext to change the arrow\nplt.annotate('50% Drop in Sales', xy=(4.2, 5), xytext=(5.0, 12),\nhorizontalalignment='center',\narrowprops=dict(facecolor='red', shrink=0.05))\n\n# Set the legent\nplt.legend(mobile, title='Manufacturers')\n\nplt.legend(mobile, title='Manufacturers')\nplt.subplots_adjust(right=1.2)\n\n# plt.show()\nplt.savefig('MobileSales.png')" } ]
Java - Assignment Operators Example
The following program is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in Test.java file. Compile and run this program − public class Test { public static void main(String args[]) { int a = 10; int b = 20; int c = 0; c = a + b; System.out.println("c = a + b = " + c ); c += a ; System.out.println("c += a = " + c ); c -= a ; System.out.println("c -= a = " + c ); c *= a ; System.out.println("c *= a = " + c ); a = 10; c = 15; c /= a ; System.out.println("c /= a = " + c ); a = 10; c = 15; c %= a ; System.out.println("c %= a = " + c ); c <<= 2 ; System.out.println("c <<= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c >>= 2 ; System.out.println("c >>= 2 = " + c ); c &= a ; System.out.println("c &= a = " + c ); c ^= a ; System.out.println("c ^= a = " + c ); c |= a ; System.out.println("c |= a = " + c ); } } This will produce the following result − c = a + b = 30 c += a = 40 c -= a = 30 c *= a = 300 c /= a = 1 c %= a = 5 c <<= 2 = 20 c >>= 2 = 5 c >>= 2 = 1 c &= a = 0 c ^= a = 10 c |= a = 10 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": 2555, "s": 2377, "text": "The following program is a simple example that demonstrates the assignment operators. Copy and paste the following Java program in Test.java file. Compile and run this program −" }, { "code": null, "e": 3474, "s": 2555, "text": "public class Test {\n\n public static void main(String args[]) {\n int a = 10;\n int b = 20;\n int c = 0;\n\n c = a + b;\n System.out.println(\"c = a + b = \" + c );\n\n c += a ;\n System.out.println(\"c += a = \" + c );\n\n c -= a ;\n System.out.println(\"c -= a = \" + c );\n\n c *= a ;\n System.out.println(\"c *= a = \" + c );\n\n a = 10;\n c = 15;\n c /= a ;\n System.out.println(\"c /= a = \" + c );\n\n a = 10;\n c = 15;\n c %= a ;\n System.out.println(\"c %= a = \" + c );\n\n c <<= 2 ;\n System.out.println(\"c <<= 2 = \" + c );\n\n c >>= 2 ;\n System.out.println(\"c >>= 2 = \" + c );\n\n c >>= 2 ;\n System.out.println(\"c >>= 2 = \" + c );\n\n c &= a ;\n System.out.println(\"c &= a = \" + c );\n\n c ^= a ;\n System.out.println(\"c ^= a = \" + c );\n\n c |= a ;\n System.out.println(\"c |= a = \" + c );\n }\n}" }, { "code": null, "e": 3515, "s": 3474, "text": "This will produce the following result −" }, { "code": null, "e": 3669, "s": 3515, "text": "c = a + b = 30\nc += a = 40\nc -= a = 30\nc *= a = 300\nc /= a = 1\nc %= a = 5\nc <<= 2 = 20\nc >>= 2 = 5\nc >>= 2 = 1\nc &= a = 0\nc ^= a = 10\nc |= a = 10\n" }, { "code": null, "e": 3702, "s": 3669, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3718, "s": 3702, "text": " Malhar Lathkar" }, { "code": null, "e": 3751, "s": 3718, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3767, "s": 3751, "text": " Malhar Lathkar" }, { "code": null, "e": 3802, "s": 3767, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3816, "s": 3802, "text": " Anadi Sharma" }, { "code": null, "e": 3850, "s": 3816, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 3864, "s": 3850, "text": " Tushar Kale" }, { "code": null, "e": 3901, "s": 3864, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3916, "s": 3901, "text": " Monica Mittal" }, { "code": null, "e": 3949, "s": 3916, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 3968, "s": 3949, "text": " Arnab Chakraborty" }, { "code": null, "e": 3975, "s": 3968, "text": " Print" }, { "code": null, "e": 3986, "s": 3975, "text": " Add Notes" } ]
Count the characters | Practice | GeeksforGeeks
Given a string S. Count the characters that have ‘N’ number of occurrences. If a character appears consecutively it is counted as 1 occurrence. Example 1: Input: S = "abc", N = 1 Output: 3 Explanation: 'a', 'b' and 'c' all have 1 occurrence. ​Example 2: Input: S = "geeksforgeeks", N = 2 Output: 4 Explanation: 'g', 'e', 'k' and 's' have 2 occurrences. Your Task: You don't need to read input or print anything. Your task is to complete the function getCount() which takes the string S and an integer N as inputs and returns the count of the characters that have exactly N occurrences in the string. Note that the consecutive occurrences of a character have to be counted as 1. Expected Time Complexity: O(|S|). Expected Auxiliary Space: O(1). Constraints: 1<=|S|<=105 1<=N<=103 0 abhishek11102 weeks ago Java Solution: int getCount (String s, int N) { // your code here int[] arr = new int[26]; char prev = '#'; for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (prev != c) { arr[c - 'a']++; } prev = c; } int count = 0; for (int i = 0; i < arr.length; i++) { if (arr[i] == N) { count++; } } return count; } 0 jaatgfg112 months ago hi geeks - ezz cpp soln -- int getCount (string S, int N) { map<char,int>mp; int n=S.length(); for(int i=0;i<n;i++){ if(S[i]!=S[i+1]){ mp[S[i]]++; } } map<char,int>::iterator it; int ct=0; for(it=mp.begin();it!=mp.end();it++){ if(it->second==N){ ct++; } } return ct; } 0 aarisettydivya2 months ago Hey guys, the problem statement said that the expected auxiliary space is O(1). Then how can we use array or any data Structure. I dnt get it. Can anyone explain it? +1 codeman992 months ago //c++ class Solution { public: int getCount (string S, int N) { //code here. int cnt=0; string s=""; for(int i=0;i<S.size()-1;i++){ if(S[i]!=S[i+1]){ s+=S[i]; } } s+=S[S.size()-1]; S=s; unordered_map<char,int>mp; for(int i=0;i<S.size();i++){ mp[S[i]]++; } for(auto x:mp){ if(x.second==N)cnt++; } return cnt; } }; 0 virusnetic2 months ago JAVA Solution int getCount (String S, int N) { HashMap<Character, Integer> map = new HashMap<>(); Character prev = '#'; for (Character c: S.toCharArray()) { if (prev != c) map.put(c, map.getOrDefault(c, 0) + 1); prev = c; } int count = 0; for (Character c: map.keySet()) if (map.get(c) == N) count++; return count; } 0 akkeshri140420012 months ago int getCount (string S, int N) { //code here. int count=0; unordered_map<char,int>m; int n=S.length(); int i=0; for(i=0;i<n-1;i++){ if(S[i]==S[i+1]){ int j=i+1; m[S[i]]++; while(S[i]==S[j] and j<n){ i++; j++; } } else{ m[S[i]]++; } } if(i==n-1){ m[S[i]]++; } for(auto x:m){ if(x.second==N){ count++; } } return count; } 0 mayank20213 months ago c++int getCount (string S, int N) { unordered_map<char, int>newmap; newmap[S[0]]++; for(int i=0; i<S.size(); i++) { if(i>0 && S[i]!=S[i-1]) newmap[S[i]]++; } int count=0; for(auto i:newmap) { if(i.second==N) count++; } return count; } 0 gbirla063 months ago int getCount (string S, int N) { unordered_map<char,int>gb; for(int i=0;i<S.length();i++) { if(i<(S.length()-1)) { if(S[i]!=S[i+1]) gb[S[i]]++; } else gb[S[i]]++; } int count=0; for(auto i=gb.begin();i!=gb.end();i++) { if(i->second==N) count+=1; } return count; } +1 as0042303 months ago In C++; { int arr[26] = {0}, total = 0; for(int i = 0; i < S.size(); i++) { arr[S[i] - 'a']++; if(S[i] == S[i+1]) arr[S[i] - 'a']--; } for(int i = 0; i < 26; i++) { if(arr[i] == N) total++; } return total; } 0 chessnoobdj4 months ago c++ using hash int getCount (string S, int k) { int hash[26] = {0}, i=0, N = S.size(), cnt = 0; while(i < N){ hash[S[i]-'a']++; while(i < N-1 && S[i] == S[i+1]) i++; i++; } for(int i=0; i<26; i++){ if(hash[i] == k) cnt++; } return cnt; } 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": 370, "s": 226, "text": "Given a string S. Count the characters that have ‘N’ number of occurrences. If a character appears consecutively it is counted as 1 occurrence." }, { "code": null, "e": 381, "s": 370, "text": "Example 1:" }, { "code": null, "e": 471, "s": 381, "text": "Input:\nS = \"abc\", N = 1\nOutput: 3\nExplanation: 'a', 'b' and 'c' all have \n1 occurrence.\n\n" }, { "code": null, "e": 486, "s": 471, "text": "​Example 2:" }, { "code": null, "e": 587, "s": 486, "text": "Input: \nS = \"geeksforgeeks\", N = 2\nOutput: 4\nExplanation: 'g', 'e', 'k' and 's' have\n2 occurrences.\n" }, { "code": null, "e": 913, "s": 587, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function getCount() which takes the string S and an integer N as inputs and returns the count of the characters that have exactly N occurrences in the string. Note that the consecutive occurrences of a character have to be counted as 1." }, { "code": null, "e": 980, "s": 913, "text": "\nExpected Time Complexity: O(|S|).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1016, "s": 980, "text": "\nConstraints:\n1<=|S|<=105\n1<=N<=103" }, { "code": null, "e": 1020, "s": 1018, "text": "0" }, { "code": null, "e": 1044, "s": 1020, "text": "abhishek11102 weeks ago" }, { "code": null, "e": 1059, "s": 1044, "text": "Java Solution:" }, { "code": null, "e": 1555, "s": 1059, "text": "int getCount (String s, int N)\n {\n // your code here\n int[] arr = new int[26];\n char prev = '#';\n for (int i = 0; i < s.length(); i++) {\n char c = s.charAt(i);\n if (prev != c) {\n arr[c - 'a']++;\n }\n prev = c;\n }\n \n int count = 0;\n for (int i = 0; i < arr.length; i++) {\n if (arr[i] == N) {\n count++;\n }\n }\n return count;\n }" }, { "code": null, "e": 1557, "s": 1555, "text": "0" }, { "code": null, "e": 1579, "s": 1557, "text": "jaatgfg112 months ago" }, { "code": null, "e": 1590, "s": 1579, "text": "hi geeks -" }, { "code": null, "e": 1606, "s": 1590, "text": "ezz cpp soln --" }, { "code": null, "e": 2064, "s": 1606, "text": " int getCount (string S, int N) { map<char,int>mp; int n=S.length(); for(int i=0;i<n;i++){ if(S[i]!=S[i+1]){ mp[S[i]]++; } } map<char,int>::iterator it; int ct=0; for(it=mp.begin();it!=mp.end();it++){ if(it->second==N){ ct++; } } return ct; }" }, { "code": null, "e": 2066, "s": 2064, "text": "0" }, { "code": null, "e": 2093, "s": 2066, "text": "aarisettydivya2 months ago" }, { "code": null, "e": 2260, "s": 2093, "text": "Hey guys, the problem statement said that the expected auxiliary space is O(1). Then how can we use array or any data Structure. I dnt get it. Can anyone explain it?" }, { "code": null, "e": 2263, "s": 2260, "text": "+1" }, { "code": null, "e": 2285, "s": 2263, "text": "codeman992 months ago" }, { "code": null, "e": 2864, "s": 2285, "text": "//c++\nclass Solution\n{\n public:\n int getCount (string S, int N)\n {\n //code here.\n int cnt=0;\n string s=\"\";\n for(int i=0;i<S.size()-1;i++){\n if(S[i]!=S[i+1]){\n s+=S[i];\n }\n }\n s+=S[S.size()-1];\n S=s;\n unordered_map<char,int>mp;\n for(int i=0;i<S.size();i++){\n mp[S[i]]++;\n }\n for(auto x:mp){\n if(x.second==N)cnt++;\n }\n return cnt;\n }\n};" }, { "code": null, "e": 2866, "s": 2864, "text": "0" }, { "code": null, "e": 2889, "s": 2866, "text": "virusnetic2 months ago" }, { "code": null, "e": 2903, "s": 2889, "text": "JAVA Solution" }, { "code": null, "e": 3377, "s": 2905, "text": "\tint getCount (String S, int N) {\n \n HashMap<Character, Integer> map = new HashMap<>();\n \n Character prev = '#';\n for (Character c: S.toCharArray()) {\n if (prev != c)\n map.put(c, map.getOrDefault(c, 0) + 1);\n prev = c;\n }\n \n int count = 0;\n for (Character c: map.keySet())\n if (map.get(c) == N)\n count++;\n \n return count;\n }" }, { "code": null, "e": 3379, "s": 3377, "text": "0" }, { "code": null, "e": 3408, "s": 3379, "text": "akkeshri140420012 months ago" }, { "code": null, "e": 4153, "s": 3408, "text": "int getCount (string S, int N) { //code here. int count=0; unordered_map<char,int>m; int n=S.length(); int i=0; for(i=0;i<n-1;i++){ if(S[i]==S[i+1]){ int j=i+1; m[S[i]]++; while(S[i]==S[j] and j<n){ i++; j++; } } else{ m[S[i]]++; } } if(i==n-1){ m[S[i]]++; } for(auto x:m){ if(x.second==N){ count++; } } return count; }" }, { "code": null, "e": 4155, "s": 4153, "text": "0" }, { "code": null, "e": 4178, "s": 4155, "text": "mayank20213 months ago" }, { "code": null, "e": 4582, "s": 4178, "text": "c++int getCount (string S, int N) { unordered_map<char, int>newmap; newmap[S[0]]++; for(int i=0; i<S.size(); i++) { if(i>0 && S[i]!=S[i-1]) newmap[S[i]]++; } int count=0; for(auto i:newmap) { if(i.second==N) count++; } return count; }" }, { "code": null, "e": 4584, "s": 4582, "text": "0" }, { "code": null, "e": 4605, "s": 4584, "text": "gbirla063 months ago" }, { "code": null, "e": 5108, "s": 4605, "text": "int getCount (string S, int N) { unordered_map<char,int>gb; for(int i=0;i<S.length();i++) { if(i<(S.length()-1)) { if(S[i]!=S[i+1]) gb[S[i]]++; } else gb[S[i]]++; } int count=0; for(auto i=gb.begin();i!=gb.end();i++) { if(i->second==N) count+=1; } return count; }" }, { "code": null, "e": 5111, "s": 5108, "text": "+1" }, { "code": null, "e": 5132, "s": 5111, "text": "as0042303 months ago" }, { "code": null, "e": 5140, "s": 5132, "text": "In C++;" }, { "code": null, "e": 5528, "s": 5140, "text": " { int arr[26] = {0}, total = 0; for(int i = 0; i < S.size(); i++) { arr[S[i] - 'a']++; if(S[i] == S[i+1]) arr[S[i] - 'a']--; } for(int i = 0; i < 26; i++) { if(arr[i] == N) total++; } return total; }" }, { "code": null, "e": 5530, "s": 5528, "text": "0" }, { "code": null, "e": 5554, "s": 5530, "text": "chessnoobdj4 months ago" }, { "code": null, "e": 5569, "s": 5554, "text": "c++ using hash" }, { "code": null, "e": 5985, "s": 5569, "text": "\nint getCount (string S, int k)\n {\n int hash[26] = {0}, i=0, N = S.size(), cnt = 0;\n while(i < N){\n hash[S[i]-'a']++;\n while(i < N-1 && S[i] == S[i+1])\n i++;\n i++;\n }\n for(int i=0; i<26; i++){\n if(hash[i] == k)\n cnt++;\n }\n return cnt;\n }" }, { "code": null, "e": 6131, "s": 5985, "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": 6167, "s": 6131, "text": " Login to access your submissions. " }, { "code": null, "e": 6177, "s": 6167, "text": "\nProblem\n" }, { "code": null, "e": 6187, "s": 6177, "text": "\nContest\n" }, { "code": null, "e": 6250, "s": 6187, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6398, "s": 6250, "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": 6606, "s": 6398, "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": 6712, "s": 6606, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to extract a string that lies between two strings in R?
If we have a long string then we might want to extract a part of string that lies between two strings. For example, if we have a string “E-learning changing the education system in the world” and we want to extract the string “the education system” brave then we must be very careful about passing the strings in string function, you get to know this in examples. The extraction is not difficult with gsub function but we have to make sure that we are using the correct syntax, otherwise, the result will become obnoxious. x1<-"E-learning changing the education system in the world" gsub(".*changing (.+) in.*", "\\1",x1) [1] "the education system" gsub(".*the (.+) system.*", "\\1",x1) [1] "education" x2<-"Tutorialspoint helping programmers around the world" gsub(".*helping (.+) around.*", "\\1",x2) [1] "programmers" gsub(".*Tutorialspoint (.+) programmers.*", "\\1",x2) [1] "helping" gsub(".*helping (.+) the.*", "\\1",x2) [1] "programmers around" x3<-"kindness is a mark of faith, and whoever has not kindness has not faith" gsub(".*a (.+) of.*", "\\1",x3) [1] "mark" gsub(".*and (.+) has.*", "\\1",x3) [1] "whoever has not kindness" gsub(".*has (.+) has.*", "\\1",x3) [1] "not kindness" gsub(".*has (.+) faith.*", "\\1",x3) [1] "not" gsub(".*and (.+) faith.*", "\\1",x3) [1] "whoever has not kindness has not" gsub(".*of (.+) whoever.*", "\\1",x3) [1] "faith, and" gsub(".*of (.+) and.*", "\\1",x3) [1] "faith," x4<-"None of you truly believes until he wishes for his brother what he wishes for himself." gsub(".*of (.+) truly.*", "\\1",x4) [1] "you" gsub(".*believes (.+) until.*", "\\1",x4) [1] "None of you truly believes until he wishes for his brother what he wishes for himself." gsub(".*believes (.+) for.*", "\\1",x4) [1] "until he wishes for his brother what he wishes" gsub(".*you (.+) until.*", "\\1",x4) [1] "truly believes" gsub(".*his (.+) what.*", "\\1",x4) [1] "brother" gsub(".*he (.+) for.*", "\\1",x4) [1] "wishes" gsub(".*until (.+) for.*", "\\1",x4) [1] "he wishes for his brother what he wishes" gsub(".*truly (.+) until.*", "\\1",x4) [1] "believes" gsub(".*truly (.+) what.*", "\\1",x4) [1] "believes until he wishes for his brother" gsub(".*truly (.+) for.*", "\\1",x4) [1] "believes until he wishes for his brother what he wishes" gsub(".*until (.+) what.*", "\\1",x4) [1] "he wishes for his brother" x5<-"To overcome evil with good is good, to resist evil by evil is evil." gsub(".*To (.+) with.*", "\\1",x5) [1] "overcome evil" gsub(".*good (.+) good.*", "\\1",x5) [1] "is" gsub(".*resist (.+) evil.*", "\\1",x5) [1] "evil by evil is" gsub(".*to (.+) evil.*", "\\1",x5) [1] "resist evil by evil is" gsub(".*evil (.+) evil.*", "\\1",x5) [1] "is" gsub(".*To (.+) evil.*", "\\1",x5) [1] "overcome evil with good is good, to resist evil by evil is" gsub(".*good, (.+) resist.*", "\\1",x5) [1] "to" gsub(".with (.+) is.*", "\\1",x5) [1] "To overcome evilgood is good, to resist evil by evil"
[ { "code": null, "e": 1585, "s": 1062, "text": "If we have a long string then we might want to extract a part of string that lies between two strings. For example, if we have a string “E-learning changing the education system in the world” and we want to extract the string “the education system” brave then we must be very careful about passing the strings in string function, you get to know this in examples. The extraction is not difficult with gsub function but we have to make sure that we are using the correct syntax, otherwise, the result will become obnoxious." }, { "code": null, "e": 3983, "s": 1585, "text": "x1<-\"E-learning changing the education system in the world\"\ngsub(\".*changing (.+) in.*\", \"\\\\1\",x1)\n[1] \"the education system\"\ngsub(\".*the (.+) system.*\", \"\\\\1\",x1)\n[1] \"education\"\nx2<-\"Tutorialspoint helping programmers around the world\"\ngsub(\".*helping (.+) around.*\", \"\\\\1\",x2)\n[1] \"programmers\"\ngsub(\".*Tutorialspoint (.+) programmers.*\", \"\\\\1\",x2)\n[1] \"helping\"\ngsub(\".*helping (.+) the.*\", \"\\\\1\",x2)\n[1] \"programmers around\"\nx3<-\"kindness is a mark of faith, and whoever has not kindness has not faith\"\ngsub(\".*a (.+) of.*\", \"\\\\1\",x3)\n[1] \"mark\"\ngsub(\".*and (.+) has.*\", \"\\\\1\",x3)\n[1] \"whoever has not kindness\"\ngsub(\".*has (.+) has.*\", \"\\\\1\",x3)\n[1] \"not kindness\"\ngsub(\".*has (.+) faith.*\", \"\\\\1\",x3)\n[1] \"not\"\ngsub(\".*and (.+) faith.*\", \"\\\\1\",x3)\n[1] \"whoever has not kindness has not\"\ngsub(\".*of (.+) whoever.*\", \"\\\\1\",x3)\n[1] \"faith, and\"\ngsub(\".*of (.+) and.*\", \"\\\\1\",x3)\n[1] \"faith,\"\nx4<-\"None of you truly believes until he wishes for his brother what he wishes for himself.\"\ngsub(\".*of (.+) truly.*\", \"\\\\1\",x4)\n[1] \"you\"\ngsub(\".*believes (.+) until.*\", \"\\\\1\",x4)\n[1] \"None of you truly believes until he wishes for his brother what he wishes for himself.\"\ngsub(\".*believes (.+) for.*\", \"\\\\1\",x4)\n[1] \"until he wishes for his brother what he wishes\"\ngsub(\".*you (.+) until.*\", \"\\\\1\",x4)\n[1] \"truly believes\"\ngsub(\".*his (.+) what.*\", \"\\\\1\",x4)\n[1] \"brother\"\ngsub(\".*he (.+) for.*\", \"\\\\1\",x4)\n[1] \"wishes\"\ngsub(\".*until (.+) for.*\", \"\\\\1\",x4)\n[1] \"he wishes for his brother what he wishes\"\ngsub(\".*truly (.+) until.*\", \"\\\\1\",x4)\n[1] \"believes\"\ngsub(\".*truly (.+) what.*\", \"\\\\1\",x4)\n[1] \"believes until he wishes for his brother\"\ngsub(\".*truly (.+) for.*\", \"\\\\1\",x4)\n[1] \"believes until he wishes for his brother what he wishes\"\ngsub(\".*until (.+) what.*\", \"\\\\1\",x4)\n[1] \"he wishes for his brother\"\nx5<-\"To overcome evil with good is good, to resist evil by evil is evil.\"\ngsub(\".*To (.+) with.*\", \"\\\\1\",x5)\n[1] \"overcome evil\"\ngsub(\".*good (.+) good.*\", \"\\\\1\",x5)\n[1] \"is\"\ngsub(\".*resist (.+) evil.*\", \"\\\\1\",x5)\n[1] \"evil by evil is\"\ngsub(\".*to (.+) evil.*\", \"\\\\1\",x5)\n[1] \"resist evil by evil is\"\ngsub(\".*evil (.+) evil.*\", \"\\\\1\",x5)\n[1] \"is\"\ngsub(\".*To (.+) evil.*\", \"\\\\1\",x5)\n[1] \"overcome evil with good is good, to resist evil by evil is\"\ngsub(\".*good, (.+) resist.*\", \"\\\\1\",x5)\n[1] \"to\"\ngsub(\".with (.+) is.*\", \"\\\\1\",x5)\n[1] \"To overcome evilgood is good, to resist evil by evil\"" } ]
Dive into Queue Module in Python — It’s more than FIFO | by Xiaoxu Gao | Towards Data Science
Queue is a very practical data structure. It’s normally compared with stack, array, linked list, and other linear data structures. What makes a linear structure differs from another is where additions and removals occur. Queue data structure has three types: FIFO, LIFO, and Priority Queue. The queue module in Python implements all of these types. Besides, it’s extremely useful in thread programming as well which makes this module even more shining. In this article, I will first help you refresh knowledge on the data structures and learn how to use module queue. Then I will show you how to use queue to solve 2 different multi-threading problems. In the end, I will talk about the pros and cons of this module. Before moving to some of the advanced features, let’s talk a bit about the queue data structure and learn how to use the module to create a “simple” queue. FIFO — First in, First out This is the basic type of queue. Elements inserted first will be removed first, which works like a waiting list in the real world. The earlier you are added to the list, the earlier you will get the concert ticket. The Python module provides queue.Queue() and queue.SimpleQueue() that implements a FIFO queue. queue.SimpleQueue() is a new feature in Python 3.7. There are 2 differences between them: SimpleQueue() doesn’t do task tracking in the thread programming. Thread programming will be discussed later.SimpleQueue() is an unbounded FIFO queue while Queue() can have an upper bound. In both classes, if the queue is empty, get() operation will be blocked until new elements are inserted. In Queue(), if the queue is full, the put() operation will be blocked as well until elements are removed. This will never happen to SimpleQueue(). According to Python doc, it’s possible to disable the block using block=False in both get() and put(), then you will receive a queue.Full and queue.Empty exception immediately. SimpleQueue() doesn’t do task tracking in the thread programming. Thread programming will be discussed later. SimpleQueue() is an unbounded FIFO queue while Queue() can have an upper bound. In both classes, if the queue is empty, get() operation will be blocked until new elements are inserted. In Queue(), if the queue is full, the put() operation will be blocked as well until elements are removed. This will never happen to SimpleQueue(). According to Python doc, it’s possible to disable the block using block=False in both get() and put(), then you will receive a queue.Full and queue.Empty exception immediately. LIFO — Last in, First out LIFO queue has another name: Stack. Elements inserted last will be removed first. This works like the shelves in the supermarket. People normally take the items on the first row which are added lately. This is implemented in queue.LifoQueue() class. The interface is the same as queue.Queue() except for the order of removing elements. If you compare the results with the previous ones, you should see the difference in the printing result. Priority Queue As the name states, the priority queue gives a priority to each element in the queue. It first pops up the element with the highest priority. In the following graph, element 5 has the highest priority, so it will be the first element popped up in case 2 and 3. Now the question is how Python decides the priority? In the queue module, the lowest valued entries are retrieved first. The lower the value is, the higher the priority it has. Then in the previous example, 2 actually has a higher priority than 5. This is because internally Python priority queue uses min heap queue algorithm. A property of a min heap is that the smallest element is the first element. A heap is in fact a binary tree where node has a value less than its children. When a new node is pushed to the tree, the tree will be sorted again. And the root node is always the next element to be retrieved. Time complexity for push() and pop() operation is O(log n) and O(1). The priority queue doesn’t only work with numbers but also complex data types like tuple or customized classes as long as the objects are comparable. To make a class object comparable, you need to implement a couple of rich comparison methods. A simpler way is to use @dataclass, dataclass can implement these methods for you with config order=True. In this example, the objects are first sorted by key and then by value. There are many applications of queue data structure. A well-known use case must be the message queue in which we have a producer and a consumer. The producer and consumer usually sit in different threads. Luckily, Queue() class has a thread-safe implementation with all the required locking mechanism. So producer and consumer from different threads can work with the same queue instance safely and easily. Essentially, queue stores a number of “tasks” to be done, threads can insert tasks into the queue and take tasks from the queue when they are available, and then complete the task and come back for the next task. If you are new to the threading in Python, I would highly recommend you to read An Intro to Threading in Python from Real Python. It’s a very nice article. realpython.com Ok, I assume you’ve read this article and have a good understanding of how threading module works in Python. Let’s combine it with Queue() class. I gave 2 examples here. They are slightly different use cases. Example 1: Create a queue of image URLs, and download those images “in parallel ” with multiple threads. (If you don’t understand why I added quotes here, please read the above article) I will use save_image function in this example. def save_image(id, url): with open(f'pic{id}.jpg','wb') as image: response = requests.get(url, stream=True) for block in response.iter_content(1024): if not block: break image.write(block) Each Thread object has start() method that starts up a thread, and also join() method that informs the main thread to wait until the thread x completes running. We can solve the problem like this: Since Queue() is designed for multi-threads, it also offers 2 methods that support task tracking: Queue.task_done() and Queue.join(). Queue.task_done() is to indicate that a task in the queue has been processed, it’s usually called after get(). Queue.join() is similar to Thread.join() which will block the main thread until all the tasks in the queue have been processed. But you don’t have to create a worker list workers and do a loop in the end to join every thread, but just do a single queue.join(). Let’s check out the code. Example 2: Create a message queue, a producer and a consumer. Producer and consumer from different threads are able to interact with the same queue instance. The producer will send a sentinel message to tell the consumer to stop the process. In Example 1, we let 10 different threads execute the same function. But in this example, 2 threads are doing completely different jobs. Since there is no real “parallel processing” in Python threading, one thread will do the job first. In this case, producer thread is triggered first and then the consumer thread. You can also see this behavior in the results. If I uncomment line 9, what would be the result? Think about it! 😄 If I suspend the producer thread before each put() operation, then we will see the interaction between producer and consumer more clearly. Insert element 0Retrieve element 0Insert element 1Retrieve element 1Insert element 2Retrieve element 2Insert element 3Retrieve element 3Insert element 4Insert sentinelRetrieve element 4Receive SENTINEL, the consumer will be closed. An obvious advantage of queue is its thread-safe characteristic. But we can’t just take that convenience for granted. What will happen if we don’t have thread-safe queue? What if I want to share a dictionary or a customized class object among multiple threads? For beginners, probably they will run into race conditions issues. Again, the same article has a very intuitive example about race condition. Basically, the same value will not be synchronized among threads. A solution is to use threading.Lock(). But it requires some extra code and extra attention to control threads. Another advantage is to avoid potential memory explosion. If the producer works much faster than the consumer, then tasks will be stored in the “pipeline” until it reaches to the memory boundary. In this case, maxsize attribute can avoid this problem. queue also helps the program to reduce busy waiting. The program doesn’t need to keep trying to pull something from the “pipeline”, but the thread will be blocked until the data is available. Meanwhile, we should also understand the limitation of queue. queue works with multi-threads, so the programs will not run faster because of this. Also, maxsize refers to the number of items in the queue, not the memory size. So, it’s still possible to reach the limit. I hope you enjoyed this article! Leave your comments below if you have any thoughts.
[ { "code": null, "e": 393, "s": 172, "text": "Queue is a very practical data structure. It’s normally compared with stack, array, linked list, and other linear data structures. What makes a linear structure differs from another is where additions and removals occur." }, { "code": null, "e": 625, "s": 393, "text": "Queue data structure has three types: FIFO, LIFO, and Priority Queue. The queue module in Python implements all of these types. Besides, it’s extremely useful in thread programming as well which makes this module even more shining." }, { "code": null, "e": 889, "s": 625, "text": "In this article, I will first help you refresh knowledge on the data structures and learn how to use module queue. Then I will show you how to use queue to solve 2 different multi-threading problems. In the end, I will talk about the pros and cons of this module." }, { "code": null, "e": 1045, "s": 889, "text": "Before moving to some of the advanced features, let’s talk a bit about the queue data structure and learn how to use the module to create a “simple” queue." }, { "code": null, "e": 1072, "s": 1045, "text": "FIFO — First in, First out" }, { "code": null, "e": 1287, "s": 1072, "text": "This is the basic type of queue. Elements inserted first will be removed first, which works like a waiting list in the real world. The earlier you are added to the list, the earlier you will get the concert ticket." }, { "code": null, "e": 1472, "s": 1287, "text": "The Python module provides queue.Queue() and queue.SimpleQueue() that implements a FIFO queue. queue.SimpleQueue() is a new feature in Python 3.7. There are 2 differences between them:" }, { "code": null, "e": 2090, "s": 1472, "text": "SimpleQueue() doesn’t do task tracking in the thread programming. Thread programming will be discussed later.SimpleQueue() is an unbounded FIFO queue while Queue() can have an upper bound. In both classes, if the queue is empty, get() operation will be blocked until new elements are inserted. In Queue(), if the queue is full, the put() operation will be blocked as well until elements are removed. This will never happen to SimpleQueue(). According to Python doc, it’s possible to disable the block using block=False in both get() and put(), then you will receive a queue.Full and queue.Empty exception immediately." }, { "code": null, "e": 2200, "s": 2090, "text": "SimpleQueue() doesn’t do task tracking in the thread programming. Thread programming will be discussed later." }, { "code": null, "e": 2709, "s": 2200, "text": "SimpleQueue() is an unbounded FIFO queue while Queue() can have an upper bound. In both classes, if the queue is empty, get() operation will be blocked until new elements are inserted. In Queue(), if the queue is full, the put() operation will be blocked as well until elements are removed. This will never happen to SimpleQueue(). According to Python doc, it’s possible to disable the block using block=False in both get() and put(), then you will receive a queue.Full and queue.Empty exception immediately." }, { "code": null, "e": 2735, "s": 2709, "text": "LIFO — Last in, First out" }, { "code": null, "e": 2937, "s": 2735, "text": "LIFO queue has another name: Stack. Elements inserted last will be removed first. This works like the shelves in the supermarket. People normally take the items on the first row which are added lately." }, { "code": null, "e": 3176, "s": 2937, "text": "This is implemented in queue.LifoQueue() class. The interface is the same as queue.Queue() except for the order of removing elements. If you compare the results with the previous ones, you should see the difference in the printing result." }, { "code": null, "e": 3191, "s": 3176, "text": "Priority Queue" }, { "code": null, "e": 3452, "s": 3191, "text": "As the name states, the priority queue gives a priority to each element in the queue. It first pops up the element with the highest priority. In the following graph, element 5 has the highest priority, so it will be the first element popped up in case 2 and 3." }, { "code": null, "e": 3856, "s": 3452, "text": "Now the question is how Python decides the priority? In the queue module, the lowest valued entries are retrieved first. The lower the value is, the higher the priority it has. Then in the previous example, 2 actually has a higher priority than 5. This is because internally Python priority queue uses min heap queue algorithm. A property of a min heap is that the smallest element is the first element." }, { "code": null, "e": 4136, "s": 3856, "text": "A heap is in fact a binary tree where node has a value less than its children. When a new node is pushed to the tree, the tree will be sorted again. And the root node is always the next element to be retrieved. Time complexity for push() and pop() operation is O(log n) and O(1)." }, { "code": null, "e": 4486, "s": 4136, "text": "The priority queue doesn’t only work with numbers but also complex data types like tuple or customized classes as long as the objects are comparable. To make a class object comparable, you need to implement a couple of rich comparison methods. A simpler way is to use @dataclass, dataclass can implement these methods for you with config order=True." }, { "code": null, "e": 4558, "s": 4486, "text": "In this example, the objects are first sorted by key and then by value." }, { "code": null, "e": 4965, "s": 4558, "text": "There are many applications of queue data structure. A well-known use case must be the message queue in which we have a producer and a consumer. The producer and consumer usually sit in different threads. Luckily, Queue() class has a thread-safe implementation with all the required locking mechanism. So producer and consumer from different threads can work with the same queue instance safely and easily." }, { "code": null, "e": 5178, "s": 4965, "text": "Essentially, queue stores a number of “tasks” to be done, threads can insert tasks into the queue and take tasks from the queue when they are available, and then complete the task and come back for the next task." }, { "code": null, "e": 5334, "s": 5178, "text": "If you are new to the threading in Python, I would highly recommend you to read An Intro to Threading in Python from Real Python. It’s a very nice article." }, { "code": null, "e": 5349, "s": 5334, "text": "realpython.com" }, { "code": null, "e": 5558, "s": 5349, "text": "Ok, I assume you’ve read this article and have a good understanding of how threading module works in Python. Let’s combine it with Queue() class. I gave 2 examples here. They are slightly different use cases." }, { "code": null, "e": 5744, "s": 5558, "text": "Example 1: Create a queue of image URLs, and download those images “in parallel ” with multiple threads. (If you don’t understand why I added quotes here, please read the above article)" }, { "code": null, "e": 5792, "s": 5744, "text": "I will use save_image function in this example." }, { "code": null, "e": 6035, "s": 5792, "text": "def save_image(id, url): with open(f'pic{id}.jpg','wb') as image: response = requests.get(url, stream=True) for block in response.iter_content(1024): if not block: break image.write(block)" }, { "code": null, "e": 6232, "s": 6035, "text": "Each Thread object has start() method that starts up a thread, and also join() method that informs the main thread to wait until the thread x completes running. We can solve the problem like this:" }, { "code": null, "e": 6764, "s": 6232, "text": "Since Queue() is designed for multi-threads, it also offers 2 methods that support task tracking: Queue.task_done() and Queue.join(). Queue.task_done() is to indicate that a task in the queue has been processed, it’s usually called after get(). Queue.join() is similar to Thread.join() which will block the main thread until all the tasks in the queue have been processed. But you don’t have to create a worker list workers and do a loop in the end to join every thread, but just do a single queue.join(). Let’s check out the code." }, { "code": null, "e": 7006, "s": 6764, "text": "Example 2: Create a message queue, a producer and a consumer. Producer and consumer from different threads are able to interact with the same queue instance. The producer will send a sentinel message to tell the consumer to stop the process." }, { "code": null, "e": 7369, "s": 7006, "text": "In Example 1, we let 10 different threads execute the same function. But in this example, 2 threads are doing completely different jobs. Since there is no real “parallel processing” in Python threading, one thread will do the job first. In this case, producer thread is triggered first and then the consumer thread. You can also see this behavior in the results." }, { "code": null, "e": 7436, "s": 7369, "text": "If I uncomment line 9, what would be the result? Think about it! 😄" }, { "code": null, "e": 7575, "s": 7436, "text": "If I suspend the producer thread before each put() operation, then we will see the interaction between producer and consumer more clearly." }, { "code": null, "e": 7807, "s": 7575, "text": "Insert element 0Retrieve element 0Insert element 1Retrieve element 1Insert element 2Retrieve element 2Insert element 3Retrieve element 3Insert element 4Insert sentinelRetrieve element 4Receive SENTINEL, the consumer will be closed." }, { "code": null, "e": 8068, "s": 7807, "text": "An obvious advantage of queue is its thread-safe characteristic. But we can’t just take that convenience for granted. What will happen if we don’t have thread-safe queue? What if I want to share a dictionary or a customized class object among multiple threads?" }, { "code": null, "e": 8387, "s": 8068, "text": "For beginners, probably they will run into race conditions issues. Again, the same article has a very intuitive example about race condition. Basically, the same value will not be synchronized among threads. A solution is to use threading.Lock(). But it requires some extra code and extra attention to control threads." }, { "code": null, "e": 8639, "s": 8387, "text": "Another advantage is to avoid potential memory explosion. If the producer works much faster than the consumer, then tasks will be stored in the “pipeline” until it reaches to the memory boundary. In this case, maxsize attribute can avoid this problem." }, { "code": null, "e": 8831, "s": 8639, "text": "queue also helps the program to reduce busy waiting. The program doesn’t need to keep trying to pull something from the “pipeline”, but the thread will be blocked until the data is available." }, { "code": null, "e": 9101, "s": 8831, "text": "Meanwhile, we should also understand the limitation of queue. queue works with multi-threads, so the programs will not run faster because of this. Also, maxsize refers to the number of items in the queue, not the memory size. So, it’s still possible to reach the limit." } ]
Count words in a given string - GeeksforGeeks
15 Jun, 2021 Given a string, count number of words in it. The words are separated by following characters: space (‘ ‘) or new line (‘\n’) or tab (‘\t’) or a combination of these. There can be many solutions to this problem. Following is a simple and interesting solution. The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character. C++ C Java Python3 C# PHP Javascript /* C++ program to count no of wordsfrom given input string. */#include <bits/stdc++.h>using namespace std; #define OUT 0#define IN 1 // returns number of words in strunsigned countWords(char *str){ int state = OUT; unsigned wc = 0; // word count // Scan all characters one by one while (*str) { // If next character is a separator, set the // state as OUT if (*str == ' ' || *str == '\n' || *str == '\t') state = OUT; // If next character is not a word separator and // state is OUT, then set the state as IN and // increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++str; } return wc;} // Driver codeint main(void){ char str[] = "One two three\n four\tfive "; cout<<"No of words : "<<countWords(str); return 0;} // This is code is contributed by rathbhupendra /* C program to count no of words from given input string. */#include <stdio.h> #define OUT 0#define IN 1 // returns number of words in strunsigned countWords(char *str){ int state = OUT; unsigned wc = 0; // word count // Scan all characters one by one while (*str) { // If next character is a separator, set the // state as OUT if (*str == ' ' || *str == '\n' || *str == '\t') state = OUT; // If next character is not a word separator and // state is OUT, then set the state as IN and // increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++str; } return wc;} // Driver program to tes above functionsint main(void){ char str[] = "One two three\n four\tfive "; printf("No of words : %u", countWords(str)); return 0;} /* Java program to count no of wordsfrom given input string. */public class GFG { static final int OUT = 0; static final int IN = 1; // returns number of words in str static int countWords(String str) { int state = OUT; int wc = 0; // word count int i = 0; // Scan all characters one by one while (i < str.length()) { // If next character is a separator, set the // state as OUT if (str.charAt(i) == ' ' || str.charAt(i) == '\n' || str.charAt(i) == '\t') state = OUT; // If next character is not a word separator // and state is OUT, then set the state as IN // and increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++i; } return wc; } // Driver program to test above functions public static void main(String args[]) { String str = "One two three\n four\tfive "; System.out.println("No of words : " + countWords(str)); }}// This code is contributed by Sumit Ghosh # Python3 program to count words# in a given stringOUT = 0IN = 1 # Returns number of words in stringdef countWords(string): state = OUT wc = 0 # Scan all characters one by one for i in range(len(string)): # If next character is a separator, # set the state as OUT if (string[i] == ' ' or string[i] == '\n' or string[i] == '\t'): state = OUT # If next character is not a word # separator and state is OUT, then # set the state as IN and increment # word count elif state == OUT: state = IN wc += 1 # Return the number of words return wc # Driver Codestring = "One two three\n four\tfive "print("No. of words : " + str(countWords(string))) # This code is contributed by BHAVYA JAIN // C# program to count no of words// from given input string.using System; class GFG { static int OUT = 0; static int IN = 1; // returns number of words in str static int countWords(String str) { int state = OUT; int wc = 0; // word count int i = 0; // Scan all characters one // by one while (i < str.Length) { // If next character is a separator, // set the state as OUT if (str[i] == ' ' || str[i] == '\n'|| str[i] == '\t') state = OUT; // If next character is not a word // separator and state is OUT, then // set the state as IN and increment // word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++i; } return wc; } // Driver program to test above functions public static void Main() { String str = "One two three\n four\tfive "; Console.WriteLine("No of words : " + countWords(str)); }} // This code is contributed by Sam007. <?php// PHP program to count no of// words from given input string$OUT = 0;$IN = 1; // returns number of words in strfunction countWords($str){ global $OUT, $IN; $state = $OUT; $wc = 0; // word count $i = 0; // Scan all characters one by one while ($i < strlen($str)) { // If next character is // a separator, set the // state as OUT if ($str[$i] == " " || $str[$i] == "\n" || $str[$i] == "\t") $state = $OUT; // If next character is not a // word separator and state is // OUT, then set the state as // IN and increment word count else if ($state == $OUT) { $state = $IN; ++$wc; } // Move to next character ++$i; } return $wc;} // Driver Code$str = "One two three\n four\tfive ";echo "No of words : " . countWords($str); // This code is contributed// by ChitraNayal?> <script>// javascript program to count no of words// from given input string. var OUT = 0; var IN = 1; // returns number of words in str function countWords( str) { var state = OUT; var wc = 0; // word count var i = 0; // Scan all characters one // by one while (i < str.length) { // If next character is a separator, // set the state as OUT if (str[i] == ' ' || str[i] == '\n'|| str[i] == '\t') state = OUT; // If next character is not a word // separator and state is OUT, then // set the state as IN and increment // word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++i; } return wc; } // Driver program to test above functions var str = "One two three\n four\tfive "; document.write("No of words : " + countWords(str)); // This code is contributed by bunnyram19.</script> No of words : 5 Time complexity: O(n)This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Method 2: using String.split() method Get the string to count the total number of words.Check if the string is empty or null then return 0.Use split() method of String class to split the string on whitespaces.The split() method breaks the given string around matches of the given regular expression and returns an array of string.The length of the array is the number of words in the given string.Now, print the result. Get the string to count the total number of words. Check if the string is empty or null then return 0. Use split() method of String class to split the string on whitespaces. The split() method breaks the given string around matches of the given regular expression and returns an array of string. The length of the array is the number of words in the given string. Now, print the result. Below is the implementation of the above approach: Java // Java program to count total// number of words in the stringclass GFG{ // Function to count total number // of words in the string public static int countWords(String str) { // Check if the string is null // or empty then return zero if (str == null || str.isEmpty()) return 0; // Splitting the string around // matches of the given regular // expression String[] words = str.split("\\s+"); // Return number of words // in the given string return words.length; } // Driver Code public static void main(String args[]) { // Given String str String str = "One two three\n four\tfive "; // Print the result System.out.println("No of words : " + countWords(str)); }}// This code is contributed by Prashant Srivastava No of words : 5 Time Complexity: O(N) Method 3: using StringTokenizer.countTokens() method Get the string to count the total number of words.Check if the string is empty or null then return 0.Create a StringTokenizer with the given string passed as a parameter.Count the total number of words in the given string using the countTokens() method.Now, print the result. Get the string to count the total number of words. Check if the string is empty or null then return 0. Create a StringTokenizer with the given string passed as a parameter. Count the total number of words in the given string using the countTokens() method. Now, print the result. Below is the implementation of the above approach: Java // Java program to count total// number of words in the stringimport java.util.StringTokenizer;class GFG{ // Function to count total number // of words in the string public static int countWords(String str) { // Check if the string is null // or empty then return zero if (str == null || str.isEmpty()) return 0; // Create a StringTokenizer with the // given string passed as a parameter StringTokenizer tokens = new StringTokenizer(str); // Return the number of words // in the given string using // countTokens() method return tokens.countTokens(); } // Driver Code public static void main(String args[]) { // Given String str String str = "One two three\n four\tfive "; // Print the result System.out.println("No of words: " + countWords(str)); }}// This code is contributed by Prashant Srivastava No of words: 5 Time Complexity: O(N) Method 4: using Character.isLetter() method Get the string to count the total number of words.Check if the string is empty or null then return 0.Converting the given string into a character array.Check if the character is a letter and index of the character array doesn’t equal to the end of the line that means, it is a word and set isWord by true.Check if the character is not a letter that means there is a space, then we increment the wordCount by one and set the isWord by false.Check for the last word of the sentence and increment the wordCount by one.Now, print the result. Get the string to count the total number of words. Check if the string is empty or null then return 0. Converting the given string into a character array. Check if the character is a letter and index of the character array doesn’t equal to the end of the line that means, it is a word and set isWord by true. Check if the character is not a letter that means there is a space, then we increment the wordCount by one and set the isWord by false. Check for the last word of the sentence and increment the wordCount by one. Now, print the result. Below is the implementation of the above approach: Java Python3 C# Javascript // Java program to count total// number of words in the stringclass GFG{ // Function to count total number // of words in the string public static int countWords(String str) { // Check if the string is null // or empty then return zero if(str == null || str.isEmpty()) return 0; int wordCount = 0; boolean isWord = false; int endOfLine = str.length() - 1; // Converting the given string // into a character array char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // Check if the character is a letter // and index of character array doesn't // equal to end of line that means, it is // a word and set isWord by true if (Character.isLetter(ch[i]) && i != endOfLine) isWord = true; // Check if the character is not a letter // that means there is a space, then we // increment the wordCount by one and set // the isWord by false else if (!Character.isLetter(ch[i]) && isWord) { wordCount++; isWord = false; } // Check for the last word of the // sentence and increment the wordCount // by one else if (Character.isLetter(ch[i]) && i == endOfLine) wordCount++; } // Return the total number of // words in the string return wordCount; } // Driver Code public static void main(String args[]) { // Given String str String str = "One two three\n four\tfive "; // Print the result System.out.println("No of words : " + countWords(str)); }}// This code is contributed by Prashant Srivastava # Python program to count total# number of words in the string # Function to count total number# of words in the stringdef countWords(Str): # Check if the string is null # or empty then return zero if(Str == None or len(Str) == 0): return 0 wordCount = 0 isWord = False endOfLine = len(Str) - 1 # Converting the given string # into a character array ch = list(Str) for i in range(len(ch)): # Check if the character is a letter # and index of character array doesn't # equal to end of line that means, it is # a word and set isWord by true if(ch[i].isalpha() and i != endOfLine): isWord = True # Check if the character is not a letter # that means there is a space, then we # increment the wordCount by one and set # the isWord by false elif(not ch[i].isalpha() and isWord): wordCount += 1 isWord = False # Check for the last word of the # sentence and increment the wordCount # by one elif(ch[i].isalpha() and i == endOfLine): wordCount += 1 # Return the total number of # words in the string return wordCount # Driver Code # Given String strStr = "One two three\n four\tfive " # Print the resultprint("No of words :", countWords(Str)) # This code is contributed by rag2127 // C# program to count total// number of words in the stringusing System;public class GFG{ // Function to count total number // of words in the string static int countWords(String str) { // Check if the string is null // or empty then return zero if(str == null) { return 0; } int wordCount = 0; bool isWord = false; int endOfLine = str.Length - 1; // Converting the given string // into a character array char[] ch = str.ToCharArray(); for (int i = 0; i < ch.Length; i++) { // Check if the character is a letter // and index of character array doesn't // equal to end of line that means, it is // a word and set isWord by true if (Char.IsLetter(ch[i]) && i != endOfLine) { isWord = true; } // Check if the character is not a letter // that means there is a space, then we // increment the wordCount by one and set // the isWord by false else if (!Char.IsLetter(ch[i]) && isWord) { wordCount++; isWord = false; } // Check for the last word of the // sentence and increment the wordCount // by one else if (Char.IsLetter(ch[i]) && i == endOfLine) { wordCount++; } } // Return the total number of // words in the string return wordCount; } // Driver Code static public void Main () { // Given String str string str = "One two three\n four\tfive "; // Print the result Console.WriteLine("No of words : " + countWords(str)); }} // This code is contributed by avanitrachhadiya2155 <script>// Javascript program to count total// number of words in the string // Function to count total number // of words in the stringfunction countWords(str){ // Check if the string is null // or empty then return zero if(str == null || str.length==0) return 0; let wordCount = 0; let isWord = false; let endOfLine = str.length - 1; // Converting the given string // into a character array let ch = str.split(""); for (let i = 0; i < ch.length; i++) { // Check if the character is a letter // and index of character array doesn't // equal to end of line that means, it is // a word and set isWord by true if (isLetter(ch[i]) && i != endOfLine) isWord = true; // Check if the character is not a letter // that means there is a space, then we // increment the wordCount by one and set // the isWord by false else if (!isLetter(ch[i]) && isWord) { wordCount++; isWord = false; } // Check for the last word of the // sentence and increment the wordCount // by one else if (isLetter(ch[i]) && i == endOfLine) wordCount++; } // Return the total number of // words in the string return wordCount;} function isLetter(c) { return c.toLowerCase() != c.toUpperCase();} // Driver Code // Given String strlet str="One two three\n four\tfive "; // Print the resultdocument.write("No of words : " + countWords(str)); // This code is contributed by ab2127</script> No of words : 5 Time Complexity: O(N) YouTubeGeeksforGeeks502K subscribersCount words in a given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:30•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=8HY6HTXjYU8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ukasp rathbhupendra prashant_srivastava avanitrachhadiya2155 rag2127 bunnyram19 ab2127 Amazon Python Strings Amazon Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Write a program to print all permutations of a given string C++ Data Types
[ { "code": null, "e": 25026, "s": 24998, "text": "\n15 Jun, 2021" }, { "code": null, "e": 25193, "s": 25026, "text": "Given a string, count number of words in it. The words are separated by following characters: space (‘ ‘) or new line (‘\\n’) or tab (‘\\t’) or a combination of these. " }, { "code": null, "e": 25527, "s": 25193, "text": "There can be many solutions to this problem. Following is a simple and interesting solution. The idea is to maintain two states: IN and OUT. The state OUT indicates that a separator is seen. State IN indicates that a word character is seen. We increment word count when previous state is OUT and next character is a word character. " }, { "code": null, "e": 25531, "s": 25527, "text": "C++" }, { "code": null, "e": 25533, "s": 25531, "text": "C" }, { "code": null, "e": 25538, "s": 25533, "text": "Java" }, { "code": null, "e": 25546, "s": 25538, "text": "Python3" }, { "code": null, "e": 25549, "s": 25546, "text": "C#" }, { "code": null, "e": 25553, "s": 25549, "text": "PHP" }, { "code": null, "e": 25564, "s": 25553, "text": "Javascript" }, { "code": "/* C++ program to count no of wordsfrom given input string. */#include <bits/stdc++.h>using namespace std; #define OUT 0#define IN 1 // returns number of words in strunsigned countWords(char *str){ int state = OUT; unsigned wc = 0; // word count // Scan all characters one by one while (*str) { // If next character is a separator, set the // state as OUT if (*str == ' ' || *str == '\\n' || *str == '\\t') state = OUT; // If next character is not a word separator and // state is OUT, then set the state as IN and // increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++str; } return wc;} // Driver codeint main(void){ char str[] = \"One two three\\n four\\tfive \"; cout<<\"No of words : \"<<countWords(str); return 0;} // This is code is contributed by rathbhupendra", "e": 26515, "s": 25564, "text": null }, { "code": "/* C program to count no of words from given input string. */#include <stdio.h> #define OUT 0#define IN 1 // returns number of words in strunsigned countWords(char *str){ int state = OUT; unsigned wc = 0; // word count // Scan all characters one by one while (*str) { // If next character is a separator, set the // state as OUT if (*str == ' ' || *str == '\\n' || *str == '\\t') state = OUT; // If next character is not a word separator and // state is OUT, then set the state as IN and // increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++str; } return wc;} // Driver program to tes above functionsint main(void){ char str[] = \"One two three\\n four\\tfive \"; printf(\"No of words : %u\", countWords(str)); return 0;}", "e": 27436, "s": 26515, "text": null }, { "code": "/* Java program to count no of wordsfrom given input string. */public class GFG { static final int OUT = 0; static final int IN = 1; // returns number of words in str static int countWords(String str) { int state = OUT; int wc = 0; // word count int i = 0; // Scan all characters one by one while (i < str.length()) { // If next character is a separator, set the // state as OUT if (str.charAt(i) == ' ' || str.charAt(i) == '\\n' || str.charAt(i) == '\\t') state = OUT; // If next character is not a word separator // and state is OUT, then set the state as IN // and increment word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++i; } return wc; } // Driver program to test above functions public static void main(String args[]) { String str = \"One two three\\n four\\tfive \"; System.out.println(\"No of words : \" + countWords(str)); }}// This code is contributed by Sumit Ghosh", "e": 28687, "s": 27436, "text": null }, { "code": "# Python3 program to count words# in a given stringOUT = 0IN = 1 # Returns number of words in stringdef countWords(string): state = OUT wc = 0 # Scan all characters one by one for i in range(len(string)): # If next character is a separator, # set the state as OUT if (string[i] == ' ' or string[i] == '\\n' or string[i] == '\\t'): state = OUT # If next character is not a word # separator and state is OUT, then # set the state as IN and increment # word count elif state == OUT: state = IN wc += 1 # Return the number of words return wc # Driver Codestring = \"One two three\\n four\\tfive \"print(\"No. of words : \" + str(countWords(string))) # This code is contributed by BHAVYA JAIN", "e": 29497, "s": 28687, "text": null }, { "code": "// C# program to count no of words// from given input string.using System; class GFG { static int OUT = 0; static int IN = 1; // returns number of words in str static int countWords(String str) { int state = OUT; int wc = 0; // word count int i = 0; // Scan all characters one // by one while (i < str.Length) { // If next character is a separator, // set the state as OUT if (str[i] == ' ' || str[i] == '\\n'|| str[i] == '\\t') state = OUT; // If next character is not a word // separator and state is OUT, then // set the state as IN and increment // word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++i; } return wc; } // Driver program to test above functions public static void Main() { String str = \"One two three\\n four\\tfive \"; Console.WriteLine(\"No of words : \" + countWords(str)); }} // This code is contributed by Sam007.", "e": 30771, "s": 29497, "text": null }, { "code": "<?php// PHP program to count no of// words from given input string$OUT = 0;$IN = 1; // returns number of words in strfunction countWords($str){ global $OUT, $IN; $state = $OUT; $wc = 0; // word count $i = 0; // Scan all characters one by one while ($i < strlen($str)) { // If next character is // a separator, set the // state as OUT if ($str[$i] == \" \" || $str[$i] == \"\\n\" || $str[$i] == \"\\t\") $state = $OUT; // If next character is not a // word separator and state is // OUT, then set the state as // IN and increment word count else if ($state == $OUT) { $state = $IN; ++$wc; } // Move to next character ++$i; } return $wc;} // Driver Code$str = \"One two three\\n four\\tfive \";echo \"No of words : \" . countWords($str); // This code is contributed// by ChitraNayal?>", "e": 31729, "s": 30771, "text": null }, { "code": "<script>// javascript program to count no of words// from given input string. var OUT = 0; var IN = 1; // returns number of words in str function countWords( str) { var state = OUT; var wc = 0; // word count var i = 0; // Scan all characters one // by one while (i < str.length) { // If next character is a separator, // set the state as OUT if (str[i] == ' ' || str[i] == '\\n'|| str[i] == '\\t') state = OUT; // If next character is not a word // separator and state is OUT, then // set the state as IN and increment // word count else if (state == OUT) { state = IN; ++wc; } // Move to next character ++i; } return wc; } // Driver program to test above functions var str = \"One two three\\n four\\tfive \"; document.write(\"No of words : \" + countWords(str)); // This code is contributed by bunnyram19.</script>", "e": 32943, "s": 31729, "text": null }, { "code": null, "e": 32959, "s": 32943, "text": "No of words : 5" }, { "code": null, "e": 33155, "s": 32959, "text": "Time complexity: O(n)This article is compiled by Narendra Kangralkar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33193, "s": 33155, "text": "Method 2: using String.split() method" }, { "code": null, "e": 33575, "s": 33193, "text": "Get the string to count the total number of words.Check if the string is empty or null then return 0.Use split() method of String class to split the string on whitespaces.The split() method breaks the given string around matches of the given regular expression and returns an array of string.The length of the array is the number of words in the given string.Now, print the result." }, { "code": null, "e": 33626, "s": 33575, "text": "Get the string to count the total number of words." }, { "code": null, "e": 33678, "s": 33626, "text": "Check if the string is empty or null then return 0." }, { "code": null, "e": 33749, "s": 33678, "text": "Use split() method of String class to split the string on whitespaces." }, { "code": null, "e": 33871, "s": 33749, "text": "The split() method breaks the given string around matches of the given regular expression and returns an array of string." }, { "code": null, "e": 33939, "s": 33871, "text": "The length of the array is the number of words in the given string." }, { "code": null, "e": 33962, "s": 33939, "text": "Now, print the result." }, { "code": null, "e": 34013, "s": 33962, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 34018, "s": 34013, "text": "Java" }, { "code": "// Java program to count total// number of words in the stringclass GFG{ // Function to count total number // of words in the string public static int countWords(String str) { // Check if the string is null // or empty then return zero if (str == null || str.isEmpty()) return 0; // Splitting the string around // matches of the given regular // expression String[] words = str.split(\"\\\\s+\"); // Return number of words // in the given string return words.length; } // Driver Code public static void main(String args[]) { // Given String str String str = \"One two three\\n four\\tfive \"; // Print the result System.out.println(\"No of words : \" + countWords(str)); }}// This code is contributed by Prashant Srivastava", "e": 34953, "s": 34018, "text": null }, { "code": null, "e": 34972, "s": 34956, "text": "No of words : 5" }, { "code": null, "e": 34996, "s": 34974, "text": "Time Complexity: O(N)" }, { "code": null, "e": 35052, "s": 34998, "text": "Method 3: using StringTokenizer.countTokens() method" }, { "code": null, "e": 35330, "s": 35054, "text": "Get the string to count the total number of words.Check if the string is empty or null then return 0.Create a StringTokenizer with the given string passed as a parameter.Count the total number of words in the given string using the countTokens() method.Now, print the result." }, { "code": null, "e": 35381, "s": 35330, "text": "Get the string to count the total number of words." }, { "code": null, "e": 35433, "s": 35381, "text": "Check if the string is empty or null then return 0." }, { "code": null, "e": 35503, "s": 35433, "text": "Create a StringTokenizer with the given string passed as a parameter." }, { "code": null, "e": 35587, "s": 35503, "text": "Count the total number of words in the given string using the countTokens() method." }, { "code": null, "e": 35610, "s": 35587, "text": "Now, print the result." }, { "code": null, "e": 35663, "s": 35612, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 35670, "s": 35665, "text": "Java" }, { "code": "// Java program to count total// number of words in the stringimport java.util.StringTokenizer;class GFG{ // Function to count total number // of words in the string public static int countWords(String str) { // Check if the string is null // or empty then return zero if (str == null || str.isEmpty()) return 0; // Create a StringTokenizer with the // given string passed as a parameter StringTokenizer tokens = new StringTokenizer(str); // Return the number of words // in the given string using // countTokens() method return tokens.countTokens(); } // Driver Code public static void main(String args[]) { // Given String str String str = \"One two three\\n four\\tfive \"; // Print the result System.out.println(\"No of words: \" + countWords(str)); }}// This code is contributed by Prashant Srivastava", "e": 36703, "s": 35670, "text": null }, { "code": null, "e": 36721, "s": 36706, "text": "No of words: 5" }, { "code": null, "e": 36745, "s": 36723, "text": "Time Complexity: O(N)" }, { "code": null, "e": 36791, "s": 36747, "text": "Method 4: using Character.isLetter() method" }, { "code": null, "e": 37331, "s": 36793, "text": "Get the string to count the total number of words.Check if the string is empty or null then return 0.Converting the given string into a character array.Check if the character is a letter and index of the character array doesn’t equal to the end of the line that means, it is a word and set isWord by true.Check if the character is not a letter that means there is a space, then we increment the wordCount by one and set the isWord by false.Check for the last word of the sentence and increment the wordCount by one.Now, print the result." }, { "code": null, "e": 37382, "s": 37331, "text": "Get the string to count the total number of words." }, { "code": null, "e": 37434, "s": 37382, "text": "Check if the string is empty or null then return 0." }, { "code": null, "e": 37486, "s": 37434, "text": "Converting the given string into a character array." }, { "code": null, "e": 37640, "s": 37486, "text": "Check if the character is a letter and index of the character array doesn’t equal to the end of the line that means, it is a word and set isWord by true." }, { "code": null, "e": 37776, "s": 37640, "text": "Check if the character is not a letter that means there is a space, then we increment the wordCount by one and set the isWord by false." }, { "code": null, "e": 37852, "s": 37776, "text": "Check for the last word of the sentence and increment the wordCount by one." }, { "code": null, "e": 37875, "s": 37852, "text": "Now, print the result." }, { "code": null, "e": 37928, "s": 37877, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 37935, "s": 37930, "text": "Java" }, { "code": null, "e": 37943, "s": 37935, "text": "Python3" }, { "code": null, "e": 37946, "s": 37943, "text": "C#" }, { "code": null, "e": 37957, "s": 37946, "text": "Javascript" }, { "code": "// Java program to count total// number of words in the stringclass GFG{ // Function to count total number // of words in the string public static int countWords(String str) { // Check if the string is null // or empty then return zero if(str == null || str.isEmpty()) return 0; int wordCount = 0; boolean isWord = false; int endOfLine = str.length() - 1; // Converting the given string // into a character array char[] ch = str.toCharArray(); for (int i = 0; i < ch.length; i++) { // Check if the character is a letter // and index of character array doesn't // equal to end of line that means, it is // a word and set isWord by true if (Character.isLetter(ch[i]) && i != endOfLine) isWord = true; // Check if the character is not a letter // that means there is a space, then we // increment the wordCount by one and set // the isWord by false else if (!Character.isLetter(ch[i]) && isWord) { wordCount++; isWord = false; } // Check for the last word of the // sentence and increment the wordCount // by one else if (Character.isLetter(ch[i]) && i == endOfLine) wordCount++; } // Return the total number of // words in the string return wordCount; } // Driver Code public static void main(String args[]) { // Given String str String str = \"One two three\\n four\\tfive \"; // Print the result System.out.println(\"No of words : \" + countWords(str)); }}// This code is contributed by Prashant Srivastava", "e": 39994, "s": 37957, "text": null }, { "code": "# Python program to count total# number of words in the string # Function to count total number# of words in the stringdef countWords(Str): # Check if the string is null # or empty then return zero if(Str == None or len(Str) == 0): return 0 wordCount = 0 isWord = False endOfLine = len(Str) - 1 # Converting the given string # into a character array ch = list(Str) for i in range(len(ch)): # Check if the character is a letter # and index of character array doesn't # equal to end of line that means, it is # a word and set isWord by true if(ch[i].isalpha() and i != endOfLine): isWord = True # Check if the character is not a letter # that means there is a space, then we # increment the wordCount by one and set # the isWord by false elif(not ch[i].isalpha() and isWord): wordCount += 1 isWord = False # Check for the last word of the # sentence and increment the wordCount # by one elif(ch[i].isalpha() and i == endOfLine): wordCount += 1 # Return the total number of # words in the string return wordCount # Driver Code # Given String strStr = \"One two three\\n four\\tfive \" # Print the resultprint(\"No of words :\", countWords(Str)) # This code is contributed by rag2127", "e": 41410, "s": 39994, "text": null }, { "code": "// C# program to count total// number of words in the stringusing System;public class GFG{ // Function to count total number // of words in the string static int countWords(String str) { // Check if the string is null // or empty then return zero if(str == null) { return 0; } int wordCount = 0; bool isWord = false; int endOfLine = str.Length - 1; // Converting the given string // into a character array char[] ch = str.ToCharArray(); for (int i = 0; i < ch.Length; i++) { // Check if the character is a letter // and index of character array doesn't // equal to end of line that means, it is // a word and set isWord by true if (Char.IsLetter(ch[i]) && i != endOfLine) { isWord = true; } // Check if the character is not a letter // that means there is a space, then we // increment the wordCount by one and set // the isWord by false else if (!Char.IsLetter(ch[i]) && isWord) { wordCount++; isWord = false; } // Check for the last word of the // sentence and increment the wordCount // by one else if (Char.IsLetter(ch[i]) && i == endOfLine) { wordCount++; } } // Return the total number of // words in the string return wordCount; } // Driver Code static public void Main () { // Given String str string str = \"One two three\\n four\\tfive \"; // Print the result Console.WriteLine(\"No of words : \" + countWords(str)); }} // This code is contributed by avanitrachhadiya2155", "e": 43051, "s": 41410, "text": null }, { "code": "<script>// Javascript program to count total// number of words in the string // Function to count total number // of words in the stringfunction countWords(str){ // Check if the string is null // or empty then return zero if(str == null || str.length==0) return 0; let wordCount = 0; let isWord = false; let endOfLine = str.length - 1; // Converting the given string // into a character array let ch = str.split(\"\"); for (let i = 0; i < ch.length; i++) { // Check if the character is a letter // and index of character array doesn't // equal to end of line that means, it is // a word and set isWord by true if (isLetter(ch[i]) && i != endOfLine) isWord = true; // Check if the character is not a letter // that means there is a space, then we // increment the wordCount by one and set // the isWord by false else if (!isLetter(ch[i]) && isWord) { wordCount++; isWord = false; } // Check for the last word of the // sentence and increment the wordCount // by one else if (isLetter(ch[i]) && i == endOfLine) wordCount++; } // Return the total number of // words in the string return wordCount;} function isLetter(c) { return c.toLowerCase() != c.toUpperCase();} // Driver Code // Given String strlet str=\"One two three\\n four\\tfive \"; // Print the resultdocument.write(\"No of words : \" + countWords(str)); // This code is contributed by ab2127</script>", "e": 44935, "s": 43051, "text": null }, { "code": null, "e": 44954, "s": 44938, "text": "No of words : 5" }, { "code": null, "e": 44978, "s": 44956, "text": "Time Complexity: O(N)" }, { "code": null, "e": 45808, "s": 44980, "text": "YouTubeGeeksforGeeks502K subscribersCount words in a given string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:30•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=8HY6HTXjYU8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 45816, "s": 45810, "text": "ukasp" }, { "code": null, "e": 45830, "s": 45816, "text": "rathbhupendra" }, { "code": null, "e": 45850, "s": 45830, "text": "prashant_srivastava" }, { "code": null, "e": 45871, "s": 45850, "text": "avanitrachhadiya2155" }, { "code": null, "e": 45879, "s": 45871, "text": "rag2127" }, { "code": null, "e": 45890, "s": 45879, "text": "bunnyram19" }, { "code": null, "e": 45897, "s": 45890, "text": "ab2127" }, { "code": null, "e": 45904, "s": 45897, "text": "Amazon" }, { "code": null, "e": 45911, "s": 45904, "text": "Python" }, { "code": null, "e": 45919, "s": 45911, "text": "Strings" }, { "code": null, "e": 45926, "s": 45919, "text": "Amazon" }, { "code": null, "e": 45934, "s": 45926, "text": "Strings" }, { "code": null, "e": 46032, "s": 45934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46050, "s": 46032, "text": "Python Dictionary" }, { "code": null, "e": 46085, "s": 46050, "text": "Read a file line by line in Python" }, { "code": null, "e": 46107, "s": 46085, "text": "Enumerate() in Python" }, { "code": null, "e": 46139, "s": 46107, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 46169, "s": 46139, "text": "Iterate over a list in Python" }, { "code": null, "e": 46215, "s": 46169, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 46240, "s": 46215, "text": "Reverse a string in Java" }, { "code": null, "e": 46274, "s": 46240, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 46334, "s": 46274, "text": "Write a program to print all permutations of a given string" } ]
YAML - Flow Styles
Flow styles in YAML can be thought of as a natural extension of JSON to cover the folding content lines for better readable feature which uses anchors and aliases to create the object instances. In this chapter, we will focus on flow representation of the following concepts − Alias Nodes Empty Nodes Flow Scalar styles Flow collection styles Flow nodes The example of alias nodes is shown below − %YAML 1.2 --- !!map { ? !!str "First occurrence" : &A !!str "Foo", ? !!str "Override anchor" : &B !!str "Bar", ? !!str "Second occurrence" : *A, ? !!str "Reuse anchor" : *B, } The JSON output of the code given above is given below − { "First occurrence": "Foo", "Second occurrence": "Foo", "Override anchor": "Bar", "Reuse anchor": "Bar" } Nodes with empty content are considered as empty nodes. The following example shows this − %YAML 1.2 --- !!map { ? !!str "foo" : !!str "", ? !!str "" : !!str "bar", } The output of empty nodes in JSON is represented as below − { "": "bar", "foo": "" } Flow scalar styles include double-quoted, single-quoted and plain types. The basic example for the same is given below − %YAML 1.2 --- !!map { ? !!str "implicit block key" : !!seq [ !!map { ? !!str "implicit flow key" : !!str "value", } ] } The output in JSON format for the example given above is shown below − { "implicit block key": [ { "implicit flow key": "value" } ] } Flow collection in YAML is nested with a block collection within another flow collection. Flow collection entries are terminated with comma (,) indicator. The following example explains the flow collection block in detail − %YAML 1.2 --- !!seq [ !!seq [ !!str "one", !!str "two", ], !!seq [ !!str "three", !!str "four", ], ] The output for flow collection in JSON is shown below − [ [ "one", "two" ], [ "three", "four" ] ] Flow styles like JSON include start and end indicators. The only flow style that does not have any property is the plain scalar. %YAML 1.2 --- !!seq [ !!seq [ !!str "a", !!str "b" ], !!map { ? !!str "a" : !!str "b" }, !!str "a", !!str "b", !!str "c",] The output for the code shown above in JSON format is given below − [ [ "a", "b" ], { "a": "b" }, "a", "b", "c" ] 33 Lectures 44 mins Tarun Telang Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2048, "text": "Flow styles in YAML can be thought of as a natural extension of JSON to cover the folding content lines for better readable feature which uses anchors and aliases to create the object instances. In this chapter, we will focus on flow representation of the following concepts −" }, { "code": null, "e": 2337, "s": 2325, "text": "Alias Nodes" }, { "code": null, "e": 2349, "s": 2337, "text": "Empty Nodes" }, { "code": null, "e": 2368, "s": 2349, "text": "Flow Scalar styles" }, { "code": null, "e": 2391, "s": 2368, "text": "Flow collection styles" }, { "code": null, "e": 2402, "s": 2391, "text": "Flow nodes" }, { "code": null, "e": 2446, "s": 2402, "text": "The example of alias nodes is shown below −" }, { "code": null, "e": 2646, "s": 2446, "text": "%YAML 1.2\n---\n!!map {\n ? !!str \"First occurrence\"\n : &A !!str \"Foo\",\n ? !!str \"Override anchor\"\n : &B !!str \"Bar\",\n ? !!str \"Second occurrence\"\n : *A,\n ? !!str \"Reuse anchor\"\n : *B,\n}" }, { "code": null, "e": 2703, "s": 2646, "text": "The JSON output of the code given above is given below −" }, { "code": null, "e": 2826, "s": 2703, "text": "{\n \"First occurrence\": \"Foo\", \n \"Second occurrence\": \"Foo\", \n \"Override anchor\": \"Bar\", \n \"Reuse anchor\": \"Bar\"\n}\n" }, { "code": null, "e": 2917, "s": 2826, "text": "Nodes with empty content are considered as empty nodes. The following example shows this −" }, { "code": null, "e": 2999, "s": 2917, "text": "%YAML 1.2\n---\n!!map {\n ? !!str \"foo\" : !!str \"\",\n ? !!str \"\" : !!str \"bar\",\n}" }, { "code": null, "e": 3059, "s": 2999, "text": "The output of empty nodes in JSON is represented as below −" }, { "code": null, "e": 3092, "s": 3059, "text": "{\n \"\": \"bar\", \n \"foo\": \"\"\n}\n" }, { "code": null, "e": 3213, "s": 3092, "text": "Flow scalar styles include double-quoted, single-quoted and plain types. The basic example for the same is given below −" }, { "code": null, "e": 3374, "s": 3213, "text": "%YAML 1.2\n---\n!!map {\n ? !!str \"implicit block key\"\n : !!seq [\n !!map {\n ? !!str \"implicit flow key\"\n : !!str \"value\",\n }\n ] \n}" }, { "code": null, "e": 3445, "s": 3374, "text": "The output in JSON format for the example given above is shown below −" }, { "code": null, "e": 3537, "s": 3445, "text": "{\n \"implicit block key\": [\n {\n \"implicit flow key\": \"value\"\n }\n ] \n}\n" }, { "code": null, "e": 3761, "s": 3537, "text": "Flow collection in YAML is nested with a block collection within another flow collection. Flow collection entries are terminated with comma (,) indicator. The following example explains the flow collection block in detail −" }, { "code": null, "e": 3902, "s": 3761, "text": "%YAML 1.2\n---\n!!seq [\n !!seq [\n !!str \"one\",\n !!str \"two\",\n ],\n \n !!seq [\n !!str \"three\",\n !!str \"four\",\n ],\n]" }, { "code": null, "e": 3958, "s": 3902, "text": "The output for flow collection in JSON is shown below −" }, { "code": null, "e": 4040, "s": 3958, "text": "[\n [\n \"one\", \n \"two\"\n ], \n [\n \"three\", \n \"four\"\n ]\n]\n" }, { "code": null, "e": 4169, "s": 4040, "text": "Flow styles like JSON include start and end indicators. The only flow style that does not have any property is the plain scalar." }, { "code": null, "e": 4292, "s": 4169, "text": "%YAML 1.2\n---\n!!seq [\n!!seq [ !!str \"a\", !!str \"b\" ],\n!!map { ? !!str \"a\" : !!str \"b\" },\n!!str \"a\",\n!!str \"b\",\n!!str \"c\",]" }, { "code": null, "e": 4360, "s": 4292, "text": "The output for the code shown above in JSON format is given below −" }, { "code": null, "e": 4459, "s": 4360, "text": "[\n [\n \"a\", \n \"b\"\n ], \n \n {\n \"a\": \"b\"\n }, \n \n \"a\", \n \"b\", \n \"c\"\n]\n" }, { "code": null, "e": 4491, "s": 4459, "text": "\n 33 Lectures \n 44 mins\n" }, { "code": null, "e": 4505, "s": 4491, "text": " Tarun Telang" }, { "code": null, "e": 4512, "s": 4505, "text": " Print" }, { "code": null, "e": 4523, "s": 4512, "text": " Add Notes" } ]
Explaining Scikit-learn models with SHAP | by Zolzaya Luvsandorj | Towards Data Science
Explainable AI (XAI) helps build trust and confidence in machine learning models by making them more transparent. XAI is a set of tools and frameworks that can be used to understand and interpret how a machine learning model makes decisions. One useful XAI tool is the SHAP library in Python. This tool allows us to quantify feature’s contribution towards a single prediction as well as predictions at an overall level. The library also comes with aesthetically pleasing easy-to-use visualisations. In this post, we will learn the basics of the SHAP library to understand predictions from regression and classification models built in Scikit-learn. Shap value helps us quantify feature’s contribution towards a prediction. Shap value closer to zero means the feature contributes little to the prediction whereas shap value away from zero indicates the feature contributes more. Let’s learn how to pull shap values for features for a regression problem. We will start by loading libraries and sample data, then will build a quick model to predict diabetes progression: import numpy as npnp.set_printoptions(formatter={'float':lambda x:"{:.4f}".format(x)})import pandas as pdpd.options.display.float_format = "{:.3f}".formatimport seaborn as snsimport matplotlib.pyplot as pltsns.set(style='darkgrid', context='talk', palette='rainbow')from sklearn.datasets import load_diabetesfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import (RandomForestRegressor, RandomForestClassifier)import shap # v0.39.0shap.initjs()# Import sample datadiabetes = load_diabetes(as_frame=True)X = diabetes['data'].iloc[:, :4] # Select first 4 columnsy = diabetes['target']# Partition dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)print(f"Training features shape: {X_train.shape}")print(f"Training target shape: {y_train.shape}\n")print(f"Test features shape: {X_test.shape}")print(f"Test target shape: {y_test.shape}")display(X_train.head())# Train a simple modelmodel = RandomForestRegressor(random_state=42)model.fit(X_train, y_train) One common way to get shap values is to use the Explainer object. Let’s create an Explainer object and extract shap_test for the test data: explainer = shap.Explainer(model)shap_test = explainer(X_test)print(f"Shap values length: {len(shap_test)}\n")print(f"Sample shap value:\n{shap_test[0]}") The length of shap_test is 89 because it contains a record for each test instance. From looking at the first test record, we can see that there are three attributes:◼ shap_test[0].base_values: Base value for target◼ shap_test[0].data: Value for each feature◼ shap_test[0].values: Shap value for each feature Let’s understand what each one of these attributes shows us. Base value (shap_test.base_values), also known as the expected value (explainer.expected_value), is the average target value in the training data. We can check this with the following code: print(f"Expected value: {explainer.expected_value[0]:.1f}")print(f"Average target value (training data): {y_train.mean():.1f}")print(f"Base value: {np.unique(shap_test.base_values)[0]:.1f}") Hence, we will use the word expected value and base value interchangeably. Next, shap_test.data contains the same values as X_test: (shap_test.data == X_test).describe() Let’s convert it to a DataFrame and have a look: pd.DataFrame(shap_test.data, columns=shap_test.feature_names, index=X_test.index) So, it’s just a copy of the dataset we passed on to. The most important attribute from shap_test is the values attribute. This is because we can access the shap values from it. Let’s convert the shap values into a DataFrame for easier manipulation: shap_df = pd.DataFrame(shap_test.values, columns=shap_test.feature_names, index=X_test.index)shap_df We can see the shap values by feature for each record. If we add these shap values to the expected value, we will get the prediction: Let’s check if this is the case: np.isclose(model.predict(X_test), explainer.expected_value[0] + shap_df.sum(axis=1)) Awesome! Here, we used np.isclose() to ignore floating point inaccuracy. Now, we have the shap values, we can do custom visualisations like this one to understand the feature contribution: columns = shap_df.apply(np.abs).mean()\ .sort_values(ascending=False).indexfig, ax = plt.subplots(1, 2, figsize=(11,4))sns.barplot(data=shap_df[columns].apply(np.abs), orient='h', ax=ax[0])ax[0].set_title("Mean absolute shap value")sns.boxplot(data=shap_df[columns], orient='h', ax=ax[1])ax[1].set_title("Distribution of shap values"); The left subplot shows the mean absolute shap value for each feature whereas the right subplot shows the distribution of the shap values by feature. One takeaway from these graphs is that bmi has the biggest contribution among the 4 features being used. While we can construct our own visualisations using the shap values, the shap package comes with built-in fancy visualisations. In this section, we will familiarise with a selected few of these visualisations. We are going to look at two main kinds of plots:🌳 Global: Plots visualising feature’s overall contribution. This kind of plot shows an aggregated contribution of a feature over the entire data. 🍀 Local: Plots showing feature’s contribution in a particular instance. This helps us drill down into individual predictions. For the left subplot shown earlier, there’s an equivalent built-in function which takes only a few keystrokes: shap.plots.bar(shap_test) This simple but useful plot shows the strength of features’ contribution. The plot is based on the mean absolute shap values by features: shap_df.apply(np.abs).mean(). Features are ranked from top to bottom where feature with the highest average absolute shap value is shown at the top. Another useful plot is summary plot: shap.summary_plot(shap_test) Here’s an alternative syntax: shap.plots.beeswarm(shap_test) for this exact plot. Just like before, features are sorted by their mean absolute shap value. This chart is more complicated and packed with more information compared to the previous bar plot. Here’s a guide to interpret this plot:◼️ Horizontal axis of the plot shows the shap value distribution of a feature. Each dot represents a record in the dataset. For instance, we can see that for bmi, dots are quite scattered and there are barely any dots around 0 whereas dots are clustered closer to 0 for age.◼️ The colour of dots shows the feature values. This addition dimension allows us to see the how the shap values changes as the feature value changes. In other words, we can see the direction of the relationship. For instance, we can see that shap value tend to be higher when bmi is high (represented by hot pink dots) and lower when bmi is low (represented by blue dots). There are also some purple points scattered across the spectrum as well. If we find the default colourmap to be not intuitive or not suitable, we can change it to our preferred matplotlib colourmap like this: shap.summary_plot(shap_test, cmap=plt.get_cmap("winter_r")) In addition, there are different plot types we can use. Here’s an example: shap.summary_plot(shap_test, plot_type='violin') Heatmap is another way to visualise the shap values. Instead of aggregating shap value to a mean, we see colour-coded individual values. Features are plotted on y-axis and records are plotted on x-axis: shap.plots.heatmap(shap_test) This heatmap is supplemented by a line plot of the predicted value (i.e. f(x)) for each record at the top. We can change the colourmap to our desired one with the cmap parameter: shap.plots.heatmap(shap_test, cmap=plt.get_cmap("winter_r")) This interactive plot allows us to see shap value make-up by record: shap.force_plot(explainer.expected_value, shap_test.values, X_test) Just like heatmap, x-axis shows each record. Positive shap values are shown in red and and negative ones are in blue. For instance, since the first record had more red contributions than blue ones, the prediction for this record would be higher than the expected value. The interactivity allows us to change both axes. For instance, y-axis shows predictions, f(x) and x-axis is sorted by the output (prediction) value in the snapshot above. Now we will look at plots for understanding predictions for individual cases. Let’s start with a bar plot: shap.plots.bar(shap_test[0]) The syntax is exactly same as in section ‘2.1. Global | Bar plot’ except this time we sliced the data for a single record. This is another alternative to the bar plot: class WaterfallData(): def __init__ (self, shap_test, index): self.values = shap_test[index].values self.base_values = shap_test[index].base_values[0] self.data = shap_test[index].data self.feature_names = shap_test.feature_namesshap.plots.waterfall(WaterfallData(shap_test, 0)) The waterfall plot is information-dense and there are four bits of information:◼️ On the y-axis, we see the actual feature value for the record. If you are not sure what I mean, compare X_test.head(1) to the values on the y-axis. ◼️ At the bottom right corner of the chart, we see E[f(X)], the expected value.◼️ At the top left corner, we see f(x), the predicted value.◼️ ️Just like the previous bar plot, horizontal bars represent the colour-coded feature contribution. Starting from the expected value at the bottom, we can see how each contribution is moving the prediction up and down to finally arrive at the predicted value. Last plot to familiarise is the force plot for a single record. If we rotate this plot 90 degrees and plot it for multiple records, we will see the global force plot. shap.plots.force(shap_test[0]) We can see both the base value:153.4 and the prediction: 103.48. We can also see the breakdown of the feature contributions. We have so far focused a regression example. In this section, we’ll learn one way to tweak what we learned to suit a binary classification. Let’s import the subset of titanic data and train a simple model: # Import sample datadf = sns.load_dataset('titanic')df['is_male'] = df['sex'].map({'male': 1, 'female': 0}) # Encode# Keep numerical complete columnsdf = df.select_dtypes('number').dropna() X = df.drop(columns=['survived'])y = df['survived']# Partition dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)print(f"Training features shape: {X_train.shape}")print(f"Training target shape: {y_train.shape}\n")print(f"Test features shape: {X_test.shape}")print(f"Test target shape: {y_test.shape}")display(X_train.head())# Train a simple modelmodel = RandomForestClassifier(random_state=42)model.fit(X_train, y_train) We will create an explainer object and extract shap values like before: explainer = shap.Explainer(model)shap_test = explainer(X_test)print(f"Length of shap_test: {len(shap_test)}\n")print(f"Sample shap_test:\n{shap_test[0]}") Just like regression shap_test.data will contain the same number of records as the X_test. However, from this example record, we can see that the dimension of values and base_values are different. Let’s first look at the base value. The base value now tells us the probability for each class. We will focus on the positive class (i.e. y==1, survival): print(f"Expected value: {explainer.expected_value[1]:.2f}")print(f"Average target value (training data): {y_train.mean():.2f}")print(f"Base value: {np.unique(shap_test.base_values)[0]:.2f}") Now, let’s look at the shap values. Shap values are also provided for both classes. You will also notice that they are the negative of each other. We can extract the shap values for positive class like this: shap_df = pd.DataFrame(shap_test.values[:,:,1], columns=shap_test.feature_names, index=X_test.index)shap_df Let’s double check whether adding the sum of shap values to the expected probability will give the predicted probability: np.isclose(model.predict_proba(X_test)[:,1], explainer.expected_value[1] + shap_df.sum(axis=1)) Awesome, now you know how to get the shap values in the unit of probability. It’s time to tweak the plots we looked at earlier. To avoid repeating, I will show an example for global plots and another for local plots since the other plots can be replicated using the same logic. Global | Bar plot: Let’s check out features’ overall contribution to predicting the positive class: shap.plots.bar(shap_test[:,:,1]) Local | Waterfall plot: Let’s look at waterfall plot for the first test record: shap.plots.waterfall(shap_test[:,:,1][0]) From this plot, we can see how each feature has contributed towards predicted probability of belonging to the positive class: 0.98 for this record. Before we wrap up, let’s look at an example use-case. We will find the most incorrect examples for the survivors and will try to understand why the model makes incorrect predictions: test = pd.concat([X_test, y_test], axis=1)test['probability'] = model.predict_proba(X_test)[:,1]test['order'] = np.arange(len(test))test.query('survived==1').nsmallest(5, 'probability') The probability of survival was 0.03 for the first record. Let’s check out how features contributed to arrive at this prediction: ind1 = test.query('survived==1')\ .nsmallest(1, 'probability')['order'].values[0]shap.plots.waterfall(shap_test[:,:,1][ind1]) Young third-class male passenger... We can see mostly gender, passenger class and age have pushed down the prediction. Let’s find similar examples in the training data: pd.concat([X_train, y_train], axis=1)[(X_train['is_male']==1) & (X_train['pclass']==3) & (X_train['age']==22) & (X_train['fare'].between(7,8))] All similar training examples actually didn’t survive. Now, that makes sense! This was a small use-case of how shap can be helpful in unravelling why the model comes up with an incorrect prediction. Hope you enjoyed learning how to use the SHAP library to understand both regression and classification models built in Scikit-learn. Since SHAP is model-agnostic, you can also use it for other models too. I hope you will get to use this explainable AI tool soon to understand why the model comes up with its predictions in order to improve the model and explain it to others better. Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading this article. If you are interested, here are links to some of my other posts:◼️️ K-Nearest Neighbours explained◼️️ Logistic regression explained◼️️ Comparing Random Forest and Gradient Boosting◼️️ How are decision trees built?◼️️ Pipeline, ColumnTransformer and FeatureUnion explained◼️️ FeatureUnion, ColumnTransformer & Pipeline for preprocessing text data Bye for now 🏃 💨
[ { "code": null, "e": 820, "s": 171, "text": "Explainable AI (XAI) helps build trust and confidence in machine learning models by making them more transparent. XAI is a set of tools and frameworks that can be used to understand and interpret how a machine learning model makes decisions. One useful XAI tool is the SHAP library in Python. This tool allows us to quantify feature’s contribution towards a single prediction as well as predictions at an overall level. The library also comes with aesthetically pleasing easy-to-use visualisations. In this post, we will learn the basics of the SHAP library to understand predictions from regression and classification models built in Scikit-learn." }, { "code": null, "e": 1049, "s": 820, "text": "Shap value helps us quantify feature’s contribution towards a prediction. Shap value closer to zero means the feature contributes little to the prediction whereas shap value away from zero indicates the feature contributes more." }, { "code": null, "e": 1239, "s": 1049, "text": "Let’s learn how to pull shap values for features for a regression problem. We will start by loading libraries and sample data, then will build a quick model to predict diabetes progression:" }, { "code": null, "e": 2392, "s": 1239, "text": "import numpy as npnp.set_printoptions(formatter={'float':lambda x:\"{:.4f}\".format(x)})import pandas as pdpd.options.display.float_format = \"{:.3f}\".formatimport seaborn as snsimport matplotlib.pyplot as pltsns.set(style='darkgrid', context='talk', palette='rainbow')from sklearn.datasets import load_diabetesfrom sklearn.model_selection import train_test_splitfrom sklearn.ensemble import (RandomForestRegressor, RandomForestClassifier)import shap # v0.39.0shap.initjs()# Import sample datadiabetes = load_diabetes(as_frame=True)X = diabetes['data'].iloc[:, :4] # Select first 4 columnsy = diabetes['target']# Partition dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)print(f\"Training features shape: {X_train.shape}\")print(f\"Training target shape: {y_train.shape}\\n\")print(f\"Test features shape: {X_test.shape}\")print(f\"Test target shape: {y_test.shape}\")display(X_train.head())# Train a simple modelmodel = RandomForestRegressor(random_state=42)model.fit(X_train, y_train)" }, { "code": null, "e": 2532, "s": 2392, "text": "One common way to get shap values is to use the Explainer object. Let’s create an Explainer object and extract shap_test for the test data:" }, { "code": null, "e": 2687, "s": 2532, "text": "explainer = shap.Explainer(model)shap_test = explainer(X_test)print(f\"Shap values length: {len(shap_test)}\\n\")print(f\"Sample shap value:\\n{shap_test[0]}\")" }, { "code": null, "e": 2995, "s": 2687, "text": "The length of shap_test is 89 because it contains a record for each test instance. From looking at the first test record, we can see that there are three attributes:◼ shap_test[0].base_values: Base value for target◼ shap_test[0].data: Value for each feature◼ shap_test[0].values: Shap value for each feature" }, { "code": null, "e": 3056, "s": 2995, "text": "Let’s understand what each one of these attributes shows us." }, { "code": null, "e": 3246, "s": 3056, "text": "Base value (shap_test.base_values), also known as the expected value (explainer.expected_value), is the average target value in the training data. We can check this with the following code:" }, { "code": null, "e": 3437, "s": 3246, "text": "print(f\"Expected value: {explainer.expected_value[0]:.1f}\")print(f\"Average target value (training data): {y_train.mean():.1f}\")print(f\"Base value: {np.unique(shap_test.base_values)[0]:.1f}\")" }, { "code": null, "e": 3512, "s": 3437, "text": "Hence, we will use the word expected value and base value interchangeably." }, { "code": null, "e": 3569, "s": 3512, "text": "Next, shap_test.data contains the same values as X_test:" }, { "code": null, "e": 3607, "s": 3569, "text": "(shap_test.data == X_test).describe()" }, { "code": null, "e": 3656, "s": 3607, "text": "Let’s convert it to a DataFrame and have a look:" }, { "code": null, "e": 3751, "s": 3656, "text": "pd.DataFrame(shap_test.data, columns=shap_test.feature_names, index=X_test.index)" }, { "code": null, "e": 3804, "s": 3751, "text": "So, it’s just a copy of the dataset we passed on to." }, { "code": null, "e": 4000, "s": 3804, "text": "The most important attribute from shap_test is the values attribute. This is because we can access the shap values from it. Let’s convert the shap values into a DataFrame for easier manipulation:" }, { "code": null, "e": 4147, "s": 4000, "text": "shap_df = pd.DataFrame(shap_test.values, columns=shap_test.feature_names, index=X_test.index)shap_df" }, { "code": null, "e": 4281, "s": 4147, "text": "We can see the shap values by feature for each record. If we add these shap values to the expected value, we will get the prediction:" }, { "code": null, "e": 4314, "s": 4281, "text": "Let’s check if this is the case:" }, { "code": null, "e": 4410, "s": 4314, "text": "np.isclose(model.predict(X_test), explainer.expected_value[0] + shap_df.sum(axis=1))" }, { "code": null, "e": 4599, "s": 4410, "text": "Awesome! Here, we used np.isclose() to ignore floating point inaccuracy. Now, we have the shap values, we can do custom visualisations like this one to understand the feature contribution:" }, { "code": null, "e": 4963, "s": 4599, "text": "columns = shap_df.apply(np.abs).mean()\\ .sort_values(ascending=False).indexfig, ax = plt.subplots(1, 2, figsize=(11,4))sns.barplot(data=shap_df[columns].apply(np.abs), orient='h', ax=ax[0])ax[0].set_title(\"Mean absolute shap value\")sns.boxplot(data=shap_df[columns], orient='h', ax=ax[1])ax[1].set_title(\"Distribution of shap values\");" }, { "code": null, "e": 5217, "s": 4963, "text": "The left subplot shows the mean absolute shap value for each feature whereas the right subplot shows the distribution of the shap values by feature. One takeaway from these graphs is that bmi has the biggest contribution among the 4 features being used." }, { "code": null, "e": 5747, "s": 5217, "text": "While we can construct our own visualisations using the shap values, the shap package comes with built-in fancy visualisations. In this section, we will familiarise with a selected few of these visualisations. We are going to look at two main kinds of plots:🌳 Global: Plots visualising feature’s overall contribution. This kind of plot shows an aggregated contribution of a feature over the entire data. 🍀 Local: Plots showing feature’s contribution in a particular instance. This helps us drill down into individual predictions." }, { "code": null, "e": 5858, "s": 5747, "text": "For the left subplot shown earlier, there’s an equivalent built-in function which takes only a few keystrokes:" }, { "code": null, "e": 5884, "s": 5858, "text": "shap.plots.bar(shap_test)" }, { "code": null, "e": 6171, "s": 5884, "text": "This simple but useful plot shows the strength of features’ contribution. The plot is based on the mean absolute shap values by features: shap_df.apply(np.abs).mean(). Features are ranked from top to bottom where feature with the highest average absolute shap value is shown at the top." }, { "code": null, "e": 6208, "s": 6171, "text": "Another useful plot is summary plot:" }, { "code": null, "e": 6237, "s": 6208, "text": "shap.summary_plot(shap_test)" }, { "code": null, "e": 7250, "s": 6237, "text": "Here’s an alternative syntax: shap.plots.beeswarm(shap_test) for this exact plot. Just like before, features are sorted by their mean absolute shap value. This chart is more complicated and packed with more information compared to the previous bar plot. Here’s a guide to interpret this plot:◼️ Horizontal axis of the plot shows the shap value distribution of a feature. Each dot represents a record in the dataset. For instance, we can see that for bmi, dots are quite scattered and there are barely any dots around 0 whereas dots are clustered closer to 0 for age.◼️ The colour of dots shows the feature values. This addition dimension allows us to see the how the shap values changes as the feature value changes. In other words, we can see the direction of the relationship. For instance, we can see that shap value tend to be higher when bmi is high (represented by hot pink dots) and lower when bmi is low (represented by blue dots). There are also some purple points scattered across the spectrum as well." }, { "code": null, "e": 7386, "s": 7250, "text": "If we find the default colourmap to be not intuitive or not suitable, we can change it to our preferred matplotlib colourmap like this:" }, { "code": null, "e": 7446, "s": 7386, "text": "shap.summary_plot(shap_test, cmap=plt.get_cmap(\"winter_r\"))" }, { "code": null, "e": 7521, "s": 7446, "text": "In addition, there are different plot types we can use. Here’s an example:" }, { "code": null, "e": 7570, "s": 7521, "text": "shap.summary_plot(shap_test, plot_type='violin')" }, { "code": null, "e": 7773, "s": 7570, "text": "Heatmap is another way to visualise the shap values. Instead of aggregating shap value to a mean, we see colour-coded individual values. Features are plotted on y-axis and records are plotted on x-axis:" }, { "code": null, "e": 7803, "s": 7773, "text": "shap.plots.heatmap(shap_test)" }, { "code": null, "e": 7910, "s": 7803, "text": "This heatmap is supplemented by a line plot of the predicted value (i.e. f(x)) for each record at the top." }, { "code": null, "e": 7982, "s": 7910, "text": "We can change the colourmap to our desired one with the cmap parameter:" }, { "code": null, "e": 8043, "s": 7982, "text": "shap.plots.heatmap(shap_test, cmap=plt.get_cmap(\"winter_r\"))" }, { "code": null, "e": 8112, "s": 8043, "text": "This interactive plot allows us to see shap value make-up by record:" }, { "code": null, "e": 8196, "s": 8112, "text": "shap.force_plot(explainer.expected_value, shap_test.values, X_test)" }, { "code": null, "e": 8466, "s": 8196, "text": "Just like heatmap, x-axis shows each record. Positive shap values are shown in red and and negative ones are in blue. For instance, since the first record had more red contributions than blue ones, the prediction for this record would be higher than the expected value." }, { "code": null, "e": 8637, "s": 8466, "text": "The interactivity allows us to change both axes. For instance, y-axis shows predictions, f(x) and x-axis is sorted by the output (prediction) value in the snapshot above." }, { "code": null, "e": 8744, "s": 8637, "text": "Now we will look at plots for understanding predictions for individual cases. Let’s start with a bar plot:" }, { "code": null, "e": 8773, "s": 8744, "text": "shap.plots.bar(shap_test[0])" }, { "code": null, "e": 8896, "s": 8773, "text": "The syntax is exactly same as in section ‘2.1. Global | Bar plot’ except this time we sliced the data for a single record." }, { "code": null, "e": 8941, "s": 8896, "text": "This is another alternative to the bar plot:" }, { "code": null, "e": 9251, "s": 8941, "text": "class WaterfallData(): def __init__ (self, shap_test, index): self.values = shap_test[index].values self.base_values = shap_test[index].base_values[0] self.data = shap_test[index].data self.feature_names = shap_test.feature_namesshap.plots.waterfall(WaterfallData(shap_test, 0))" }, { "code": null, "e": 9882, "s": 9251, "text": "The waterfall plot is information-dense and there are four bits of information:◼️ On the y-axis, we see the actual feature value for the record. If you are not sure what I mean, compare X_test.head(1) to the values on the y-axis. ◼️ At the bottom right corner of the chart, we see E[f(X)], the expected value.◼️ At the top left corner, we see f(x), the predicted value.◼️ ️Just like the previous bar plot, horizontal bars represent the colour-coded feature contribution. Starting from the expected value at the bottom, we can see how each contribution is moving the prediction up and down to finally arrive at the predicted value." }, { "code": null, "e": 10049, "s": 9882, "text": "Last plot to familiarise is the force plot for a single record. If we rotate this plot 90 degrees and plot it for multiple records, we will see the global force plot." }, { "code": null, "e": 10080, "s": 10049, "text": "shap.plots.force(shap_test[0])" }, { "code": null, "e": 10205, "s": 10080, "text": "We can see both the base value:153.4 and the prediction: 103.48. We can also see the breakdown of the feature contributions." }, { "code": null, "e": 10411, "s": 10205, "text": "We have so far focused a regression example. In this section, we’ll learn one way to tweak what we learned to suit a binary classification. Let’s import the subset of titanic data and train a simple model:" }, { "code": null, "e": 11169, "s": 10411, "text": "# Import sample datadf = sns.load_dataset('titanic')df['is_male'] = df['sex'].map({'male': 1, 'female': 0}) # Encode# Keep numerical complete columnsdf = df.select_dtypes('number').dropna() X = df.drop(columns=['survived'])y = df['survived']# Partition dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=1)print(f\"Training features shape: {X_train.shape}\")print(f\"Training target shape: {y_train.shape}\\n\")print(f\"Test features shape: {X_test.shape}\")print(f\"Test target shape: {y_test.shape}\")display(X_train.head())# Train a simple modelmodel = RandomForestClassifier(random_state=42)model.fit(X_train, y_train)" }, { "code": null, "e": 11241, "s": 11169, "text": "We will create an explainer object and extract shap values like before:" }, { "code": null, "e": 11396, "s": 11241, "text": "explainer = shap.Explainer(model)shap_test = explainer(X_test)print(f\"Length of shap_test: {len(shap_test)}\\n\")print(f\"Sample shap_test:\\n{shap_test[0]}\")" }, { "code": null, "e": 11593, "s": 11396, "text": "Just like regression shap_test.data will contain the same number of records as the X_test. However, from this example record, we can see that the dimension of values and base_values are different." }, { "code": null, "e": 11748, "s": 11593, "text": "Let’s first look at the base value. The base value now tells us the probability for each class. We will focus on the positive class (i.e. y==1, survival):" }, { "code": null, "e": 11939, "s": 11748, "text": "print(f\"Expected value: {explainer.expected_value[1]:.2f}\")print(f\"Average target value (training data): {y_train.mean():.2f}\")print(f\"Base value: {np.unique(shap_test.base_values)[0]:.2f}\")" }, { "code": null, "e": 12147, "s": 11939, "text": "Now, let’s look at the shap values. Shap values are also provided for both classes. You will also notice that they are the negative of each other. We can extract the shap values for positive class like this:" }, { "code": null, "e": 12301, "s": 12147, "text": "shap_df = pd.DataFrame(shap_test.values[:,:,1], columns=shap_test.feature_names, index=X_test.index)shap_df" }, { "code": null, "e": 12423, "s": 12301, "text": "Let’s double check whether adding the sum of shap values to the expected probability will give the predicted probability:" }, { "code": null, "e": 12530, "s": 12423, "text": "np.isclose(model.predict_proba(X_test)[:,1], explainer.expected_value[1] + shap_df.sum(axis=1))" }, { "code": null, "e": 12607, "s": 12530, "text": "Awesome, now you know how to get the shap values in the unit of probability." }, { "code": null, "e": 12808, "s": 12607, "text": "It’s time to tweak the plots we looked at earlier. To avoid repeating, I will show an example for global plots and another for local plots since the other plots can be replicated using the same logic." }, { "code": null, "e": 12908, "s": 12808, "text": "Global | Bar plot: Let’s check out features’ overall contribution to predicting the positive class:" }, { "code": null, "e": 12941, "s": 12908, "text": "shap.plots.bar(shap_test[:,:,1])" }, { "code": null, "e": 13021, "s": 12941, "text": "Local | Waterfall plot: Let’s look at waterfall plot for the first test record:" }, { "code": null, "e": 13063, "s": 13021, "text": "shap.plots.waterfall(shap_test[:,:,1][0])" }, { "code": null, "e": 13211, "s": 13063, "text": "From this plot, we can see how each feature has contributed towards predicted probability of belonging to the positive class: 0.98 for this record." }, { "code": null, "e": 13394, "s": 13211, "text": "Before we wrap up, let’s look at an example use-case. We will find the most incorrect examples for the survivors and will try to understand why the model makes incorrect predictions:" }, { "code": null, "e": 13580, "s": 13394, "text": "test = pd.concat([X_test, y_test], axis=1)test['probability'] = model.predict_proba(X_test)[:,1]test['order'] = np.arange(len(test))test.query('survived==1').nsmallest(5, 'probability')" }, { "code": null, "e": 13710, "s": 13580, "text": "The probability of survival was 0.03 for the first record. Let’s check out how features contributed to arrive at this prediction:" }, { "code": null, "e": 13846, "s": 13710, "text": "ind1 = test.query('survived==1')\\ .nsmallest(1, 'probability')['order'].values[0]shap.plots.waterfall(shap_test[:,:,1][ind1])" }, { "code": null, "e": 14015, "s": 13846, "text": "Young third-class male passenger... We can see mostly gender, passenger class and age have pushed down the prediction. Let’s find similar examples in the training data:" }, { "code": null, "e": 14223, "s": 14015, "text": "pd.concat([X_train, y_train], axis=1)[(X_train['is_male']==1) & (X_train['pclass']==3) & (X_train['age']==22) & (X_train['fare'].between(7,8))]" }, { "code": null, "e": 14422, "s": 14223, "text": "All similar training examples actually didn’t survive. Now, that makes sense! This was a small use-case of how shap can be helpful in unravelling why the model comes up with an incorrect prediction." }, { "code": null, "e": 14805, "s": 14422, "text": "Hope you enjoyed learning how to use the SHAP library to understand both regression and classification models built in Scikit-learn. Since SHAP is model-agnostic, you can also use it for other models too. I hope you will get to use this explainable AI tool soon to understand why the model comes up with its predictions in order to improve the model and explain it to others better." }, { "code": null, "e": 15029, "s": 14805, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 15411, "s": 15029, "text": "Thank you for reading this article. If you are interested, here are links to some of my other posts:◼️️ K-Nearest Neighbours explained◼️️ Logistic regression explained◼️️ Comparing Random Forest and Gradient Boosting◼️️ How are decision trees built?◼️️ Pipeline, ColumnTransformer and FeatureUnion explained◼️️ FeatureUnion, ColumnTransformer & Pipeline for preprocessing text data" } ]
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) - GeeksforGeeks
28 Jun, 2021 To improve the performance of a CPU we have two options:1) Improve the hardware by introducing faster circuits.2) Arrange the hardware such that more than one operation can be performed at the same time. Since, there is a limit on the speed of hardware and the cost of faster circuits is quite high, we have to adopt the 2nd option. Pipelining : Pipelining is a process of arrangement of hardware elements of the CPU such that its overall performance is increased. Simultaneous execution of more than one instruction takes place in a pipelined processor. Let us see a real life example that works on the concept of pipelined operation. Consider a water bottle packaging plant. Let there be 3 stages that a bottle should pass through, Inserting the bottle(I), Filling water in the bottle(F), and Sealing the bottle(S). Let us consider these stages as stage 1, stage 2 and stage 3 respectively. Let each stage take 1 minute to complete its operation.Now, in a non pipelined operation, a bottle is first inserted in the plant, after 1 minute it is moved to stage 2 where water is filled. Now, in stage 1 nothing is happening. Similarly, when the bottle moves to stage 3, both stage 1 and stage 2 are idle. But in pipelined operation, when the bottle is in stage 2, another bottle can be loaded at stage 1. Similarly, when the bottle is in stage 3, there can be one bottle each in stage 1 and stage 2. So, after each minute, we get a new bottle at the end of stage 3. Hence, the average time taken to manufacture 1 bottle is : Without pipelining = 9/3 minutes = 3m I F S | | | | | | | | | I F S | | | | | | | | | I F S (9 minutes) With pipelining = 5/3 minutes = 1.67m I F S | | | I F S | | | I F S (5 minutes) Thus, pipelined operation increases the efficiency of a system. Design of a basic pipeline In a pipelined processor, a pipeline has two ends, the input end and the output end. Between these ends, there are multiple stages/segments such that output of one stage is connected to input of next stage and each stage performs a specific operation. Interface registers are used to hold the intermediate output between two stages. These interface registers are also called latch or buffer. All the stages in the pipeline along with the interface registers are controlled by a common clock. Execution in a pipelined processorExecution sequence of instructions in a pipelined processor can be visualized using a space-time diagram. For example, consider a processor having 4 stages and let there be 2 instructions to be executed. We can visualize the execution sequence through the following space-time diagrams: Non overlapped execution: Total time = 8 Cycle Overlapped execution: Total time = 5 Cycle Pipeline Stages RISC processor has 5 stage instruction pipeline to execute all the instructions in the RISC instruction set. Following are the 5 stages of RISC pipeline with their respective operations: Stage 1 (Instruction Fetch)In this stage the CPU reads instructions from the address in the memory whose value is present in the program counter. Stage 2 (Instruction Decode)In this stage, instruction is decoded and the register file is accessed to get the values from the registers used in the instruction. Stage 3 (Instruction Execute)In this stage, ALU operations are performed. Stage 4 (Memory Access)In this stage, memory operands are read and written from/to the memory that is present in the instruction. Stage 5 (Write Back)In this stage, computed/fetched value is written back to the register present in the instructions. Performance of a pipelined processorConsider a ‘k’ segment pipeline with clock cycle time as ‘Tp’. Let there be ‘n’ tasks to be completed in the pipelined processor. Now, the first instruction is going to take ‘k’ cycles to come out of the pipeline but the other ‘n – 1’ instructions will take only ‘1’ cycle each, i.e, a total of ‘n – 1’ cycles. So, time taken to execute ‘n’ instructions in a pipelined processor: ETpipeline = k + n – 1 cycles = (k + n – 1) Tp In the same case, for a non-pipelined processor, execution time of ‘n’ instructions will be: ETnon-pipeline = n * k * Tp So, speedup (S) of the pipelined processor over non-pipelined processor, when ‘n’ tasks are executed on the same processor is: S = Performance of pipelined processor / Performance of Non-pipelined processor As the performance of a processor is inversely proportional to the execution time, we have, S = ETnon-pipeline / ETpipeline => S = [n * k * Tp] / [(k + n – 1) * Tp] S = [n * k] / [k + n – 1] When the number of tasks ‘n’ are significantly larger than k, that is, n >> k S = n * k / n S = k where ‘k’ are the number of stages in the pipeline. Also, Efficiency = Given speed up / Max speed up = S / SmaxWe know that, Smax = k So, Efficiency = S / k Throughput = Number of instructions / Total time to complete the instructions So, Throughput = n / (k + n – 1) * Tp Note: The cycles per instruction (CPI) value of an ideal pipelined processor is 1 Please see Set 2 for Dependencies and Data Hazard and Set 3 for Types of pipeline and Stalling. Sources : goo.gl/J9KVNthttps://en.wikipedia.org/wiki/Hazard_(computer_architecture)https://en.wikipedia.org/wiki/Data_dependency This article has been contributed by Saurabh Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above anshusr94 SachinKorlaPandit Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Decimal to Binary Conversion Logical and Physical Address in Operating System Addressing modes in 8085 microprocessor Difference between Von Neumann and Harvard Architecture Interrupts Architecture of 8085 microprocessor IEEE Standard 754 Floating Point Numbers Program for Binary To Decimal Conversion Computer Organization | Booth's Algorithm Direct Access Media (DMA) Controller in Computer Architecture
[ { "code": null, "e": 27462, "s": 27434, "text": "\n28 Jun, 2021" }, { "code": null, "e": 27666, "s": 27462, "text": "To improve the performance of a CPU we have two options:1) Improve the hardware by introducing faster circuits.2) Arrange the hardware such that more than one operation can be performed at the same time." }, { "code": null, "e": 27795, "s": 27666, "text": "Since, there is a limit on the speed of hardware and the cost of faster circuits is quite high, we have to adopt the 2nd option." }, { "code": null, "e": 28017, "s": 27795, "text": "Pipelining : Pipelining is a process of arrangement of hardware elements of the CPU such that its overall performance is increased. Simultaneous execution of more than one instruction takes place in a pipelined processor." }, { "code": null, "e": 28985, "s": 28017, "text": "Let us see a real life example that works on the concept of pipelined operation. Consider a water bottle packaging plant. Let there be 3 stages that a bottle should pass through, Inserting the bottle(I), Filling water in the bottle(F), and Sealing the bottle(S). Let us consider these stages as stage 1, stage 2 and stage 3 respectively. Let each stage take 1 minute to complete its operation.Now, in a non pipelined operation, a bottle is first inserted in the plant, after 1 minute it is moved to stage 2 where water is filled. Now, in stage 1 nothing is happening. Similarly, when the bottle moves to stage 3, both stage 1 and stage 2 are idle. But in pipelined operation, when the bottle is in stage 2, another bottle can be loaded at stage 1. Similarly, when the bottle is in stage 3, there can be one bottle each in stage 1 and stage 2. So, after each minute, we get a new bottle at the end of stage 3. Hence, the average time taken to manufacture 1 bottle is :" }, { "code": null, "e": 29023, "s": 28985, "text": "Without pipelining = 9/3 minutes = 3m" }, { "code": null, "e": 29090, "s": 29023, "text": "I F S | | | | | |\n| | | I F S | | |\n| | | | | | I F S (9 minutes)\n" }, { "code": null, "e": 29128, "s": 29090, "text": "With pipelining = 5/3 minutes = 1.67m" }, { "code": null, "e": 29171, "s": 29128, "text": "I F S | |\n| I F S |\n| | I F S (5 minutes)\n" }, { "code": null, "e": 29235, "s": 29171, "text": "Thus, pipelined operation increases the efficiency of a system." }, { "code": null, "e": 29262, "s": 29235, "text": "Design of a basic pipeline" }, { "code": null, "e": 29514, "s": 29262, "text": "In a pipelined processor, a pipeline has two ends, the input end and the output end. Between these ends, there are multiple stages/segments such that output of one stage is connected to input of next stage and each stage performs a specific operation." }, { "code": null, "e": 29654, "s": 29514, "text": "Interface registers are used to hold the intermediate output between two stages. These interface registers are also called latch or buffer." }, { "code": null, "e": 29754, "s": 29654, "text": "All the stages in the pipeline along with the interface registers are controlled by a common clock." }, { "code": null, "e": 30075, "s": 29754, "text": "Execution in a pipelined processorExecution sequence of instructions in a pipelined processor can be visualized using a space-time diagram. For example, consider a processor having 4 stages and let there be 2 instructions to be executed. We can visualize the execution sequence through the following space-time diagrams:" }, { "code": null, "e": 30101, "s": 30075, "text": "Non overlapped execution:" }, { "code": null, "e": 30122, "s": 30101, "text": "Total time = 8 Cycle" }, { "code": null, "e": 30144, "s": 30122, "text": "Overlapped execution:" }, { "code": null, "e": 30165, "s": 30144, "text": "Total time = 5 Cycle" }, { "code": null, "e": 30181, "s": 30165, "text": "Pipeline Stages" }, { "code": null, "e": 30368, "s": 30181, "text": "RISC processor has 5 stage instruction pipeline to execute all the instructions in the RISC instruction set. Following are the 5 stages of RISC pipeline with their respective operations:" }, { "code": null, "e": 30514, "s": 30368, "text": "Stage 1 (Instruction Fetch)In this stage the CPU reads instructions from the address in the memory whose value is present in the program counter." }, { "code": null, "e": 30676, "s": 30514, "text": "Stage 2 (Instruction Decode)In this stage, instruction is decoded and the register file is accessed to get the values from the registers used in the instruction." }, { "code": null, "e": 30750, "s": 30676, "text": "Stage 3 (Instruction Execute)In this stage, ALU operations are performed." }, { "code": null, "e": 30880, "s": 30750, "text": "Stage 4 (Memory Access)In this stage, memory operands are read and written from/to the memory that is present in the instruction." }, { "code": null, "e": 30999, "s": 30880, "text": "Stage 5 (Write Back)In this stage, computed/fetched value is written back to the register present in the instructions." }, { "code": null, "e": 31415, "s": 30999, "text": "Performance of a pipelined processorConsider a ‘k’ segment pipeline with clock cycle time as ‘Tp’. Let there be ‘n’ tasks to be completed in the pipelined processor. Now, the first instruction is going to take ‘k’ cycles to come out of the pipeline but the other ‘n – 1’ instructions will take only ‘1’ cycle each, i.e, a total of ‘n – 1’ cycles. So, time taken to execute ‘n’ instructions in a pipelined processor:" }, { "code": null, "e": 31514, "s": 31415, "text": " ETpipeline = k + n – 1 cycles\n = (k + n – 1) Tp\n" }, { "code": null, "e": 31607, "s": 31514, "text": "In the same case, for a non-pipelined processor, execution time of ‘n’ instructions will be:" }, { "code": null, "e": 31656, "s": 31607, "text": " ETnon-pipeline = n * k * Tp\n" }, { "code": null, "e": 31783, "s": 31656, "text": "So, speedup (S) of the pipelined processor over non-pipelined processor, when ‘n’ tasks are executed on the same processor is:" }, { "code": null, "e": 31876, "s": 31783, "text": " S = Performance of pipelined processor /\n Performance of Non-pipelined processor\n" }, { "code": null, "e": 31968, "s": 31876, "text": "As the performance of a processor is inversely proportional to the execution time, we have," }, { "code": null, "e": 32083, "s": 31968, "text": " S = ETnon-pipeline / ETpipeline\n => S = [n * k * Tp] / [(k + n – 1) * Tp]\n S = [n * k] / [k + n – 1]\n" }, { "code": null, "e": 32161, "s": 32083, "text": "When the number of tasks ‘n’ are significantly larger than k, that is, n >> k" }, { "code": null, "e": 32190, "s": 32161, "text": " S = n * k / n\n S = k\n" }, { "code": null, "e": 32242, "s": 32190, "text": "where ‘k’ are the number of stages in the pipeline." }, { "code": null, "e": 32324, "s": 32242, "text": "Also, Efficiency = Given speed up / Max speed up = S / SmaxWe know that, Smax = k" }, { "code": null, "e": 32347, "s": 32324, "text": "So, Efficiency = S / k" }, { "code": null, "e": 32425, "s": 32347, "text": "Throughput = Number of instructions / Total time to complete the instructions" }, { "code": null, "e": 32463, "s": 32425, "text": "So, Throughput = n / (k + n – 1) * Tp" }, { "code": null, "e": 32545, "s": 32463, "text": "Note: The cycles per instruction (CPI) value of an ideal pipelined processor is 1" }, { "code": null, "e": 32641, "s": 32545, "text": "Please see Set 2 for Dependencies and Data Hazard and Set 3 for Types of pipeline and Stalling." }, { "code": null, "e": 32770, "s": 32641, "text": "Sources : goo.gl/J9KVNthttps://en.wikipedia.org/wiki/Hazard_(computer_architecture)https://en.wikipedia.org/wiki/Data_dependency" }, { "code": null, "e": 32823, "s": 32770, "text": "This article has been contributed by Saurabh Sharma." }, { "code": null, "e": 32947, "s": 32823, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 32957, "s": 32947, "text": "anshusr94" }, { "code": null, "e": 32975, "s": 32957, "text": "SachinKorlaPandit" }, { "code": null, "e": 33012, "s": 32975, "text": "Computer Organization & Architecture" }, { "code": null, "e": 33110, "s": 33012, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33151, "s": 33110, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 33200, "s": 33151, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 33240, "s": 33200, "text": "Addressing modes in 8085 microprocessor" }, { "code": null, "e": 33296, "s": 33240, "text": "Difference between Von Neumann and Harvard Architecture" }, { "code": null, "e": 33307, "s": 33296, "text": "Interrupts" }, { "code": null, "e": 33343, "s": 33307, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 33384, "s": 33343, "text": "IEEE Standard 754 Floating Point Numbers" }, { "code": null, "e": 33425, "s": 33384, "text": "Program for Binary To Decimal Conversion" }, { "code": null, "e": 33467, "s": 33425, "text": "Computer Organization | Booth's Algorithm" } ]
C++ STL | Set 5 (queue) | Practice | GeeksforGeeks
Implement different operations on a queue q . Input: The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries . A query can be of four types 1. a x (Pushes an element x at the end of the queue q ) 2. b (if queue is not empty pops the front element and prints it, else prints -1) 3. c (prints the size of the queue) 4. d (if queue is not empty prints the front element of the queue, else prints -1) 5. e (if queue is not empty prints the last element of the queue else prints -1) Output: The output for each test case will be space separated integers denoting the results of each query . Constraints: 1<=T<=100 1<=Q<=100 Example: Input 2 5 a 4 a 6 a 7 b c 4 a 55 a 11 d e Output 4 2 55 11 Explanation : For the first test case There are five queries. Queries are performed in this order 1. a 4 { queue q has 4 } 2. a 7 {queue q has 4,7 } 3. a 6 {queue q has 4,7,6} 4. b {pop 4 from queue q and prints it queue now has 7,6} 5. c {prints the size of the queue q ie 2} For the sec test case There are three queries. Queries are performed in this order 1. a 55 {queue q has 55 } 2. a 11 {queue q has 55 ,11 } 3. d {prints the front element of the queue q ie. 55 } 4. e {prints the end element of the queue q ie 11 } Note:The Input/Output 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. +1 aqquilin1413 months ago void push(queue<int> &q,int x){ //Your code here q.push(x); } int pop(queue<int> &q) { //Your code here if(!q.empty()){ int x = q.front(); q.pop(); return x; } return -1; } int getSize(queue<int> &q) { //Your code here return q.size(); } int getBack(queue<int> &q) { //Your code here if(!q.empty()){ return q.back();} return -1; } int getFront(queue<int> &q) { //Your code here if(!q.empty()){ return q.front();} return -1; } +1 kumarnitesh884414 months ago void push(queue<int> &q,int x){ //Your code here q.push(x);} /*pop out the front element from the queue q and returns it */int pop(queue<int> &q){ //Your code here if(q.size()>0){ int res=q.front(); q.pop(); return res; } return -1;} /*returns the size of the queue q */int getSize(queue<int> &q){ //Your code here return q.size();} /*returns the last element of the queue */int getBack(queue<int> &q){//Your code hereif(q.size()>0){ int r=q.back(); return r;}return -1;} /*returns the first element of the queue */int getFront(queue<int> &q){//Your code hereif(q.size()>0){ int s=q.front(); return s; }return -1;} -1 Siddharth Katiyar1 year ago Siddharth Katiyar void push(queue<int> &q,int x){ q.push(x); //Your code here}/*pop out the front element from the queue q and returns it */int pop(queue<int> &q){ if(!q.empty()){ int front = q.front(); q.pop(); return front; } return -1; //Your code here}/*returns the size of the queue q */int getSize(queue<int> &q){ return q.size(); //Your code here}/*returns the last element of the queue */int getBack(queue<int> &q){ if(!q.empty()){ int r = q.back(); return r; } return -1;//Your code here}/*returns the first element of the queue */int getFront(queue<int> &q){ if(!q.empty()){ int f = q.front(); return f; } return -1;//Your code here} +1 Rishabh Patel1 year ago Rishabh Patel 0 Rishabh Patel This comment was deleted. 0 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.01 void push(queue<int> &q, int x){ q.push(x);}int pop(queue<int> &q){ if(q.empty() == true) { return -1; } int val = q.front(); q.pop(); return val;}int getSize(queue<int> &q){ return q.size();}int getBack(queue<int> &q){ if(q.empty() == true) { return -1; } return q.back();}int getFront(queue<int> &q){ if(q.empty() == true) { return -1; } return q.front();} 0 Arijit Biswas2 years ago Arijit Biswas void push(queue<int> &q,int x){ q.push(x);}int pop(queue<int> &q){ if (!q.empty()) { int x= q.front(); q.pop(); return x; } else return -1;}int getSize(queue<int> &q){ return q.size();}int getBack(queue<int> &q){return q.empty() ? -1 : q.back();}int getFront(queue<int> &q){return q.empty() ? -1 : q.front();} 0 NITIN SHARMA2 years ago NITIN SHARMA https://ide.geeksforgeeks.o...Correct Answer.C++Execution Time:0.01 0 Arun Karthik2 years ago Arun Karthik Correct Answer.Correct AnswerExecution Time:0.01 https://ide.geeksforgeeks.o... void push(queue<int> &q,int x){ q.push(x);} int pop(queue<int> &q){ if(q.empty()) return -1; int x=q.front(); q.pop(); return x;} int getSize(queue<int> &q){ return q.size();} int getBack(queue<int> &q){if(q.empty()) return -1;return q.back();} int getFront(queue<int> &q){if(q.empty()) return -1;return q.front();} 0 Yash Parmar2 years ago Yash Parmar void push(queue<int> &q,int x){ //Your code here q.push(x);} /*pop out the front element from the queue q and returns it */int pop(queue<int> &q){ //Your code here if(q.empty()) return -1; int x = q.front(); q.pop(); return x;} /*returns the size of the queue q */int getSize(queue<int> &q){ //Your code here return q.size();} /*returns the last element of the queue */int getBack(queue<int> &q){//Your code hereif(q.empty())return -1;return q.back();} /*returns the first element of the queue */int getFront(queue<int> &q){//Your code hereif(q.empty())return -1;return q.front();} 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": 1048, "s": 238, "text": "Implement different operations on a queue q .\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of four types \n1. a x (Pushes an element x at the end of the queue q )\n2. b (if queue is not empty pops the front element and prints it, else prints -1)\n3. c (prints the size of the queue)\n4. d (if queue is not empty prints the front element of the queue, else prints -1)\n5. e (if queue is not empty prints the last element of the queue else prints -1)\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample:" }, { "code": null, "e": 1968, "s": 1048, "text": "Input\n2\n5\na 4 a 6 a 7 b c \n4\na 55 a 11 d e\n \nOutput\n4 2\n55 11\n\nExplanation :\nFor the first test case\nThere are five queries. Queries are performed in this order\n1. a 4 { queue q has 4 }\n2. a 7 {queue q has 4,7 }\n3. a 6 {queue q has 4,7,6}\n4. b {pop 4 from queue q and prints it queue now has 7,6}\n5. c {prints the size of the queue q ie 2}\n\nFor the sec test case \nThere are three queries. Queries are performed in this order\n1. a 55 {queue q has 55 }\n2. a 11 {queue q has 55 ,11 }\n3. d {prints the front element of the queue q ie. 55 }\n4. e {prints the end element of the queue q ie 11 }\n\n\n\nNote:The Input/Output 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": 1971, "s": 1968, "text": "+1" }, { "code": null, "e": 1995, "s": 1971, "text": "aqquilin1413 months ago" }, { "code": null, "e": 2062, "s": 1995, "text": "void push(queue<int> &q,int x){\n //Your code here\n q.push(x);\n}" }, { "code": null, "e": 2206, "s": 2062, "text": "int pop(queue<int> &q)\n{\n //Your code here\n if(!q.empty()){\n int x = q.front();\n q.pop();\n return x;\n }\n return -1;\n}" }, { "code": null, "e": 2279, "s": 2206, "text": "int getSize(queue<int> &q)\n{\n //Your code here\n return q.size();\n}" }, { "code": null, "e": 2372, "s": 2279, "text": "int getBack(queue<int> &q)\n{\n//Your code here\nif(!q.empty()){\nreturn q.back();}\nreturn -1;\n}" }, { "code": null, "e": 2469, "s": 2372, "text": "\nint getFront(queue<int> &q)\n{\n//Your code here\n if(!q.empty()){\nreturn q.front();}\nreturn -1;\n}" }, { "code": null, "e": 2474, "s": 2471, "text": "+1" }, { "code": null, "e": 2503, "s": 2474, "text": "kumarnitesh884414 months ago" }, { "code": null, "e": 2568, "s": 2503, "text": "void push(queue<int> &q,int x){ //Your code here q.push(x);}" }, { "code": null, "e": 2760, "s": 2568, "text": "/*pop out the front element from the queue q and returns it */int pop(queue<int> &q){ //Your code here if(q.size()>0){ int res=q.front(); q.pop(); return res; } return -1;}" }, { "code": null, "e": 2863, "s": 2760, "text": "/*returns the size of the queue q */int getSize(queue<int> &q){ //Your code here return q.size();}" }, { "code": null, "e": 3008, "s": 2863, "text": "/*returns the last element of the queue */int getBack(queue<int> &q){//Your code hereif(q.size()>0){ int r=q.back(); return r;}return -1;}" }, { "code": null, "e": 3160, "s": 3008, "text": "/*returns the first element of the queue */int getFront(queue<int> &q){//Your code hereif(q.size()>0){ int s=q.front(); return s; }return -1;}" }, { "code": null, "e": 3163, "s": 3160, "text": "-1" }, { "code": null, "e": 3191, "s": 3163, "text": "Siddharth Katiyar1 year ago" }, { "code": null, "e": 3209, "s": 3191, "text": "Siddharth Katiyar" }, { "code": null, "e": 3936, "s": 3209, "text": "void push(queue<int> &q,int x){ q.push(x); //Your code here}/*pop out the front element from the queue q and returns it */int pop(queue<int> &q){ if(!q.empty()){ int front = q.front(); q.pop(); return front; } return -1; //Your code here}/*returns the size of the queue q */int getSize(queue<int> &q){ return q.size(); //Your code here}/*returns the last element of the queue */int getBack(queue<int> &q){ if(!q.empty()){ int r = q.back(); return r; } return -1;//Your code here}/*returns the first element of the queue */int getFront(queue<int> &q){ if(!q.empty()){ int f = q.front(); return f; } return -1;//Your code here}" }, { "code": null, "e": 3939, "s": 3936, "text": "+1" }, { "code": null, "e": 3963, "s": 3939, "text": "Rishabh Patel1 year ago" }, { "code": null, "e": 3977, "s": 3963, "text": "Rishabh Patel" }, { "code": null, "e": 3979, "s": 3977, "text": "0" }, { "code": null, "e": 3993, "s": 3979, "text": "Rishabh Patel" }, { "code": null, "e": 4019, "s": 3993, "text": "This comment was deleted." }, { "code": null, "e": 4021, "s": 4019, "text": "0" }, { "code": null, "e": 4047, "s": 4021, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 4063, "s": 4047, "text": "Debojyoti Sinha" }, { "code": null, "e": 4112, "s": 4063, "text": "Correct Answer.Correct AnswerExecution Time:0.01" }, { "code": null, "e": 4560, "s": 4112, "text": "void push(queue<int> &q, int x){ q.push(x);}int pop(queue<int> &q){ if(q.empty() == true) { return -1; } int val = q.front(); q.pop(); return val;}int getSize(queue<int> &q){ return q.size();}int getBack(queue<int> &q){ if(q.empty() == true) { return -1; } return q.back();}int getFront(queue<int> &q){ if(q.empty() == true) { return -1; } return q.front();}" }, { "code": null, "e": 4562, "s": 4560, "text": "0" }, { "code": null, "e": 4587, "s": 4562, "text": "Arijit Biswas2 years ago" }, { "code": null, "e": 4601, "s": 4587, "text": "Arijit Biswas" }, { "code": null, "e": 4956, "s": 4601, "text": "void push(queue<int> &q,int x){ q.push(x);}int pop(queue<int> &q){ if (!q.empty()) { int x= q.front(); q.pop(); return x; } else return -1;}int getSize(queue<int> &q){ return q.size();}int getBack(queue<int> &q){return q.empty() ? -1 : q.back();}int getFront(queue<int> &q){return q.empty() ? -1 : q.front();}" }, { "code": null, "e": 4958, "s": 4956, "text": "0" }, { "code": null, "e": 4982, "s": 4958, "text": "NITIN SHARMA2 years ago" }, { "code": null, "e": 4995, "s": 4982, "text": "NITIN SHARMA" }, { "code": null, "e": 5063, "s": 4995, "text": "https://ide.geeksforgeeks.o...Correct Answer.C++Execution Time:0.01" }, { "code": null, "e": 5065, "s": 5063, "text": "0" }, { "code": null, "e": 5089, "s": 5065, "text": "Arun Karthik2 years ago" }, { "code": null, "e": 5102, "s": 5089, "text": "Arun Karthik" }, { "code": null, "e": 5151, "s": 5102, "text": "Correct Answer.Correct AnswerExecution Time:0.01" }, { "code": null, "e": 5182, "s": 5151, "text": "https://ide.geeksforgeeks.o..." }, { "code": null, "e": 5229, "s": 5182, "text": "void push(queue<int> &q,int x){ q.push(x);}" }, { "code": null, "e": 5323, "s": 5229, "text": "int pop(queue<int> &q){ if(q.empty()) return -1; int x=q.front(); q.pop(); return x;}" }, { "code": null, "e": 5371, "s": 5323, "text": "int getSize(queue<int> &q){ return q.size();}" }, { "code": null, "e": 5440, "s": 5371, "text": "int getBack(queue<int> &q){if(q.empty()) return -1;return q.back();}" }, { "code": null, "e": 5511, "s": 5440, "text": "int getFront(queue<int> &q){if(q.empty()) return -1;return q.front();}" }, { "code": null, "e": 5513, "s": 5511, "text": "0" }, { "code": null, "e": 5536, "s": 5513, "text": "Yash Parmar2 years ago" }, { "code": null, "e": 5548, "s": 5536, "text": "Yash Parmar" }, { "code": null, "e": 5615, "s": 5548, "text": "void push(queue<int> &q,int x){ //Your code here q.push(x);}" }, { "code": null, "e": 5794, "s": 5615, "text": "/*pop out the front element from the queue q and returns it */int pop(queue<int> &q){ //Your code here if(q.empty()) return -1; int x = q.front(); q.pop(); return x;}" }, { "code": null, "e": 5899, "s": 5794, "text": "/*returns the size of the queue q */int getSize(queue<int> &q){ //Your code here return q.size();}" }, { "code": null, "e": 6025, "s": 5899, "text": "/*returns the last element of the queue */int getBack(queue<int> &q){//Your code hereif(q.empty())return -1;return q.back();}" }, { "code": null, "e": 6154, "s": 6025, "text": "/*returns the first element of the queue */int getFront(queue<int> &q){//Your code hereif(q.empty())return -1;return q.front();}" }, { "code": null, "e": 6300, "s": 6154, "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": 6336, "s": 6300, "text": " Login to access your submissions. " }, { "code": null, "e": 6346, "s": 6336, "text": "\nProblem\n" }, { "code": null, "e": 6356, "s": 6346, "text": "\nContest\n" }, { "code": null, "e": 6419, "s": 6356, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6567, "s": 6419, "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": 6775, "s": 6567, "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": 6881, "s": 6775, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Bootstrap class to emphasize text
HTML's default emphasis tags such as <small> sets text at 85% the size of the parent, <strong> emphasizes a text with heavier font-weight, and <em> emphasizes a text in italics. You can try to run the following code to an emphasis on text − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap emphasis tags</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <small>This content is within tag</small><br> <strong>This content is within tag</strong><br> <em>This content is within tag and is rendered as italics</em><br> <p class = "text-left">Left aligned text.</p> <p class = "text-center">Center aligned text.</p> <p class = "text-right">Right aligned text.</p> <p class = "text-muted">This content is muted</p> <p class = "text-primary">This content carries a primary class</p> <p class = "text-danger">This content carries a danger class</p> </body> </html>
[ { "code": null, "e": 1240, "s": 1062, "text": "HTML's default emphasis tags such as <small> sets text at 85% the size of the parent, <strong> emphasizes a text with heavier font-weight, and <em> emphasizes a text in italics." }, { "code": null, "e": 1303, "s": 1240, "text": "You can try to run the following code to an emphasis on text −" }, { "code": null, "e": 1314, "s": 1303, "text": " Live Demo" }, { "code": null, "e": 2354, "s": 1314, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap emphasis tags</title>\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <small>This content is within tag</small><br>\n <strong>This content is within tag</strong><br>\n <em>This content is within tag and is rendered as italics</em><br>\n <p class = \"text-left\">Left aligned text.</p>\n <p class = \"text-center\">Center aligned text.</p>\n <p class = \"text-right\">Right aligned text.</p>\n <p class = \"text-muted\">This content is muted</p>\n <p class = \"text-primary\">This content carries a primary class</p>\n <p class = \"text-danger\">This content carries a danger class</p>\n </body>\n</html>" } ]
Algorithms for Text Classification — Part 1 | by Hailey Huong Nguyen | Towards Data Science
When you check news about Natural Language Processing (NLP) these days, you will see a lot of hype surrounding language models, transfer learning, OpenAI, ULMFit, etc. Catching up with the current state-of-art in NLP is great, though I still believe that one shall be strong in understanding the classic algorithms, such as Naive Bayes and Logistic Regression. Why? Because the company that you might work with might not be specialized in building chatbots or working on a text-generating machine! Most of the time, starting with simple models might give you great results without banging your head to the wall trying to explain your methodology to your business partners. So this blog post is the beginning of a series about text classification’s methods, starting with the basic. I will try to explain the theory as well as how to use the algorithm in practice. Why the name? “Bayes” is named from the famous Bayes’ Theorem in probability, and “Naive” is because the assumptions of this algorithm are very simple and most of the time not true. The general idea of Naive Bayes: Represent a document X as a set of (w, a frequency of w) pairs.For each label y, build a probabilistic model P(X| Y = y) of documents in class y.To classify, select label y which is most likely to generate X: Represent a document X as a set of (w, a frequency of w) pairs. For each label y, build a probabilistic model P(X| Y = y) of documents in class y. To classify, select label y which is most likely to generate X: Assumptions: The order of the words in document X makes no difference but repetitions of words do.Words appear independently of each other, given the document class. The order of the words in document X makes no difference but repetitions of words do. Words appear independently of each other, given the document class. Based on these assumptions, we have the following equations to estimate P(X|y): There are problems with these equations: For equation (1), if our document has more than 100 words, P(w1,..., w_n|Y = y) will be a product of very small word probabilities ( < 0.1), leading to the UNDERFLOW problem => Working with logarithms is desirable to maintain numerical stability. For equation (2), if we have a new word w in the new text that we need to classify, P(W = w | Y = y) = 0 as w has never appeared in our training data. => one solution is to smooth the probabilities. Assume we have m examples with P(w|y) = p. This use of m and p is a Dirichlet prior for the multinomial distribution. Please note that there are many smoothing methods. Putting all these together, we have the following algorithm: Now, let’s work on a hypothetical example to understand the algorithm: Suppose we have 3 documents: X1 = “The government shutdown” with label y1 = news X2 = “Federal employees are protesting shutdown” with label y2 = news X3 = “Turn melancholy forth to funerals” with label y3 = poetry and a new document to classify: X_new = “The shutdown affects federal employees benefit” We then can have this count table from our training data For the purpose of simplicity, I did not exclude stopwords, but in practice, you definitely should. Besides, to prevent the underflow problem, I define the smoothing parameters: p = 0.5 and m = 1. We can then calculate the score of each label for the new document X_new as following. We can see that the score for label “news” is higher than the score for label “poetry”, so we will classify X_new as “news”. Next, let’s see how to run this algorithm using Python with real data: import pandas as pdimport numpy as npspam_data = pd.read_csv('spam.csv')spam_data['target'] = np.where(spam_data['target']=='spam',1,0)print(spam_data.shape)spam_data.head(10) from sklearn.model_selection import train_test_split#Split data into train and test setsX_train, X_test, y_train, y_test = train_test_split(spam_data['text'],spam_data['target'],random_state=0)from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import roc_auc_score#Train and evaluate the modelvect = CountVectorizer().fit(X_train)X_train_vectorized = vect.transform(X_train)clfrNB = MultinomialNB(alpha = 0.1)clfrNB.fit(X_train_vectorized, y_train)preds = clfrNB.predict(vect.transform(X_test))score = roc_auc_score(y_test, preds)print(score)#0.9720812182741116 Our AUC score is 0.97, which is not bad for a simple model like this. We will compare this performance with other algorithms’ performance using the same dataset in later blog posts.
[ { "code": null, "e": 1035, "s": 171, "text": "When you check news about Natural Language Processing (NLP) these days, you will see a lot of hype surrounding language models, transfer learning, OpenAI, ULMFit, etc. Catching up with the current state-of-art in NLP is great, though I still believe that one shall be strong in understanding the classic algorithms, such as Naive Bayes and Logistic Regression. Why? Because the company that you might work with might not be specialized in building chatbots or working on a text-generating machine! Most of the time, starting with simple models might give you great results without banging your head to the wall trying to explain your methodology to your business partners. So this blog post is the beginning of a series about text classification’s methods, starting with the basic. I will try to explain the theory as well as how to use the algorithm in practice." }, { "code": null, "e": 1217, "s": 1035, "text": "Why the name? “Bayes” is named from the famous Bayes’ Theorem in probability, and “Naive” is because the assumptions of this algorithm are very simple and most of the time not true." }, { "code": null, "e": 1250, "s": 1217, "text": "The general idea of Naive Bayes:" }, { "code": null, "e": 1459, "s": 1250, "text": "Represent a document X as a set of (w, a frequency of w) pairs.For each label y, build a probabilistic model P(X| Y = y) of documents in class y.To classify, select label y which is most likely to generate X:" }, { "code": null, "e": 1523, "s": 1459, "text": "Represent a document X as a set of (w, a frequency of w) pairs." }, { "code": null, "e": 1606, "s": 1523, "text": "For each label y, build a probabilistic model P(X| Y = y) of documents in class y." }, { "code": null, "e": 1670, "s": 1606, "text": "To classify, select label y which is most likely to generate X:" }, { "code": null, "e": 1683, "s": 1670, "text": "Assumptions:" }, { "code": null, "e": 1836, "s": 1683, "text": "The order of the words in document X makes no difference but repetitions of words do.Words appear independently of each other, given the document class." }, { "code": null, "e": 1922, "s": 1836, "text": "The order of the words in document X makes no difference but repetitions of words do." }, { "code": null, "e": 1990, "s": 1922, "text": "Words appear independently of each other, given the document class." }, { "code": null, "e": 2070, "s": 1990, "text": "Based on these assumptions, we have the following equations to estimate P(X|y):" }, { "code": null, "e": 2111, "s": 2070, "text": "There are problems with these equations:" }, { "code": null, "e": 2358, "s": 2111, "text": "For equation (1), if our document has more than 100 words, P(w1,..., w_n|Y = y) will be a product of very small word probabilities ( < 0.1), leading to the UNDERFLOW problem => Working with logarithms is desirable to maintain numerical stability." }, { "code": null, "e": 2726, "s": 2358, "text": "For equation (2), if we have a new word w in the new text that we need to classify, P(W = w | Y = y) = 0 as w has never appeared in our training data. => one solution is to smooth the probabilities. Assume we have m examples with P(w|y) = p. This use of m and p is a Dirichlet prior for the multinomial distribution. Please note that there are many smoothing methods." }, { "code": null, "e": 2787, "s": 2726, "text": "Putting all these together, we have the following algorithm:" }, { "code": null, "e": 2858, "s": 2787, "text": "Now, let’s work on a hypothetical example to understand the algorithm:" }, { "code": null, "e": 2887, "s": 2858, "text": "Suppose we have 3 documents:" }, { "code": null, "e": 2939, "s": 2887, "text": "X1 = “The government shutdown” with label y1 = news" }, { "code": null, "e": 3009, "s": 2939, "text": "X2 = “Federal employees are protesting shutdown” with label y2 = news" }, { "code": null, "e": 3073, "s": 3009, "text": "X3 = “Turn melancholy forth to funerals” with label y3 = poetry" }, { "code": null, "e": 3105, "s": 3073, "text": "and a new document to classify:" }, { "code": null, "e": 3162, "s": 3105, "text": "X_new = “The shutdown affects federal employees benefit”" }, { "code": null, "e": 3219, "s": 3162, "text": "We then can have this count table from our training data" }, { "code": null, "e": 3503, "s": 3219, "text": "For the purpose of simplicity, I did not exclude stopwords, but in practice, you definitely should. Besides, to prevent the underflow problem, I define the smoothing parameters: p = 0.5 and m = 1. We can then calculate the score of each label for the new document X_new as following." }, { "code": null, "e": 3628, "s": 3503, "text": "We can see that the score for label “news” is higher than the score for label “poetry”, so we will classify X_new as “news”." }, { "code": null, "e": 3699, "s": 3628, "text": "Next, let’s see how to run this algorithm using Python with real data:" }, { "code": null, "e": 3875, "s": 3699, "text": "import pandas as pdimport numpy as npspam_data = pd.read_csv('spam.csv')spam_data['target'] = np.where(spam_data['target']=='spam',1,0)print(spam_data.shape)spam_data.head(10)" }, { "code": null, "e": 4511, "s": 3875, "text": "from sklearn.model_selection import train_test_split#Split data into train and test setsX_train, X_test, y_train, y_test = train_test_split(spam_data['text'],spam_data['target'],random_state=0)from sklearn.feature_extraction.text import CountVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.metrics import roc_auc_score#Train and evaluate the modelvect = CountVectorizer().fit(X_train)X_train_vectorized = vect.transform(X_train)clfrNB = MultinomialNB(alpha = 0.1)clfrNB.fit(X_train_vectorized, y_train)preds = clfrNB.predict(vect.transform(X_test))score = roc_auc_score(y_test, preds)print(score)#0.9720812182741116" } ]
Maximum possible number with the given operation - GeeksforGeeks
19 Mar, 2022 Given a positive integer N, the task is to convert this integer to the maximum possible integer without leading zeroes by changing the digits. A digit X can only be changed into a digit Y if X + Y = 9.Examples: Input: N = 42 Output: 57 Change 4 -> 5 and 2 -> 7.Input: N = 1 Output: 8 Approach: Only the digits which are greater than or equal to 5 need to be changed as changing the digits which are less than 5 will result in a larger number. After all the required digits have been updated, check whether the resultant number has a leading zero, if yes then change it to a 9.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 the maximum possible// integer that can be obtained from the// given integer after performing// the given operationsstring maxInt(string str){ // For every digit for (int i = 0; i < str.length(); i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { str[i] = ('9' - str[i]) + '0'; } } // The resulting integer // cannot have leading zero if (str[0] == '0') str[0] = '9'; return str;} // Driver codeint main(){ string str = "42"; cout << maxInt(str); return 0;} // Java implementation of the approachclass GFG{ // Function to return the maximum possible // integer that can be obtained from the // given integer after performing // the given operations static String maxInt(char str[]) { // For every digit for (int i = 0; i < str.length; i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { str[i] = (char)(('9' - str[i]) + '0'); } } // The resulting integer // cannot have leading zero if (str[0] == '0') str[0] = '9'; String str2 = new String(str); return str2; } // Driver code public static void main (String[] args) { String str = "42"; System.out.println(maxInt(str.toCharArray())); }} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to return the maximum possible# integer that can be obtained from the# given integer after performing# the given operationsdef maxInt(string): string2 = "" # For every digit for i in range(0, len(string)): # Digits greater than or equal to 5 # need not to be changed as changing # them will lead to a smaller number if (string[i] < '5'): string2 += str((ord('9') - ord(string[i]))) else: string2 += str(string[i]) # The resulting integer # cannot have leading zero if (string2[0] == '0'): string2[0] = '9' return string2 # Driver codeif __name__ == '__main__': string = "42" print(maxInt(string)) # This code is contributed by ashutosh450 // C# implementation of the approachusing System; class GFG{ // Function to return the maximum possible // integer that can be obtained from the // given integer after performing // the given operations static String maxInt(char []str) { // For every digit for (int i = 0; i < str.Length; i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { str[i] = (char)(('9' - str[i]) + '0'); } } // The resulting integer // cannot have leading zero if (str[0] == '0') str[0] = '9'; String str2 = new String(str); return str2; } // Driver code public static void Main (String []args) { String str = "42"; Console.WriteLine(maxInt(str.ToCharArray())); }} // This code is contributed by Arnab Kundu <script>// Javascript implementation of the// above approach // Function to return the maximum possible// integer that can be obtained from the// given integer after performing// the given operationsfunction maxInt(str){ // For every digit var str2 = ""; for (var i = 0; i < str.length; i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { var l = ('9'.charCodeAt(0) - str[i].charCodeAt(0)) + '0'.charCodeAt(0); str2 = str2.concat(String.fromCharCode(l)); } } // The resulting integer // cannot have leading zero if (str2[0] == '0') str2[0] = '9'; return str2;} // Driver codevar str = "42";document.write(maxInt(str)) // This code is contributed by ShubhamSingh10</script> 57 Time Complexity: O(|str|) Auxiliary Space: O(1) ashutosh450 ankthon andrew1234 SHUBHAMSINGH10 sweetyty subham348 Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to find GCD or HCF of two numbers Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Prime Numbers Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Sieve of Eratosthenes Program for Decimal to Binary Conversion Euclidean algorithms (Basic and Extended)
[ { "code": null, "e": 24994, "s": 24966, "text": "\n19 Mar, 2022" }, { "code": null, "e": 25207, "s": 24994, "text": "Given a positive integer N, the task is to convert this integer to the maximum possible integer without leading zeroes by changing the digits. A digit X can only be changed into a digit Y if X + Y = 9.Examples: " }, { "code": null, "e": 25282, "s": 25207, "text": "Input: N = 42 Output: 57 Change 4 -> 5 and 2 -> 7.Input: N = 1 Output: 8 " }, { "code": null, "e": 25629, "s": 25284, "text": "Approach: Only the digits which are greater than or equal to 5 need to be changed as changing the digits which are less than 5 will result in a larger number. After all the required digits have been updated, check whether the resultant number has a leading zero, if yes then change it to a 9.Below is the implementation of the above approach: " }, { "code": null, "e": 25633, "s": 25629, "text": "C++" }, { "code": null, "e": 25638, "s": 25633, "text": "Java" }, { "code": null, "e": 25646, "s": 25638, "text": "Python3" }, { "code": null, "e": 25649, "s": 25646, "text": "C#" }, { "code": null, "e": 25660, "s": 25649, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the maximum possible// integer that can be obtained from the// given integer after performing// the given operationsstring maxInt(string str){ // For every digit for (int i = 0; i < str.length(); i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { str[i] = ('9' - str[i]) + '0'; } } // The resulting integer // cannot have leading zero if (str[0] == '0') str[0] = '9'; return str;} // Driver codeint main(){ string str = \"42\"; cout << maxInt(str); return 0;}", "e": 26399, "s": 25660, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to return the maximum possible // integer that can be obtained from the // given integer after performing // the given operations static String maxInt(char str[]) { // For every digit for (int i = 0; i < str.length; i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { str[i] = (char)(('9' - str[i]) + '0'); } } // The resulting integer // cannot have leading zero if (str[0] == '0') str[0] = '9'; String str2 = new String(str); return str2; } // Driver code public static void main (String[] args) { String str = \"42\"; System.out.println(maxInt(str.toCharArray())); }} // This code is contributed by AnkitRai01", "e": 27387, "s": 26399, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum possible# integer that can be obtained from the# given integer after performing# the given operationsdef maxInt(string): string2 = \"\" # For every digit for i in range(0, len(string)): # Digits greater than or equal to 5 # need not to be changed as changing # them will lead to a smaller number if (string[i] < '5'): string2 += str((ord('9') - ord(string[i]))) else: string2 += str(string[i]) # The resulting integer # cannot have leading zero if (string2[0] == '0'): string2[0] = '9' return string2 # Driver codeif __name__ == '__main__': string = \"42\" print(maxInt(string)) # This code is contributed by ashutosh450", "e": 28190, "s": 27387, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to return the maximum possible // integer that can be obtained from the // given integer after performing // the given operations static String maxInt(char []str) { // For every digit for (int i = 0; i < str.Length; i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { str[i] = (char)(('9' - str[i]) + '0'); } } // The resulting integer // cannot have leading zero if (str[0] == '0') str[0] = '9'; String str2 = new String(str); return str2; } // Driver code public static void Main (String []args) { String str = \"42\"; Console.WriteLine(maxInt(str.ToCharArray())); }} // This code is contributed by Arnab Kundu", "e": 29190, "s": 28190, "text": null }, { "code": "<script>// Javascript implementation of the// above approach // Function to return the maximum possible// integer that can be obtained from the// given integer after performing// the given operationsfunction maxInt(str){ // For every digit var str2 = \"\"; for (var i = 0; i < str.length; i++) { // Digits greater than or equal to 5 // need not to be changed as changing // them will lead to a smaller number if (str[i] < '5') { var l = ('9'.charCodeAt(0) - str[i].charCodeAt(0)) + '0'.charCodeAt(0); str2 = str2.concat(String.fromCharCode(l)); } } // The resulting integer // cannot have leading zero if (str2[0] == '0') str2[0] = '9'; return str2;} // Driver codevar str = \"42\";document.write(maxInt(str)) // This code is contributed by ShubhamSingh10</script>", "e": 30048, "s": 29190, "text": null }, { "code": null, "e": 30051, "s": 30048, "text": "57" }, { "code": null, "e": 30079, "s": 30053, "text": "Time Complexity: O(|str|)" }, { "code": null, "e": 30101, "s": 30079, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30113, "s": 30101, "text": "ashutosh450" }, { "code": null, "e": 30121, "s": 30113, "text": "ankthon" }, { "code": null, "e": 30132, "s": 30121, "text": "andrew1234" }, { "code": null, "e": 30147, "s": 30132, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 30156, "s": 30147, "text": "sweetyty" }, { "code": null, "e": 30166, "s": 30156, "text": "subham348" }, { "code": null, "e": 30179, "s": 30166, "text": "Mathematical" }, { "code": null, "e": 30192, "s": 30179, "text": "Mathematical" }, { "code": null, "e": 30290, "s": 30192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30332, "s": 30290, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 30375, "s": 30332, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 30399, "s": 30375, "text": "Merge two sorted arrays" }, { "code": null, "e": 30413, "s": 30399, "text": "Prime Numbers" }, { "code": null, "e": 30462, "s": 30413, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30496, "s": 30462, "text": "Program for factorial of a number" }, { "code": null, "e": 30517, "s": 30496, "text": "Operators in C / C++" }, { "code": null, "e": 30539, "s": 30517, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 30580, "s": 30539, "text": "Program for Decimal to Binary Conversion" } ]
Base64 Encoding and Decoding
Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (PEM) and is primarily used in email encryption process. Python includes a module called BASE64 which includes two primary functions as given below − base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object. base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object. Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object. Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object. You can use the following piece of code to perform base64 encoding − import base64 encoded_data = base64.b64encode("Encode this text") print("Encoded text with base 64 is") print(encoded_data) The code for base64 encoding gives you the following output − You can use the following piece of code to perform base64 decoding − import base64 decoded_data = base64.b64decode("RW5jb2RlIHRoaXMgdGV4dA==") print("decoded text is ") print(decoded_data) The code for base64 decoding gives you the following output − You can observe the following differences when you work on ASCII and base64 for encoding data − When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes. When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes. When you encode data in Base64, you start with a sequence of bytes and convert it to a text string. When you encode data in Base64, you start with a sequence of bytes and convert it to a text string. Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2549, "s": 2292, "text": "Base64 encoding converts the binary data into text format, which is passed through communication channel where a user can handle text safely. Base64 is also called as Privacy enhanced Electronic mail (PEM) and is primarily used in email encryption process." }, { "code": null, "e": 2642, "s": 2549, "text": "Python includes a module called BASE64 which includes two primary functions as given below −" }, { "code": null, "e": 2764, "s": 2642, "text": "base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object." }, { "code": null, "e": 2886, "s": 2764, "text": "base64.decode(input, output) − It decodes the input value parameter specified and stores the decoded output as an object." }, { "code": null, "e": 3008, "s": 2886, "text": "Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object." }, { "code": null, "e": 3130, "s": 3008, "text": "Base64.encode(input, output) − It encodes the input value parameter specified and stores the decoded output as an object." }, { "code": null, "e": 3199, "s": 3130, "text": "You can use the following piece of code to perform base64 encoding −" }, { "code": null, "e": 3324, "s": 3199, "text": "import base64\nencoded_data = base64.b64encode(\"Encode this text\")\n\nprint(\"Encoded text with base 64 is\")\nprint(encoded_data)" }, { "code": null, "e": 3386, "s": 3324, "text": "The code for base64 encoding gives you the following output −" }, { "code": null, "e": 3455, "s": 3386, "text": "You can use the following piece of code to perform base64 decoding −" }, { "code": null, "e": 3576, "s": 3455, "text": "import base64\ndecoded_data = base64.b64decode(\"RW5jb2RlIHRoaXMgdGV4dA==\")\n\nprint(\"decoded text is \")\nprint(decoded_data)" }, { "code": null, "e": 3638, "s": 3576, "text": "The code for base64 decoding gives you the following output −" }, { "code": null, "e": 3734, "s": 3638, "text": "You can observe the following differences when you work on ASCII and base64 for encoding data −" }, { "code": null, "e": 3833, "s": 3734, "text": "When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes." }, { "code": null, "e": 3932, "s": 3833, "text": "When you encode text in ASCII, you start with a text string and convert it to a sequence of bytes." }, { "code": null, "e": 4032, "s": 3932, "text": "When you encode data in Base64, you start with a sequence of bytes and convert it to a text string." }, { "code": null, "e": 4132, "s": 4032, "text": "When you encode data in Base64, you start with a sequence of bytes and convert it to a text string." }, { "code": null, "e": 4334, "s": 4132, "text": "Base64 algorithm is usually used to store passwords in database. The major drawback is that each decoded word can be encoded easily through any online tool and intruders can easily get the information." }, { "code": null, "e": 4367, "s": 4334, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4383, "s": 4367, "text": " Total Seminars" }, { "code": null, "e": 4416, "s": 4383, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4439, "s": 4416, "text": " Stone River ELearning" }, { "code": null, "e": 4446, "s": 4439, "text": " Print" }, { "code": null, "e": 4457, "s": 4446, "text": " Add Notes" } ]
End-to-End Data Science Example: Predicting Diabetes with Logistic Regression | by Keshav Dhandhania | Towards Data Science
As the title suggests, this tutorial is an end-to-end example of solving a real-world problem using Data Science. We’ll be using Machine Learning to predict whether a person has diabetes or not, based on information about the patient such as blood pressure, body mass index (BMI), age, etc. The tutorial walks through the various stages of the data science workflow. In particular, the tutorial has the following sections Overview Data Description Data Exploration Data Preparation Training and Evaluating the Machine Learning Model Interpreting the ML Model Saving the Model Making Predictions with the Model Next Steps The data was collected and made available by “National Institute of Diabetes and Digestive and Kidney Diseases” as part of the Pima Indians Diabetes Database. Several constraints were placed on the selection of these instances from a larger database. In particular, all patients here belong to the Pima Indian heritage (subgroup of Native Americans), and are females of ages 21 and above. We’ll be using Python and some of its popular data science related packages. First of all, we will import pandas to read our data from a CSV file and manipulate it for further use. We will also use numpy to convert out data into a format suitable to feed our classification model. We’ll use seaborn and matplotlib for visualizations. We will then import Logistic Regression algorithm from sklearn. This algorithm will help us build our classification model. Lastly, we will use joblib available in sklearn to save our model for future use. import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt% matplotlib inlinefrom sklearn.linear_model import LogisticRegressionfrom sklearn.externals import joblib We have our data saved in a CSV file called diabetes.csv. We first read our dataset into a pandas dataframe called diabetesDF, and then use the head() function to show the first five records from our dataset. diabetesDF = pd.read_csv('diabetes.csv')print(diabetesDF.head()) The following features have been provided to help us predict whether a person is diabetic or not: Pregnancies: Number of times pregnant Glucose: Plasma glucose concentration over 2 hours in an oral glucose tolerance test BloodPressure: Diastolic blood pressure (mm Hg) SkinThickness: Triceps skin fold thickness (mm) Insulin: 2-Hour serum insulin (mu U/ml) BMI: Body mass index (weight in kg/(height in m)2) DiabetesPedigreeFunction: Diabetes pedigree function (a function which scores likelihood of diabetes based on family history) Age: Age (years) Outcome: Class variable (0 if non-diabetic, 1 if diabetic) Let’s also make sure that our data is clean (has no null values, etc). diabetesDF.info() # output shown below<class 'pandas.core.frame.DataFrame'>RangeIndex: 768 entries, 0 to 767Data columns (total 9 columns):Pregnancies 768 non-null int64Glucose 768 non-null int64BloodPressure 768 non-null int64SkinThickness 768 non-null int64Insulin 768 non-null int64BMI 768 non-null float64DiabetesPedigreeFunction 768 non-null float64Age 768 non-null int64Outcome 768 non-null int64dtypes: float64(2), int64(7)memory usage: 54.1 KB Note that the data does have some missing values (see Insulin = 0) in the samples in the previous figure. Ideally we could replace these 0 values with the mean value for that feature, but we’ll skip that for now. Let us now explore our data set to get a feel of what it looks like and get some insights about it. Let’s start by finding correlation of every pair of features (and the outcome variable), and visualize the correlations using a heatmap. corr = diabetesDF.corr()print(corr)sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns) In the above heatmap, brighter colors indicate more correlation. As we can see from the table and the heatmap, glucose levels, age, BMI and number of pregnancies all have significant correlation with the outcome variable. Also notice the correlation between pairs of features, like age and pregnancies, or insulin and skin thickness. Let’s also look at how many people in the dataset are diabetic and how many are not. Below is the barplot of the same: It is also helpful to visualize relations between a single variable and the outcome. Below, we’ll see the relation between age and outcome. You can similarly visualize other feature. The figure is a plot of the mean age for each of the output classes. We can see that the mean age of people having diabetes is higher. By the way — as a quick aside — this tutorial is taken from the Data Science Course on Commonlounge. The course includes many hands-on assignments and projects. In addition, 80% of the course contents are available for free! If you’re interested in learning Data Science, definitely recommend checking it out. When using machine learning algorithms we should always split our data into a training set and test set. (If the number of experiments we are running is large, then we can should be dividing our data into 3 parts, namely — training set, development set and test set). In our case, we will also separate out some data for manual cross checking. The data set consists of record of 767 patients in total. To train our model we will be using 650 records. We will be using 100 records for testing, and the last 17 records to cross check our model. dfTrain = diabetesDF[:650]dfTest = diabetesDF[650:750]dfCheck = diabetesDF[750:] Next, we separate the label and features (for both training and test dataset). In addition to that, we will also convert them into NumPy arrays as our machine learning algorithm process data in NumPy array format. trainLabel = np.asarray(dfTrain['Outcome'])trainData = np.asarray(dfTrain.drop('Outcome',1))testLabel = np.asarray(dfTest['Outcome'])testData = np.asarray(dfTest.drop('Outcome',1)) As the final step before using machine learning, we will normalize our inputs. Machine Learning models often benefit substantially from input normalization. It also makes it easier for us to understand the importance of each feature later, when we’ll be looking at the model weights. We’ll normalize the data such that each variable has 0 mean and standard deviation of 1. means = np.mean(trainData, axis=0)stds = np.std(trainData, axis=0)trainData = (trainData - means)/stdstestData = (testData - means)/stds# np.mean(trainData, axis=0) => check that new means equal 0# np.std(trainData, axis=0) => check that new stds equal 1 We can now train our classification model. We’ll be using a machine simple learning model called logistic regression. Since the model is readily available in sklearn, the training process is quite easy and we can do it in few lines of code. First, we create an instance called diabetesCheck and then use the fit function to train the model. diabetesCheck = LogisticRegression()diabetesCheck.fit(trainData, trainLabel) Next, we will use our test data to find out accuracy of the model. accuracy = diabetesCheck.score(testData, testLabel)print("accuracy = ", accuracy * 100, "%") The print statement will print accuracy = 78.0 %. To get a better sense of what is going on inside the logistic regression model, we can visualize how our model uses the different features and which features have greater effect. coeff = list(diabetesCheck.coef_[0])labels = list(trainData.columns)features = pd.DataFrame()features['Features'] = labelsfeatures['importance'] = coefffeatures.sort_values(by=['importance'], ascending=True, inplace=True)features['positive'] = features['importance'] > 0features.set_index('Features', inplace=True)features.importance.plot(kind='barh', figsize=(11, 6),color = features.positive.map({True: 'blue', False: 'red'}))plt.xlabel('Importance') From the above figure, we can draw the following conclusions. Glucose level, BMI, pregnancies and diabetes pedigree function have significant influence on the model, specially glucose level and BMI. It is good to see our machine learning model match what we have been hearing from doctors our entire lives!Blood pressure has a negative influence on the prediction, i.e. higher blood pressure is correlated with a person not being diabetic. (also, note that blood pressure is more important as a feature than age, because the magnitude is higher for blood pressure).Although age was more correlated than BMI to the output variables (as we saw during data exploration), the model relies more on BMI. This can happen for several reasons, including the fact that the correlation captured by age is also captured by some other variable, whereas the information captured by BMI is not captured by other variables. Glucose level, BMI, pregnancies and diabetes pedigree function have significant influence on the model, specially glucose level and BMI. It is good to see our machine learning model match what we have been hearing from doctors our entire lives! Blood pressure has a negative influence on the prediction, i.e. higher blood pressure is correlated with a person not being diabetic. (also, note that blood pressure is more important as a feature than age, because the magnitude is higher for blood pressure). Although age was more correlated than BMI to the output variables (as we saw during data exploration), the model relies more on BMI. This can happen for several reasons, including the fact that the correlation captured by age is also captured by some other variable, whereas the information captured by BMI is not captured by other variables. Note that this above interpretations require that our input data is normalized. Without that, we can’t claim that importance is proportional to weights. Now we will save our trained model for future use using joblib. joblib.dump([diabetesCheck, means, stds], 'diabeteseModel.pkl') To check whether we have saved the model properly or not, we will use our test data to check the accuracy of our saved model (we should observe no change in accuracy if we have saved it properly). diabetesLoadedModel, means, stds = joblib.load('diabeteseModel.pkl')accuracyModel = diabetesLoadedModel.score(testData, testLabel)print("accuracy = ",accuracyModel * 100,"%") We will now use our unused data to see how predictions can be made. We have our unused data in dfCheck. print(dfCheck.head()) We will now use the first record to make our prediction. sampleData = dfCheck[:1]# prepare samplesampleDataFeatures = np.asarray(sampleData.drop('Outcome',1))sampleDataFeatures = (sampleDataFeatures - means)/stds# predictpredictionProbability = diabetesLoadedModel.predict_proba(sampleDataFeatures)prediction = diabetesLoadedModel.predict(sampleDataFeatures)print('Probability:', predictionProbability)print('prediction:', prediction) From above code we get: Probability: [[ 0.4385153, 0.5614847]]prediction: [1] The first element of array predictionProbability 0.438 is the probability of the class being 0 and second element 0.561 is the probability of the class being 1. The probabilities sum to 1. As we can see that the 1 is more probable class, we get [1] as our prediction, which means that the model predicts that the person has diabetes. There are lots of ways to improve the above model. Here are some ideas. Input feature bucketing should help, i.e. create new variables for blood pressure in a particular range, glucose levels in a particular range, and so on.You could also improve the data cleaning, by replacing 0 values with the mean value.Read a bit about what metrics do doctors rely on the most to diagnose a diabetic patient, and create new features accordingly. Input feature bucketing should help, i.e. create new variables for blood pressure in a particular range, glucose levels in a particular range, and so on. You could also improve the data cleaning, by replacing 0 values with the mean value. Read a bit about what metrics do doctors rely on the most to diagnose a diabetic patient, and create new features accordingly. See if you can get to 85–90% accuracy. You can get started with the jupyter notebook for this tutorial: pima_indians.ipynb. Co-authored by Keshav Dhandhania and Bishal Lakha. Originally published as a tutorial on www.commonlounge.com as part of the Data Science Course.
[ { "code": null, "e": 594, "s": 172, "text": "As the title suggests, this tutorial is an end-to-end example of solving a real-world problem using Data Science. We’ll be using Machine Learning to predict whether a person has diabetes or not, based on information about the patient such as blood pressure, body mass index (BMI), age, etc. The tutorial walks through the various stages of the data science workflow. In particular, the tutorial has the following sections" }, { "code": null, "e": 603, "s": 594, "text": "Overview" }, { "code": null, "e": 620, "s": 603, "text": "Data Description" }, { "code": null, "e": 637, "s": 620, "text": "Data Exploration" }, { "code": null, "e": 654, "s": 637, "text": "Data Preparation" }, { "code": null, "e": 705, "s": 654, "text": "Training and Evaluating the Machine Learning Model" }, { "code": null, "e": 731, "s": 705, "text": "Interpreting the ML Model" }, { "code": null, "e": 748, "s": 731, "text": "Saving the Model" }, { "code": null, "e": 782, "s": 748, "text": "Making Predictions with the Model" }, { "code": null, "e": 793, "s": 782, "text": "Next Steps" }, { "code": null, "e": 1182, "s": 793, "text": "The data was collected and made available by “National Institute of Diabetes and Digestive and Kidney Diseases” as part of the Pima Indians Diabetes Database. Several constraints were placed on the selection of these instances from a larger database. In particular, all patients here belong to the Pima Indian heritage (subgroup of Native Americans), and are females of ages 21 and above." }, { "code": null, "e": 1722, "s": 1182, "text": "We’ll be using Python and some of its popular data science related packages. First of all, we will import pandas to read our data from a CSV file and manipulate it for further use. We will also use numpy to convert out data into a format suitable to feed our classification model. We’ll use seaborn and matplotlib for visualizations. We will then import Logistic Regression algorithm from sklearn. This algorithm will help us build our classification model. Lastly, we will use joblib available in sklearn to save our model for future use." }, { "code": null, "e": 1918, "s": 1722, "text": "import pandas as pdimport numpy as npimport seaborn as snsimport matplotlib.pyplot as plt% matplotlib inlinefrom sklearn.linear_model import LogisticRegressionfrom sklearn.externals import joblib" }, { "code": null, "e": 2127, "s": 1918, "text": "We have our data saved in a CSV file called diabetes.csv. We first read our dataset into a pandas dataframe called diabetesDF, and then use the head() function to show the first five records from our dataset." }, { "code": null, "e": 2192, "s": 2127, "text": "diabetesDF = pd.read_csv('diabetes.csv')print(diabetesDF.head())" }, { "code": null, "e": 2290, "s": 2192, "text": "The following features have been provided to help us predict whether a person is diabetic or not:" }, { "code": null, "e": 2328, "s": 2290, "text": "Pregnancies: Number of times pregnant" }, { "code": null, "e": 2413, "s": 2328, "text": "Glucose: Plasma glucose concentration over 2 hours in an oral glucose tolerance test" }, { "code": null, "e": 2461, "s": 2413, "text": "BloodPressure: Diastolic blood pressure (mm Hg)" }, { "code": null, "e": 2509, "s": 2461, "text": "SkinThickness: Triceps skin fold thickness (mm)" }, { "code": null, "e": 2549, "s": 2509, "text": "Insulin: 2-Hour serum insulin (mu U/ml)" }, { "code": null, "e": 2600, "s": 2549, "text": "BMI: Body mass index (weight in kg/(height in m)2)" }, { "code": null, "e": 2726, "s": 2600, "text": "DiabetesPedigreeFunction: Diabetes pedigree function (a function which scores likelihood of diabetes based on family history)" }, { "code": null, "e": 2743, "s": 2726, "text": "Age: Age (years)" }, { "code": null, "e": 2802, "s": 2743, "text": "Outcome: Class variable (0 if non-diabetic, 1 if diabetic)" }, { "code": null, "e": 2873, "s": 2802, "text": "Let’s also make sure that our data is clean (has no null values, etc)." }, { "code": null, "e": 3480, "s": 2873, "text": "diabetesDF.info() # output shown below<class 'pandas.core.frame.DataFrame'>RangeIndex: 768 entries, 0 to 767Data columns (total 9 columns):Pregnancies 768 non-null int64Glucose 768 non-null int64BloodPressure 768 non-null int64SkinThickness 768 non-null int64Insulin 768 non-null int64BMI 768 non-null float64DiabetesPedigreeFunction 768 non-null float64Age 768 non-null int64Outcome 768 non-null int64dtypes: float64(2), int64(7)memory usage: 54.1 KB" }, { "code": null, "e": 3693, "s": 3480, "text": "Note that the data does have some missing values (see Insulin = 0) in the samples in the previous figure. Ideally we could replace these 0 values with the mean value for that feature, but we’ll skip that for now." }, { "code": null, "e": 3793, "s": 3693, "text": "Let us now explore our data set to get a feel of what it looks like and get some insights about it." }, { "code": null, "e": 3930, "s": 3793, "text": "Let’s start by finding correlation of every pair of features (and the outcome variable), and visualize the correlations using a heatmap." }, { "code": null, "e": 4053, "s": 3930, "text": "corr = diabetesDF.corr()print(corr)sns.heatmap(corr, xticklabels=corr.columns, yticklabels=corr.columns)" }, { "code": null, "e": 4387, "s": 4053, "text": "In the above heatmap, brighter colors indicate more correlation. As we can see from the table and the heatmap, glucose levels, age, BMI and number of pregnancies all have significant correlation with the outcome variable. Also notice the correlation between pairs of features, like age and pregnancies, or insulin and skin thickness." }, { "code": null, "e": 4506, "s": 4387, "text": "Let’s also look at how many people in the dataset are diabetic and how many are not. Below is the barplot of the same:" }, { "code": null, "e": 4824, "s": 4506, "text": "It is also helpful to visualize relations between a single variable and the outcome. Below, we’ll see the relation between age and outcome. You can similarly visualize other feature. The figure is a plot of the mean age for each of the output classes. We can see that the mean age of people having diabetes is higher." }, { "code": null, "e": 5134, "s": 4824, "text": "By the way — as a quick aside — this tutorial is taken from the Data Science Course on Commonlounge. The course includes many hands-on assignments and projects. In addition, 80% of the course contents are available for free! If you’re interested in learning Data Science, definitely recommend checking it out." }, { "code": null, "e": 5478, "s": 5134, "text": "When using machine learning algorithms we should always split our data into a training set and test set. (If the number of experiments we are running is large, then we can should be dividing our data into 3 parts, namely — training set, development set and test set). In our case, we will also separate out some data for manual cross checking." }, { "code": null, "e": 5677, "s": 5478, "text": "The data set consists of record of 767 patients in total. To train our model we will be using 650 records. We will be using 100 records for testing, and the last 17 records to cross check our model." }, { "code": null, "e": 5758, "s": 5677, "text": "dfTrain = diabetesDF[:650]dfTest = diabetesDF[650:750]dfCheck = diabetesDF[750:]" }, { "code": null, "e": 5972, "s": 5758, "text": "Next, we separate the label and features (for both training and test dataset). In addition to that, we will also convert them into NumPy arrays as our machine learning algorithm process data in NumPy array format." }, { "code": null, "e": 6153, "s": 5972, "text": "trainLabel = np.asarray(dfTrain['Outcome'])trainData = np.asarray(dfTrain.drop('Outcome',1))testLabel = np.asarray(dfTest['Outcome'])testData = np.asarray(dfTest.drop('Outcome',1))" }, { "code": null, "e": 6526, "s": 6153, "text": "As the final step before using machine learning, we will normalize our inputs. Machine Learning models often benefit substantially from input normalization. It also makes it easier for us to understand the importance of each feature later, when we’ll be looking at the model weights. We’ll normalize the data such that each variable has 0 mean and standard deviation of 1." }, { "code": null, "e": 6781, "s": 6526, "text": "means = np.mean(trainData, axis=0)stds = np.std(trainData, axis=0)trainData = (trainData - means)/stdstestData = (testData - means)/stds# np.mean(trainData, axis=0) => check that new means equal 0# np.std(trainData, axis=0) => check that new stds equal 1" }, { "code": null, "e": 7122, "s": 6781, "text": "We can now train our classification model. We’ll be using a machine simple learning model called logistic regression. Since the model is readily available in sklearn, the training process is quite easy and we can do it in few lines of code. First, we create an instance called diabetesCheck and then use the fit function to train the model." }, { "code": null, "e": 7199, "s": 7122, "text": "diabetesCheck = LogisticRegression()diabetesCheck.fit(trainData, trainLabel)" }, { "code": null, "e": 7266, "s": 7199, "text": "Next, we will use our test data to find out accuracy of the model." }, { "code": null, "e": 7359, "s": 7266, "text": "accuracy = diabetesCheck.score(testData, testLabel)print(\"accuracy = \", accuracy * 100, \"%\")" }, { "code": null, "e": 7409, "s": 7359, "text": "The print statement will print accuracy = 78.0 %." }, { "code": null, "e": 7588, "s": 7409, "text": "To get a better sense of what is going on inside the logistic regression model, we can visualize how our model uses the different features and which features have greater effect." }, { "code": null, "e": 8041, "s": 7588, "text": "coeff = list(diabetesCheck.coef_[0])labels = list(trainData.columns)features = pd.DataFrame()features['Features'] = labelsfeatures['importance'] = coefffeatures.sort_values(by=['importance'], ascending=True, inplace=True)features['positive'] = features['importance'] > 0features.set_index('Features', inplace=True)features.importance.plot(kind='barh', figsize=(11, 6),color = features.positive.map({True: 'blue', False: 'red'}))plt.xlabel('Importance')" }, { "code": null, "e": 8103, "s": 8041, "text": "From the above figure, we can draw the following conclusions." }, { "code": null, "e": 8949, "s": 8103, "text": "Glucose level, BMI, pregnancies and diabetes pedigree function have significant influence on the model, specially glucose level and BMI. It is good to see our machine learning model match what we have been hearing from doctors our entire lives!Blood pressure has a negative influence on the prediction, i.e. higher blood pressure is correlated with a person not being diabetic. (also, note that blood pressure is more important as a feature than age, because the magnitude is higher for blood pressure).Although age was more correlated than BMI to the output variables (as we saw during data exploration), the model relies more on BMI. This can happen for several reasons, including the fact that the correlation captured by age is also captured by some other variable, whereas the information captured by BMI is not captured by other variables." }, { "code": null, "e": 9194, "s": 8949, "text": "Glucose level, BMI, pregnancies and diabetes pedigree function have significant influence on the model, specially glucose level and BMI. It is good to see our machine learning model match what we have been hearing from doctors our entire lives!" }, { "code": null, "e": 9454, "s": 9194, "text": "Blood pressure has a negative influence on the prediction, i.e. higher blood pressure is correlated with a person not being diabetic. (also, note that blood pressure is more important as a feature than age, because the magnitude is higher for blood pressure)." }, { "code": null, "e": 9797, "s": 9454, "text": "Although age was more correlated than BMI to the output variables (as we saw during data exploration), the model relies more on BMI. This can happen for several reasons, including the fact that the correlation captured by age is also captured by some other variable, whereas the information captured by BMI is not captured by other variables." }, { "code": null, "e": 9950, "s": 9797, "text": "Note that this above interpretations require that our input data is normalized. Without that, we can’t claim that importance is proportional to weights." }, { "code": null, "e": 10014, "s": 9950, "text": "Now we will save our trained model for future use using joblib." }, { "code": null, "e": 10078, "s": 10014, "text": "joblib.dump([diabetesCheck, means, stds], 'diabeteseModel.pkl')" }, { "code": null, "e": 10275, "s": 10078, "text": "To check whether we have saved the model properly or not, we will use our test data to check the accuracy of our saved model (we should observe no change in accuracy if we have saved it properly)." }, { "code": null, "e": 10450, "s": 10275, "text": "diabetesLoadedModel, means, stds = joblib.load('diabeteseModel.pkl')accuracyModel = diabetesLoadedModel.score(testData, testLabel)print(\"accuracy = \",accuracyModel * 100,\"%\")" }, { "code": null, "e": 10554, "s": 10450, "text": "We will now use our unused data to see how predictions can be made. We have our unused data in dfCheck." }, { "code": null, "e": 10576, "s": 10554, "text": "print(dfCheck.head())" }, { "code": null, "e": 10633, "s": 10576, "text": "We will now use the first record to make our prediction." }, { "code": null, "e": 11011, "s": 10633, "text": "sampleData = dfCheck[:1]# prepare samplesampleDataFeatures = np.asarray(sampleData.drop('Outcome',1))sampleDataFeatures = (sampleDataFeatures - means)/stds# predictpredictionProbability = diabetesLoadedModel.predict_proba(sampleDataFeatures)prediction = diabetesLoadedModel.predict(sampleDataFeatures)print('Probability:', predictionProbability)print('prediction:', prediction)" }, { "code": null, "e": 11035, "s": 11011, "text": "From above code we get:" }, { "code": null, "e": 11090, "s": 11035, "text": "Probability: [[ 0.4385153, 0.5614847]]prediction: [1]" }, { "code": null, "e": 11424, "s": 11090, "text": "The first element of array predictionProbability 0.438 is the probability of the class being 0 and second element 0.561 is the probability of the class being 1. The probabilities sum to 1. As we can see that the 1 is more probable class, we get [1] as our prediction, which means that the model predicts that the person has diabetes." }, { "code": null, "e": 11496, "s": 11424, "text": "There are lots of ways to improve the above model. Here are some ideas." }, { "code": null, "e": 11860, "s": 11496, "text": "Input feature bucketing should help, i.e. create new variables for blood pressure in a particular range, glucose levels in a particular range, and so on.You could also improve the data cleaning, by replacing 0 values with the mean value.Read a bit about what metrics do doctors rely on the most to diagnose a diabetic patient, and create new features accordingly." }, { "code": null, "e": 12014, "s": 11860, "text": "Input feature bucketing should help, i.e. create new variables for blood pressure in a particular range, glucose levels in a particular range, and so on." }, { "code": null, "e": 12099, "s": 12014, "text": "You could also improve the data cleaning, by replacing 0 values with the mean value." }, { "code": null, "e": 12226, "s": 12099, "text": "Read a bit about what metrics do doctors rely on the most to diagnose a diabetic patient, and create new features accordingly." }, { "code": null, "e": 12350, "s": 12226, "text": "See if you can get to 85–90% accuracy. You can get started with the jupyter notebook for this tutorial: pima_indians.ipynb." }, { "code": null, "e": 12401, "s": 12350, "text": "Co-authored by Keshav Dhandhania and Bishal Lakha." } ]
jQuery - Element Name Selector
The element selector selects all the elements that have a tag name of T. Here is the simple syntax to use this selector − $('tagname') Here is the description of all the parameters used by this selector − tagname − Any standard HTML tag name like div, p, em, img, li etc. tagname − Any standard HTML tag name like div, p, em, img, li etc. Like any other jQuery selector, this selector also returns an array filled with the found elements. $('p') − Selects all elements with a tag name of p in the document. $('p') − Selects all elements with a tag name of p in the document. $('div') − Selects all elements with a tag name of div in the document. $('div') − Selects all elements with a tag name of div in the document. Following example would select all the divisions and will apply yellow color to their background − <html> <head> <title>The Selecter Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { /* This would select all the divisions */ $("div").css("background-color", "yellow"); }); </script> </head> <body> <div class = "big" id = "div1"> <p>This is first division of the DOM.</p> </div> <div class = "medium" id = "div2"> <p>This is second division of the DOM.</p> </div> <div class = "small" id = "div3"> <p>This is third division of the DOM</p> </div> </body> </html> This will produce following result − This is first division of the DOM. This is second division of the DOM. This is third division of the DOM 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2395, "s": 2322, "text": "The element selector selects all the elements that have a tag name of T." }, { "code": null, "e": 2444, "s": 2395, "text": "Here is the simple syntax to use this selector −" }, { "code": null, "e": 2458, "s": 2444, "text": "$('tagname')\n" }, { "code": null, "e": 2528, "s": 2458, "text": "Here is the description of all the parameters used by this selector −" }, { "code": null, "e": 2595, "s": 2528, "text": "tagname − Any standard HTML tag name like div, p, em, img, li etc." }, { "code": null, "e": 2662, "s": 2595, "text": "tagname − Any standard HTML tag name like div, p, em, img, li etc." }, { "code": null, "e": 2762, "s": 2662, "text": "Like any other jQuery selector, this selector also returns an array filled with the found elements." }, { "code": null, "e": 2830, "s": 2762, "text": "$('p') − Selects all elements with a tag name of p in the document." }, { "code": null, "e": 2898, "s": 2830, "text": "$('p') − Selects all elements with a tag name of p in the document." }, { "code": null, "e": 2970, "s": 2898, "text": "$('div') − Selects all elements with a tag name of div in the document." }, { "code": null, "e": 3042, "s": 2970, "text": "$('div') − Selects all elements with a tag name of div in the document." }, { "code": null, "e": 3141, "s": 3042, "text": "Following example would select all the divisions and will apply yellow color to their background −" }, { "code": null, "e": 3941, "s": 3141, "text": "<html>\n <head>\n <title>The Selecter Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n /* This would select all the divisions */\n $(\"div\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <div class = \"big\" id = \"div1\">\n <p>This is first division of the DOM.</p>\n </div>\n\n <div class = \"medium\" id = \"div2\">\n <p>This is second division of the DOM.</p>\n </div>\n\n <div class = \"small\" id = \"div3\">\n <p>This is third division of the DOM</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 3978, "s": 3941, "text": "This will produce following result −" }, { "code": null, "e": 4013, "s": 3978, "text": "This is first division of the DOM." }, { "code": null, "e": 4049, "s": 4013, "text": "This is second division of the DOM." }, { "code": null, "e": 4083, "s": 4049, "text": "This is third division of the DOM" }, { "code": null, "e": 4116, "s": 4083, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 4130, "s": 4116, "text": " Mahesh Kumar" }, { "code": null, "e": 4165, "s": 4130, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4179, "s": 4165, "text": " Pratik Singh" }, { "code": null, "e": 4214, "s": 4179, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4231, "s": 4214, "text": " Frahaan Hussain" }, { "code": null, "e": 4264, "s": 4231, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 4292, "s": 4264, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4325, "s": 4292, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 4346, "s": 4325, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4378, "s": 4346, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 4395, "s": 4378, "text": " Laurence Svekis" }, { "code": null, "e": 4402, "s": 4395, "text": " Print" }, { "code": null, "e": 4413, "s": 4402, "text": " Add Notes" } ]
What are the types of arrays in Java?
There are two types of arrays in Java they are − Single dimensional array − A single dimensional array of Java is a normal array where, the array contains sequential elements (of same type) − int[] myArray = {10, 20, 30, 40} Live Demo public class TestArray { public static void main(String[] args) { double[] myList = {1.9, 2.9, 3.4, 3.5}; // Print all the array elements for (int i = 0; i < myList.length; i++) { System.out.println(myList[i] + " "); } // Summing all elements double total = 0; for (int i = 0; i < myList.length; i++) { total += myList[i]; } System.out.println("Total is " + total); // Finding the largest element double max = myList[0]; for (int i = 1; i < myList.length; i++) { if (myList[i] > max) max = myList[i]; } System.out.println("Max is " + max); } } 1.9 2.9 3.4 3.5 Total is 11.7 Max is 3.5 Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two dimensional array is an array of one dimensional arrays and a three dimensional array is an array of two dimensional arrays. Live Demo public class Tester { public static void main(String[] args) { int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} }; for(int i = 0 ; i < 3 ; i++){ //row for(int j = 0 ; j < 2; j++){ System.out.print(multidimensionalArray[i][j] + " "); } System.out.println(); } } } 1 2 2 3 3 4
[ { "code": null, "e": 1112, "s": 1062, "text": "There are two types of arrays in Java they are −" }, { "code": null, "e": 1255, "s": 1112, "text": "Single dimensional array − A single dimensional array of Java is a normal array where, the array contains sequential elements (of same type) −" }, { "code": null, "e": 1289, "s": 1255, "text": "int[] myArray = {10, 20, 30, 40}\n" }, { "code": null, "e": 1300, "s": 1289, "text": " Live Demo" }, { "code": null, "e": 1996, "s": 1300, "text": "public class TestArray {\n public static void main(String[] args) {\n double[] myList = {1.9, 2.9, 3.4, 3.5};\n \n // Print all the array elements\n for (int i = 0; i < myList.length; i++) {\n System.out.println(myList[i] + \" \");\n }\n \n // Summing all elements\n double total = 0;\n \n for (int i = 0; i < myList.length; i++) {\n total += myList[i];\n }\n System.out.println(\"Total is \" + total);\n \n // Finding the largest element\n double max = myList[0];\n \n for (int i = 1; i < myList.length; i++) {\n if (myList[i] > max) max = myList[i];\n }\n System.out.println(\"Max is \" + max);\n }\n}" }, { "code": null, "e": 2038, "s": 1996, "text": "1.9\n2.9\n3.4\n3.5\nTotal is 11.7\nMax is 3.5\n" }, { "code": null, "e": 2252, "s": 2038, "text": "Multi-dimensional array − A multi-dimensional array in Java is an array of arrays. A two dimensional array is an array of one dimensional arrays and a three dimensional array is an array of two dimensional arrays." }, { "code": null, "e": 2263, "s": 2252, "text": " Live Demo" }, { "code": null, "e": 2609, "s": 2263, "text": "public class Tester {\n public static void main(String[] args) {\n int[][] multidimensionalArray = { {1,2},{2,3}, {3,4} };\n \n for(int i = 0 ; i < 3 ; i++){\n //row\n for(int j = 0 ; j < 2; j++){\n System.out.print(multidimensionalArray[i][j] + \" \");\n }\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 2622, "s": 2609, "text": "1 2\n2 3\n3 4\n" } ]
p5.js | round() function - GeeksforGeeks
09 Apr, 2019 The round() function in p5.js is used to calculate the round value of a number. It calculates the integer closest to the number. Syntax round(number) Parameters: The function accepts only one parameter as mentioned above and described below: number : This parameter stores the number to compute.Below program illustrates the round() function in p5.js:Example:function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 67.54; //call to round() function let y = round(x); textSize(16); fill(color('red')); text("Given Number is : " + x, 50, 30); text("Computed Number is : " + y, 50, 50);}Output:Reference: https://p5js.org/reference/#/p5/roundMy Personal Notes arrow_drop_upSave Below program illustrates the round() function in p5.js:Example: function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 67.54; //call to round() function let y = round(x); textSize(16); fill(color('red')); text("Given Number is : " + x, 50, 30); text("Computed Number is : " + y, 50, 50);} Output: Reference: https://p5js.org/reference/#/p5/round JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript How to append HTML code to a div using JavaScript ? Set the value of an input field in JavaScript Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24896, "s": 24868, "text": "\n09 Apr, 2019" }, { "code": null, "e": 25025, "s": 24896, "text": "The round() function in p5.js is used to calculate the round value of a number. It calculates the integer closest to the number." }, { "code": null, "e": 25032, "s": 25025, "text": "Syntax" }, { "code": null, "e": 25047, "s": 25032, "text": "round(number)\n" }, { "code": null, "e": 25139, "s": 25047, "text": "Parameters: The function accepts only one parameter as mentioned above and described below:" }, { "code": null, "e": 25698, "s": 25139, "text": "number : This parameter stores the number to compute.Below program illustrates the round() function in p5.js:Example:function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 67.54; //call to round() function let y = round(x); textSize(16); fill(color('red')); text(\"Given Number is : \" + x, 50, 30); text(\"Computed Number is : \" + y, 50, 50);}Output:Reference: https://p5js.org/reference/#/p5/roundMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 25763, "s": 25698, "text": "Below program illustrates the round() function in p5.js:Example:" }, { "code": "function setup() { //create Canvas of size 270*80 createCanvas(270, 80);} function draw() { background(220); //initialize the parameter let x = 67.54; //call to round() function let y = round(x); textSize(16); fill(color('red')); text(\"Given Number is : \" + x, 50, 30); text(\"Computed Number is : \" + y, 50, 50);}", "e": 26115, "s": 25763, "text": null }, { "code": null, "e": 26123, "s": 26115, "text": "Output:" }, { "code": null, "e": 26172, "s": 26123, "text": "Reference: https://p5js.org/reference/#/p5/round" }, { "code": null, "e": 26189, "s": 26172, "text": "JavaScript-p5.js" }, { "code": null, "e": 26200, "s": 26189, "text": "JavaScript" }, { "code": null, "e": 26217, "s": 26200, "text": "Web Technologies" }, { "code": null, "e": 26315, "s": 26217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26324, "s": 26315, "text": "Comments" }, { "code": null, "e": 26337, "s": 26324, "text": "Old Comments" }, { "code": null, "e": 26398, "s": 26337, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26470, "s": 26398, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26515, "s": 26470, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26567, "s": 26515, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 26613, "s": 26567, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 26655, "s": 26613, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26688, "s": 26655, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26750, "s": 26688, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26793, "s": 26750, "text": "How to fetch data from an API in ReactJS ?" } ]
Image Scraping with Python. A code-along guide to learn how to... | by Fabian Bosler | Towards Data Science
To train a model, you need images. You can most certainly download them by hand, possibly even somewhere in batch, but I think there is a much more enjoyable way. Let’s use Python and some web scraping techniques to download images. Update 2 (Feb 25, 2020): One of the problems with scraping webpages is that the target elements depend on the a selector of some sort. We use css-selectors to get the relevant elements from the page. Google seemed to have changed its site layout sometime in the past, which made it necessary to update the relevant selectors. The provided script should be working again. Update: Since writing this article on image scraping, I have published the article on building an image-recognizing convolutional neural network. If you want to put the scraped images to good use, check out the following article! towardsdatascience.com Scraping static pagesScraping interactive pagesScraping images from GoogleAfterword on legality Scraping static pages Scraping interactive pages Scraping images from Google Afterword on legality A Python environment (I suggest Jupyter Notebook). If you haven’t set this up, don’t worry. It is effortless and takes less than 10 minutes. towardsdatascience.com Scraping static pages (i.e., pages that don’t utilize JavaScript to create a high degree of interaction on the page) is extremely simple. A static webpage is pretty much just a large file written in a markup language that defines how the content should be presented to the user. You can very quickly get the raw content without the markup being applied. Say that we want to get the following table from this Wikipedia page: We could do this by utilizing an essential Python library called requests like this: As you can see, this is not very useful. We don’t want all that noise but instead would like to extract only specific elements of the page (the table to be precise). Cases like this are where Beautiful Soup comes in extremely handy. Beautiful Soup allows us to navigate, search, or modify the parse tree easily. After running the raw content through the appropriate parser, we get a lovely clean parse tree. In this tree, we can search for an element of the type “table”, with the class “wikitable sortable.” You can get the information about class and type by right-clicking on the table and clicking inspect to see the source code.We then loop through that table and extract the data row by row, ultimately getting this result: Neat Trick:Pandas has a built-in read_html method that becomes available after installing lxml (a powerful XML and HTML parser) by running pip install lxml. read_html allows you to do the following: As you can see, we call res[2] as pd.read_html() will dump everything it finds that even loosely resembles a table into an individual DataFrame. You will have to check which of the resulting DataFrames contains the desired data. It is worth to give read_html a try for nicely structured data. However, most modern web pages are quite interactive. The concept of “single-page application” means that the web page itself will change without the user having to reload or getting redirected from page to page all the time. Because this happens only after specific user interactions, there are few options when it comes to scraping the data (as those actions do have to take place). Sometimes the user action might trigger a call to an exposed backend API. In which case, it might be possible to directly access the API and fetch the resulting data without having to go through the unnecessary steps in-between. Most of the time, however, you will have to go through the steps of clicking buttons, scrolling pages, waiting for loads and all of that ... or at least you have to make the webpage think you are doing all of that. Selenium to the rescue! Selenium can be used to automate web browser interaction with Python (also other languages). In layman’s term, selenium pretends to be a real user, it opens the browser, “moves” the cursor around and clicks buttons if you tell it to do so. The initial idea behind Selenium, as far as I know, is automated testing. However, Selenium is equally powerful when it comes to automating repetitive web-based tasks. Let’s look at an example to illustrate the usage of Selenium. Unfortunately, a little bit of preparation is required beforehand. I will outline the installation and usage of Selenium with Google Chrome. In case you want to use another Browser (e.g., Headless) you will have to download the respective WebDriver. You can find more information here. Steps: Install Google Chrome (skip if its already installed)Identify your Chrome version. Typically found by clicking About Google Chrome. I currently have version 77.0.3865.90 (my main version is thus 77, the number before the first dot).Download der corresponding ChromeDriver from here for your main version and put the executable into an accessible location (I use Desktop/Scraping)Install the Python Selenium package viapip install selenium Install Google Chrome (skip if its already installed) Identify your Chrome version. Typically found by clicking About Google Chrome. I currently have version 77.0.3865.90 (my main version is thus 77, the number before the first dot). Download der corresponding ChromeDriver from here for your main version and put the executable into an accessible location (I use Desktop/Scraping) Install the Python Selenium package viapip install selenium Starting a WebDriver Run the following snippet (for ease of demonstration do it in a Jupyter Notebook) and see how a ghostly browser opens up. import selenium# This is the path I use# DRIVER_PATH = '.../Desktop/Scraping/chromedriver 2'# Put the path for your ChromeDriver hereDRIVER_PATH = <YOUR PATH>wd = webdriver.Chrome(executable_path=DRIVER_PATH) If all went according to plan you should see something like this now: Now run (in a new cell): wd.get('https://google.com') Your browser should navigate to — not surprisingly — google.com. Now run: search_box = wd.find_element_by_css_selector('input.gLFyf')search_box.send_keys('Dogs') You’ll see the result as your Browser will type Dogs into the search box. Alright, let’s close the driver down: wd.quit() Perfect! You’ve got the basics covered. Selenium is extremely powerful, and pretty much every interaction can be simulated. Some actions are even accessible via abstract methods, like clicking buttons or hovering over things. Also, if worst comes to worst, you can always fall back on mimicking human behavior by moving the cursor to where you want it and then performing a click action. Since you now understand the basics, we can piece everything together. Let’s do the browser do our bidding by: Searching for a specific term & get image links Downloading the images Searching for a particular phrase & get the image links The function fetch_image_urls expects three input parameters: query : Search term, like Dogmax_links_to_fetch : Number of links the scraper is supposed to collectwebdriver : instantiated Webdriver query : Search term, like Dog max_links_to_fetch : Number of links the scraper is supposed to collect webdriver : instantiated Webdriver Downloading the imagesFor the following snippet to work, we will first have to install PIL by running pip install Pillow. The persist_image function grabs an image URL url and downloads it into the folder_path. The function will assign the image a random 10-digit id. Putting it all togetherThe following function search_and_download combines the previous two functions and adds some resiliency to how we use the ChromeDriver. More precisely, we are using the ChromeDriver within a with context, which guarantees that the browser closes down ordinarily, even if something within the with context raises an error. search_and_download allows you to specify number_images, which by default is set to 5, but can be set to whatever number of images you want to download. Now we can do the following: and will get: Congratulations! You have built your very own image scraper. Use the scraper with consideration and enjoy the cup of coffee that you are having instead of downloading 100 images by hand. If you want to learn how to automate the scraping process and run it continuously, check out the following article: towardsdatascience.com Ohh and if you enjoy reading stories like these and want to support me as a writer consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll even make some 🍩. medium.com I am not a lawyer, so nothing I say should be taken as legal advice. Having said that, the question around the legality of web scraping most likely has to be evaluated on a case-by-case basis. It seems to be a consensus that you are in the clear as long as you do not violate any terms of services or negatively affect the web pages you are scraping. The act of web scraping itself can’t be illegal. You could scrape your page without repercussions whatsoever and also the Google bot is scraping the entire web every day after all. My advice: Make sure that you are not breaking any laws, terms of services, or otherwise have a negative impact on your target.
[ { "code": null, "e": 405, "s": 172, "text": "To train a model, you need images. You can most certainly download them by hand, possibly even somewhere in batch, but I think there is a much more enjoyable way. Let’s use Python and some web scraping techniques to download images." }, { "code": null, "e": 776, "s": 405, "text": "Update 2 (Feb 25, 2020): One of the problems with scraping webpages is that the target elements depend on the a selector of some sort. We use css-selectors to get the relevant elements from the page. Google seemed to have changed its site layout sometime in the past, which made it necessary to update the relevant selectors. The provided script should be working again." }, { "code": null, "e": 1006, "s": 776, "text": "Update: Since writing this article on image scraping, I have published the article on building an image-recognizing convolutional neural network. If you want to put the scraped images to good use, check out the following article!" }, { "code": null, "e": 1029, "s": 1006, "text": "towardsdatascience.com" }, { "code": null, "e": 1125, "s": 1029, "text": "Scraping static pagesScraping interactive pagesScraping images from GoogleAfterword on legality" }, { "code": null, "e": 1147, "s": 1125, "text": "Scraping static pages" }, { "code": null, "e": 1174, "s": 1147, "text": "Scraping interactive pages" }, { "code": null, "e": 1202, "s": 1174, "text": "Scraping images from Google" }, { "code": null, "e": 1224, "s": 1202, "text": "Afterword on legality" }, { "code": null, "e": 1365, "s": 1224, "text": "A Python environment (I suggest Jupyter Notebook). If you haven’t set this up, don’t worry. It is effortless and takes less than 10 minutes." }, { "code": null, "e": 1388, "s": 1365, "text": "towardsdatascience.com" }, { "code": null, "e": 1812, "s": 1388, "text": "Scraping static pages (i.e., pages that don’t utilize JavaScript to create a high degree of interaction on the page) is extremely simple. A static webpage is pretty much just a large file written in a markup language that defines how the content should be presented to the user. You can very quickly get the raw content without the markup being applied. Say that we want to get the following table from this Wikipedia page:" }, { "code": null, "e": 1897, "s": 1812, "text": "We could do this by utilizing an essential Python library called requests like this:" }, { "code": null, "e": 2130, "s": 1897, "text": "As you can see, this is not very useful. We don’t want all that noise but instead would like to extract only specific elements of the page (the table to be precise). Cases like this are where Beautiful Soup comes in extremely handy." }, { "code": null, "e": 2627, "s": 2130, "text": "Beautiful Soup allows us to navigate, search, or modify the parse tree easily. After running the raw content through the appropriate parser, we get a lovely clean parse tree. In this tree, we can search for an element of the type “table”, with the class “wikitable sortable.” You can get the information about class and type by right-clicking on the table and clicking inspect to see the source code.We then loop through that table and extract the data row by row, ultimately getting this result:" }, { "code": null, "e": 2826, "s": 2627, "text": "Neat Trick:Pandas has a built-in read_html method that becomes available after installing lxml (a powerful XML and HTML parser) by running pip install lxml. read_html allows you to do the following:" }, { "code": null, "e": 3119, "s": 2826, "text": "As you can see, we call res[2] as pd.read_html() will dump everything it finds that even loosely resembles a table into an individual DataFrame. You will have to check which of the resulting DataFrames contains the desired data. It is worth to give read_html a try for nicely structured data." }, { "code": null, "e": 3504, "s": 3119, "text": "However, most modern web pages are quite interactive. The concept of “single-page application” means that the web page itself will change without the user having to reload or getting redirected from page to page all the time. Because this happens only after specific user interactions, there are few options when it comes to scraping the data (as those actions do have to take place)." }, { "code": null, "e": 3972, "s": 3504, "text": "Sometimes the user action might trigger a call to an exposed backend API. In which case, it might be possible to directly access the API and fetch the resulting data without having to go through the unnecessary steps in-between. Most of the time, however, you will have to go through the steps of clicking buttons, scrolling pages, waiting for loads and all of that ... or at least you have to make the webpage think you are doing all of that. Selenium to the rescue!" }, { "code": null, "e": 4380, "s": 3972, "text": "Selenium can be used to automate web browser interaction with Python (also other languages). In layman’s term, selenium pretends to be a real user, it opens the browser, “moves” the cursor around and clicks buttons if you tell it to do so. The initial idea behind Selenium, as far as I know, is automated testing. However, Selenium is equally powerful when it comes to automating repetitive web-based tasks." }, { "code": null, "e": 4728, "s": 4380, "text": "Let’s look at an example to illustrate the usage of Selenium. Unfortunately, a little bit of preparation is required beforehand. I will outline the installation and usage of Selenium with Google Chrome. In case you want to use another Browser (e.g., Headless) you will have to download the respective WebDriver. You can find more information here." }, { "code": null, "e": 4735, "s": 4728, "text": "Steps:" }, { "code": null, "e": 5174, "s": 4735, "text": "Install Google Chrome (skip if its already installed)Identify your Chrome version. Typically found by clicking About Google Chrome. I currently have version 77.0.3865.90 (my main version is thus 77, the number before the first dot).Download der corresponding ChromeDriver from here for your main version and put the executable into an accessible location (I use Desktop/Scraping)Install the Python Selenium package viapip install selenium" }, { "code": null, "e": 5228, "s": 5174, "text": "Install Google Chrome (skip if its already installed)" }, { "code": null, "e": 5408, "s": 5228, "text": "Identify your Chrome version. Typically found by clicking About Google Chrome. I currently have version 77.0.3865.90 (my main version is thus 77, the number before the first dot)." }, { "code": null, "e": 5556, "s": 5408, "text": "Download der corresponding ChromeDriver from here for your main version and put the executable into an accessible location (I use Desktop/Scraping)" }, { "code": null, "e": 5616, "s": 5556, "text": "Install the Python Selenium package viapip install selenium" }, { "code": null, "e": 5637, "s": 5616, "text": "Starting a WebDriver" }, { "code": null, "e": 5759, "s": 5637, "text": "Run the following snippet (for ease of demonstration do it in a Jupyter Notebook) and see how a ghostly browser opens up." }, { "code": null, "e": 5968, "s": 5759, "text": "import selenium# This is the path I use# DRIVER_PATH = '.../Desktop/Scraping/chromedriver 2'# Put the path for your ChromeDriver hereDRIVER_PATH = <YOUR PATH>wd = webdriver.Chrome(executable_path=DRIVER_PATH)" }, { "code": null, "e": 6038, "s": 5968, "text": "If all went according to plan you should see something like this now:" }, { "code": null, "e": 6063, "s": 6038, "text": "Now run (in a new cell):" }, { "code": null, "e": 6092, "s": 6063, "text": "wd.get('https://google.com')" }, { "code": null, "e": 6166, "s": 6092, "text": "Your browser should navigate to — not surprisingly — google.com. Now run:" }, { "code": null, "e": 6254, "s": 6166, "text": "search_box = wd.find_element_by_css_selector('input.gLFyf')search_box.send_keys('Dogs')" }, { "code": null, "e": 6328, "s": 6254, "text": "You’ll see the result as your Browser will type Dogs into the search box." }, { "code": null, "e": 6366, "s": 6328, "text": "Alright, let’s close the driver down:" }, { "code": null, "e": 6376, "s": 6366, "text": "wd.quit()" }, { "code": null, "e": 6764, "s": 6376, "text": "Perfect! You’ve got the basics covered. Selenium is extremely powerful, and pretty much every interaction can be simulated. Some actions are even accessible via abstract methods, like clicking buttons or hovering over things. Also, if worst comes to worst, you can always fall back on mimicking human behavior by moving the cursor to where you want it and then performing a click action." }, { "code": null, "e": 6875, "s": 6764, "text": "Since you now understand the basics, we can piece everything together. Let’s do the browser do our bidding by:" }, { "code": null, "e": 6923, "s": 6875, "text": "Searching for a specific term & get image links" }, { "code": null, "e": 6946, "s": 6923, "text": "Downloading the images" }, { "code": null, "e": 7002, "s": 6946, "text": "Searching for a particular phrase & get the image links" }, { "code": null, "e": 7064, "s": 7002, "text": "The function fetch_image_urls expects three input parameters:" }, { "code": null, "e": 7199, "s": 7064, "text": "query : Search term, like Dogmax_links_to_fetch : Number of links the scraper is supposed to collectwebdriver : instantiated Webdriver" }, { "code": null, "e": 7229, "s": 7199, "text": "query : Search term, like Dog" }, { "code": null, "e": 7301, "s": 7229, "text": "max_links_to_fetch : Number of links the scraper is supposed to collect" }, { "code": null, "e": 7336, "s": 7301, "text": "webdriver : instantiated Webdriver" }, { "code": null, "e": 7458, "s": 7336, "text": "Downloading the imagesFor the following snippet to work, we will first have to install PIL by running pip install Pillow." }, { "code": null, "e": 7604, "s": 7458, "text": "The persist_image function grabs an image URL url and downloads it into the folder_path. The function will assign the image a random 10-digit id." }, { "code": null, "e": 8102, "s": 7604, "text": "Putting it all togetherThe following function search_and_download combines the previous two functions and adds some resiliency to how we use the ChromeDriver. More precisely, we are using the ChromeDriver within a with context, which guarantees that the browser closes down ordinarily, even if something within the with context raises an error. search_and_download allows you to specify number_images, which by default is set to 5, but can be set to whatever number of images you want to download." }, { "code": null, "e": 8131, "s": 8102, "text": "Now we can do the following:" }, { "code": null, "e": 8145, "s": 8131, "text": "and will get:" }, { "code": null, "e": 8332, "s": 8145, "text": "Congratulations! You have built your very own image scraper. Use the scraper with consideration and enjoy the cup of coffee that you are having instead of downloading 100 images by hand." }, { "code": null, "e": 8448, "s": 8332, "text": "If you want to learn how to automate the scraping process and run it continuously, check out the following article:" }, { "code": null, "e": 8471, "s": 8448, "text": "towardsdatascience.com" }, { "code": null, "e": 8721, "s": 8471, "text": "Ohh and if you enjoy reading stories like these and want to support me as a writer consider signing up to become a Medium member. It’s $5 a month, giving you unlimited access to stories on Medium. If you sign up using my link, I’ll even make some 🍩." }, { "code": null, "e": 8732, "s": 8721, "text": "medium.com" }, { "code": null, "e": 9275, "s": 8732, "text": "I am not a lawyer, so nothing I say should be taken as legal advice. Having said that, the question around the legality of web scraping most likely has to be evaluated on a case-by-case basis. It seems to be a consensus that you are in the clear as long as you do not violate any terms of services or negatively affect the web pages you are scraping. The act of web scraping itself can’t be illegal. You could scrape your page without repercussions whatsoever and also the Google bot is scraping the entire web every day after all. My advice:" } ]
CSS | transition-property Property - GeeksforGeeks
09 Aug, 2019 The transition effect is used to display the change in the property of an element over a specified duration. The transition-property property is used to specify the name of the CSS property for which the transition effect will occur. Syntax: transition-property: none | all | property | initial | inherit; Property values: none: This value is used to specify that no property will get a transition effect.Syntax:transition-property: none; Example: In the below example, we have specified that none of the property will get a transition effect. Hence if we hover of the box, the changes in its properties will be sudden rather than transitioning from one value to another over a specified duration.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: none; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: none</h2> <div class="box"></div> </body></html>Output: Syntax: transition-property: none; Example: In the below example, we have specified that none of the property will get a transition effect. Hence if we hover of the box, the changes in its properties will be sudden rather than transitioning from one value to another over a specified duration. <!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: none; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: none</h2> <div class="box"></div> </body></html> Output: all: All the CSS properties will get a transition effect. This is also the default value for this property.Syntax:transition-property: all; Example: Instead of specifying the names of all the properties for which we need transition effect, we can also use the all value for the transition-property. This will allow us to display transition effect for all the properties without specifying their names individually which can be shown by the below example:<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: all; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: all</h2> <div class="box"></div> </body></html>Output: Syntax: transition-property: all; Example: Instead of specifying the names of all the properties for which we need transition effect, we can also use the all value for the transition-property. This will allow us to display transition effect for all the properties without specifying their names individually which can be shown by the below example: <!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: all; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: all</h2> <div class="box"></div> </body></html> Output: property: We can specify the names of CSS properties for which transition effect will be applied. We can also specify multiple properties by separating them with a comma.Syntax:transition-property: property; Example: We have specified multiple properties in the below example for transition effect (i.e background-color, width and height) by separating them with a comma. Hence when we hover over the box, we can see the transitions in the properties of the box.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: background-color, width, height; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2> transition-property: background-color, width, height</h2> <div class="box"></div> </body></html>Output: Syntax: transition-property: property; Example: We have specified multiple properties in the below example for transition effect (i.e background-color, width and height) by separating them with a comma. Hence when we hover over the box, we can see the transitions in the properties of the box. <!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: background-color, width, height; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2> transition-property: background-color, width, height</h2> <div class="box"></div> </body></html> Output: initial: Used to set this property to its default value. This value is useful when we don’t know the default value for a specific property.Syntax:transition-property: initial; Example: As we have specified the property value as initial in the below example, the default value for this property (which is all) will be assigned to transition-property. Hence, transition effect will occur for all the CSS properties which change as we hover over the box.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: initial; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: initial</h2> <div class="box"></div> </body></html>Output: Syntax: transition-property: initial; Example: As we have specified the property value as initial in the below example, the default value for this property (which is all) will be assigned to transition-property. Hence, transition effect will occur for all the CSS properties which change as we hover over the box. <!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: initial; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: initial</h2> <div class="box"></div> </body></html> Output: inherit: Used to specify that this property will inherit its value from its parent element.Syntax:transition-property: inherit; Example: As we have specified the property value as inherit in the below example, the box will inherit the transition-property value of its property. But in this case, the transition-property value of its parent will be all (as it is the default value) as we haven’t not specified the value for its parent. Hence, transition effect will occur for all the CSS properties.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: inherit; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: inherit</h2> <div class="box"></div> </body></html>Output: Syntax: transition-property: inherit; Example: As we have specified the property value as inherit in the below example, the box will inherit the transition-property value of its property. But in this case, the transition-property value of its parent will be all (as it is the default value) as we haven’t not specified the value for its parent. Hence, transition effect will occur for all the CSS properties. <!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: inherit; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: inherit</h2> <div class="box"></div> </body></html> Output: Supported browsers: The browsers supported by transition-property Property are listed below: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties Picked CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 23780, "s": 23752, "text": "\n09 Aug, 2019" }, { "code": null, "e": 24014, "s": 23780, "text": "The transition effect is used to display the change in the property of an element over a specified duration. The transition-property property is used to specify the name of the CSS property for which the transition effect will occur." }, { "code": null, "e": 24022, "s": 24014, "text": "Syntax:" }, { "code": null, "e": 24087, "s": 24022, "text": "transition-property: none | all | property | initial | inherit;\n" }, { "code": null, "e": 24104, "s": 24087, "text": "Property values:" }, { "code": null, "e": 25065, "s": 24104, "text": "none: This value is used to specify that no property will get a transition effect.Syntax:transition-property: none;\nExample: In the below example, we have specified that none of the property will get a transition effect. Hence if we hover of the box, the changes in its properties will be sudden rather than transitioning from one value to another over a specified duration.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: none; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: none</h2> <div class=\"box\"></div> </body></html>Output:" }, { "code": null, "e": 25073, "s": 25065, "text": "Syntax:" }, { "code": null, "e": 25101, "s": 25073, "text": "transition-property: none;\n" }, { "code": null, "e": 25360, "s": 25101, "text": "Example: In the below example, we have specified that none of the property will get a transition effect. Hence if we hover of the box, the changes in its properties will be sudden rather than transitioning from one value to another over a specified duration." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: none; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: none</h2> <div class=\"box\"></div> </body></html>", "e": 25940, "s": 25360, "text": null }, { "code": null, "e": 25948, "s": 25940, "text": "Output:" }, { "code": null, "e": 26987, "s": 25948, "text": "all: All the CSS properties will get a transition effect. This is also the default value for this property.Syntax:transition-property: all;\nExample: Instead of specifying the names of all the properties for which we need transition effect, we can also use the all value for the transition-property. This will allow us to display transition effect for all the properties without specifying their names individually which can be shown by the below example:<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: all; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: all</h2> <div class=\"box\"></div> </body></html>Output:" }, { "code": null, "e": 26995, "s": 26987, "text": "Syntax:" }, { "code": null, "e": 27022, "s": 26995, "text": "transition-property: all;\n" }, { "code": null, "e": 27337, "s": 27022, "text": "Example: Instead of specifying the names of all the properties for which we need transition effect, we can also use the all value for the transition-property. This will allow us to display transition effect for all the properties without specifying their names individually which can be shown by the below example:" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: all; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: all</h2> <div class=\"box\"></div> </body></html>", "e": 27915, "s": 27337, "text": null }, { "code": null, "e": 27923, "s": 27915, "text": "Output:" }, { "code": null, "e": 29036, "s": 27923, "text": "property: We can specify the names of CSS properties for which transition effect will be applied. We can also specify multiple properties by separating them with a comma.Syntax:transition-property: property;\nExample: We have specified multiple properties in the below example for transition effect (i.e background-color, width and height) by separating them with a comma. Hence when we hover over the box, we can see the transitions in the properties of the box.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: background-color, width, height; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2> transition-property: background-color, width, height</h2> <div class=\"box\"></div> </body></html>Output:" }, { "code": null, "e": 29044, "s": 29036, "text": "Syntax:" }, { "code": null, "e": 29076, "s": 29044, "text": "transition-property: property;\n" }, { "code": null, "e": 29331, "s": 29076, "text": "Example: We have specified multiple properties in the below example for transition effect (i.e background-color, width and height) by separating them with a comma. Hence when we hover over the box, we can see the transitions in the properties of the box." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: background-color, width, height; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2> transition-property: background-color, width, height</h2> <div class=\"box\"></div> </body></html>", "e": 29975, "s": 29331, "text": null }, { "code": null, "e": 29983, "s": 29975, "text": "Output:" }, { "code": null, "e": 31027, "s": 29983, "text": "initial: Used to set this property to its default value. This value is useful when we don’t know the default value for a specific property.Syntax:transition-property: initial;\nExample: As we have specified the property value as initial in the below example, the default value for this property (which is all) will be assigned to transition-property. Hence, transition effect will occur for all the CSS properties which change as we hover over the box.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: initial; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: initial</h2> <div class=\"box\"></div> </body></html>Output:" }, { "code": null, "e": 31035, "s": 31027, "text": "Syntax:" }, { "code": null, "e": 31066, "s": 31035, "text": "transition-property: initial;\n" }, { "code": null, "e": 31342, "s": 31066, "text": "Example: As we have specified the property value as initial in the below example, the default value for this property (which is all) will be assigned to transition-property. Hence, transition effect will occur for all the CSS properties which change as we hover over the box." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: initial; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: initial</h2> <div class=\"box\"></div> </body></html>", "e": 31928, "s": 31342, "text": null }, { "code": null, "e": 31936, "s": 31928, "text": "Output:" }, { "code": null, "e": 33027, "s": 31936, "text": "inherit: Used to specify that this property will inherit its value from its parent element.Syntax:transition-property: inherit;\nExample: As we have specified the property value as inherit in the below example, the box will inherit the transition-property value of its property. But in this case, the transition-property value of its parent will be all (as it is the default value) as we haven’t not specified the value for its parent. Hence, transition effect will occur for all the CSS properties.<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: inherit; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: inherit</h2> <div class=\"box\"></div> </body></html>Output:" }, { "code": null, "e": 33035, "s": 33027, "text": "Syntax:" }, { "code": null, "e": 33066, "s": 33035, "text": "transition-property: inherit;\n" }, { "code": null, "e": 33437, "s": 33066, "text": "Example: As we have specified the property value as inherit in the below example, the box will inherit the transition-property value of its property. But in this case, the transition-property value of its parent will be all (as it is the default value) as we haven’t not specified the value for its parent. Hence, transition effect will occur for all the CSS properties." }, { "code": "<!DOCTYPE html><html> <head> <title>CSS transition-property property</title> <style> .box{ background-color: red; width: 300px; height: 200px; margin: auto; transition-property: inherit; transition-duration: 2s; } .box:hover{ background-color: pink; width: 200px; height: 150px; } h1, h2{ color: green; text-align: center; } </style> </head> <body> <h1>Geeks For Geeks</h1> <h2>transition-property: inherit</h2> <div class=\"box\"></div> </body></html>", "e": 34023, "s": 33437, "text": null }, { "code": null, "e": 34031, "s": 34023, "text": "Output:" }, { "code": null, "e": 34124, "s": 34031, "text": "Supported browsers: The browsers supported by transition-property Property are listed below:" }, { "code": null, "e": 34138, "s": 34124, "text": "Google Chrome" }, { "code": null, "e": 34156, "s": 34138, "text": "Internet Explorer" }, { "code": null, "e": 34164, "s": 34156, "text": "Firefox" }, { "code": null, "e": 34170, "s": 34164, "text": "Opera" }, { "code": null, "e": 34177, "s": 34170, "text": "Safari" }, { "code": null, "e": 34314, "s": 34177, "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": 34329, "s": 34314, "text": "CSS-Properties" }, { "code": null, "e": 34336, "s": 34329, "text": "Picked" }, { "code": null, "e": 34340, "s": 34336, "text": "CSS" }, { "code": null, "e": 34345, "s": 34340, "text": "HTML" }, { "code": null, "e": 34364, "s": 34345, "text": "Technical Scripter" }, { "code": null, "e": 34381, "s": 34364, "text": "Web Technologies" }, { "code": null, "e": 34386, "s": 34381, "text": "HTML" }, { "code": null, "e": 34484, "s": 34386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34534, "s": 34484, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34596, "s": 34534, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34654, "s": 34596, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 34702, "s": 34654, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 34752, "s": 34702, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 34802, "s": 34752, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 34864, "s": 34802, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 34924, "s": 34864, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 34972, "s": 34924, "text": "How to update Node.js and NPM to next version ?" } ]
How to copy only updated or newer files with PowerShell?
To copy only updated or newer files with PowerShell, we can use Copy-Item with some logic in the script that to check if the files exist on the destination folder if not then copy that file and if yes then compare the timestamp and copy the latest file. This would be tricky because we need to write several lines of code for it. But Windows support xCopy utility which can directly copy the newer or updated files and this utility we can accommodate in PowerShell as well. xCopy uses a switch called /d. its actual syntax is, /d [:MM-DD-YYYY] This means if the date specified, it copies the files and folders newer than that date and if don't specify any date then it copies all files and folders that are updated. An example is shown below. Source: C:\DSC Destination: E\Temp Our folder structure is like this, LabMachine2k16.mof file also exists on the destination but it is an updated file, Test.txt is a new file and the Pagefile folder is a new folder but it is an empty one. xcopy C:\DSC E:\Temp\ /s /d /e /f /y PS C:\> xcopy C:\DSC E:\Temp\ /s /d /e /f /y C:\DSC\LabMachine2k16.mof -> E:\Temp\LabMachine2k16.mof C:\DSC\Test.txt -> E:\Temp\Test.txt 2 File(s) copied Switches. /s – Specifies the subfolder /e – Specifies the empty directory /d – Specifies the updated files to copy /f – Displays the source and the destination. /y – Confirms without asking user prompt.
[ { "code": null, "e": 1392, "s": 1062, "text": "To copy only updated or newer files with PowerShell, we can use Copy-Item with some logic in the script that to check if the files exist on the destination folder if not then copy that file and if yes then compare the timestamp and copy the latest file. This would be tricky because we need to write several lines of code for it." }, { "code": null, "e": 1536, "s": 1392, "text": "But Windows support xCopy utility which can directly copy the newer or updated files and this utility we can accommodate in PowerShell as well." }, { "code": null, "e": 1589, "s": 1536, "text": "xCopy uses a switch called /d. its actual syntax is," }, { "code": null, "e": 1606, "s": 1589, "text": "/d [:MM-DD-YYYY]" }, { "code": null, "e": 1805, "s": 1606, "text": "This means if the date specified, it copies the files and folders newer than that date and if don't specify any date then it copies all files and folders that are updated. An example is shown below." }, { "code": null, "e": 1813, "s": 1805, "text": "Source:" }, { "code": null, "e": 1820, "s": 1813, "text": "C:\\DSC" }, { "code": null, "e": 1833, "s": 1820, "text": "Destination:" }, { "code": null, "e": 1840, "s": 1833, "text": "E\\Temp" }, { "code": null, "e": 2044, "s": 1840, "text": "Our folder structure is like this, LabMachine2k16.mof file also exists on the destination but it is an updated file, Test.txt is a new file and the Pagefile folder is a new folder but it is an empty one." }, { "code": null, "e": 2081, "s": 2044, "text": "xcopy C:\\DSC E:\\Temp\\ /s /d /e /f /y" }, { "code": null, "e": 2235, "s": 2081, "text": "PS C:\\> xcopy C:\\DSC E:\\Temp\\ /s /d /e /f /y\nC:\\DSC\\LabMachine2k16.mof -> E:\\Temp\\LabMachine2k16.mof\nC:\\DSC\\Test.txt -> E:\\Temp\\Test.txt\n2 File(s) copied" }, { "code": null, "e": 2245, "s": 2235, "text": "Switches." }, { "code": null, "e": 2274, "s": 2245, "text": "/s – Specifies the subfolder" }, { "code": null, "e": 2309, "s": 2274, "text": "/e – Specifies the empty directory" }, { "code": null, "e": 2350, "s": 2309, "text": "/d – Specifies the updated files to copy" }, { "code": null, "e": 2396, "s": 2350, "text": "/f – Displays the source and the destination." }, { "code": null, "e": 2438, "s": 2396, "text": "/y – Confirms without asking user prompt." } ]
How to get the specific process(es) information using PowerShell?
To find the specific process using Get-Process cmdlet, you need to use the –Name parameter. You can use single and multiple process names. Get-Process -Name AcroRd32, audiodg Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName ------- ------ ----- ----- ------ -- -- ----------- 506 27 9888 19216 2.22 6320 1 AcroRd32 632 51 112196 17648 42.95 8052 1 AcroRd32 209 13 10344 17100 13.98 22748 0 audiodg You can also achieve the same using Where-Object (alias: Where) command. Get-Process | Where{$_.Name -eq "AcroRd32"} But to get the multiple processes you need to use the –OR comparison operator. Get-Process | Where{($_.Name -eq "AcroRd32") -or ($_.Name -eq "AudioDg")} The result will be the same as displayed above. To get the specific process information using the WMI object, you can use –Filter parameter or pipeline Where-Object command.Using the Where-Object command. To get the specific process information using the WMI object, you can use –Filter parameter or pipeline Where-Object command. Using the Where-Object command. Get-WmiObject Win32_Process | Where{($_.Name -eq "AcroRd32.exe") -or ($_. Name -eq "AudioDg.exe")} Using –Filter parameter. Get-WmiObject Win32_Process -Filter {Name = 'AcroRD32.exe'} To get the multiple processes, you need to use AND comparison operator. Get-WmiObject Win32_Process -Filter {Name = 'AcroRD32.exe' or Name = 'AudioDg.exe'}
[ { "code": null, "e": 1201, "s": 1062, "text": "To find the specific process using Get-Process cmdlet, you need to use the –Name parameter. You can use single and multiple process names." }, { "code": null, "e": 1237, "s": 1201, "text": "Get-Process -Name AcroRd32, audiodg" }, { "code": null, "e": 1463, "s": 1237, "text": "Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName\n------- ------ ----- ----- ------ -- -- -----------\n506 27 9888 19216 2.22 6320 1 AcroRd32\n632 51 112196 17648 42.95 8052 1 AcroRd32\n209 13 10344 17100 13.98 22748 0 audiodg" }, { "code": null, "e": 1536, "s": 1463, "text": "You can also achieve the same using Where-Object (alias: Where) command." }, { "code": null, "e": 1581, "s": 1536, "text": "Get-Process | Where{$_.Name -eq \"AcroRd32\"}\n" }, { "code": null, "e": 1660, "s": 1581, "text": "But to get the multiple processes you need to use the –OR comparison operator." }, { "code": null, "e": 1734, "s": 1660, "text": "Get-Process | Where{($_.Name -eq \"AcroRd32\") -or ($_.Name -eq \"AudioDg\")}" }, { "code": null, "e": 1782, "s": 1734, "text": "The result will be the same as displayed above." }, { "code": null, "e": 1939, "s": 1782, "text": "To get the specific process information using the WMI object, you can use –Filter parameter or pipeline Where-Object command.Using the Where-Object command." }, { "code": null, "e": 2065, "s": 1939, "text": "To get the specific process information using the WMI object, you can use –Filter parameter or pipeline Where-Object command." }, { "code": null, "e": 2097, "s": 2065, "text": "Using the Where-Object command." }, { "code": null, "e": 2197, "s": 2097, "text": "Get-WmiObject Win32_Process | Where{($_.Name -eq \"AcroRd32.exe\") -or ($_. Name -eq \"AudioDg.exe\")}\n" }, { "code": null, "e": 2222, "s": 2197, "text": "Using –Filter parameter." }, { "code": null, "e": 2282, "s": 2222, "text": "Get-WmiObject Win32_Process -Filter {Name = 'AcroRD32.exe'}" }, { "code": null, "e": 2354, "s": 2282, "text": "To get the multiple processes, you need to use AND comparison operator." }, { "code": null, "e": 2439, "s": 2354, "text": "Get-WmiObject Win32_Process -Filter {Name = 'AcroRD32.exe' or Name = 'AudioDg.exe'}\n" } ]
PL/SQL - Exceptions
In this chapter, we will discuss Exceptions in PL/SQL. An exception is an error condition during a program execution. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions − System-defined exceptions User-defined exceptions The general syntax for exception handling is as follows. Here you can list down as many exceptions as you can handle. The default exception will be handled using WHEN others THEN − DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <exception handling goes here > WHEN exception1 THEN exception1-handling-statements WHEN exception2 THEN exception2-handling-statements WHEN exception3 THEN exception3-handling-statements ........ WHEN others THEN exception3-handling-statements END; Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the previous chapters − DECLARE c_id customers.id%type := 8; c_name customerS.Name%type; c_addr customers.address%type; BEGIN SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id; DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); EXCEPTION WHEN no_data_found THEN dbms_output.put_line('No such customer!'); WHEN others THEN dbms_output.put_line('Error!'); END; / When the above code is executed at the SQL prompt, it produces the following result − No such customer! PL/SQL procedure successfully completed. The above program displays the name and address of a customer whose ID is given. Since there is no customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION block. Exceptions are raised by the database server automatically whenever there is any internal database error, but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the simple syntax for raising an exception − DECLARE exception_name EXCEPTION; BEGIN IF condition THEN RAISE exception_name; END IF; EXCEPTION WHEN exception_name THEN statement; END; You can use the above syntax in raising the Oracle standard exception or any user-defined exception. In the next section, we will give you an example on raising a user-defined exception. You can raise the Oracle standard exceptions in a similar way. PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR. The syntax for declaring an exception is − DECLARE my-exception EXCEPTION; The following example illustrates the concept. This program asks for a customer ID, when the user enters an invalid ID, the exception invalid_id is raised. DECLARE c_id customers.id%type := &cc_id; c_name customerS.Name%type; c_addr customers.address%type; -- user defined exception ex_invalid_id EXCEPTION; BEGIN IF c_id <= 0 THEN RAISE ex_invalid_id; ELSE SELECT name, address INTO c_name, c_addr FROM customers WHERE id = c_id; DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); END IF; EXCEPTION WHEN ex_invalid_id THEN dbms_output.put_line('ID must be greater than zero!'); WHEN no_data_found THEN dbms_output.put_line('No such customer!'); WHEN others THEN dbms_output.put_line('Error!'); END; / When the above code is executed at the SQL prompt, it produces the following result − Enter value for cc_id: -6 (let's enter a value -6) old 2: c_id customers.id%type := &cc_id; new 2: c_id customers.id%type := -6; ID must be greater than zero! PL/SQL procedure successfully completed. PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The following table lists few of the important pre-defined exceptions − Print Add Notes Bookmark this page
[ { "code": null, "e": 2373, "s": 2065, "text": "In this chapter, we will discuss Exceptions in PL/SQL. An exception is an error condition during a program execution. PL/SQL supports programmers to catch such conditions using EXCEPTION block in the program and an appropriate action is taken against the error condition. There are two types of exceptions −" }, { "code": null, "e": 2399, "s": 2373, "text": "System-defined exceptions" }, { "code": null, "e": 2423, "s": 2399, "text": "User-defined exceptions" }, { "code": null, "e": 2604, "s": 2423, "text": "The general syntax for exception handling is as follows. Here you can list down as many exceptions as you can handle. The default exception will be handled using WHEN others THEN −" }, { "code": null, "e": 2994, "s": 2604, "text": "DECLARE \n <declarations section> \nBEGIN \n <executable command(s)> \nEXCEPTION \n <exception handling goes here > \n WHEN exception1 THEN \n exception1-handling-statements \n WHEN exception2 THEN \n exception2-handling-statements \n WHEN exception3 THEN \n exception3-handling-statements \n ........ \n WHEN others THEN \n exception3-handling-statements \nEND;" }, { "code": null, "e": 3129, "s": 2994, "text": "Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we had created and used in the previous chapters −" }, { "code": null, "e": 3588, "s": 3129, "text": "DECLARE \n c_id customers.id%type := 8; \n c_name customerS.Name%type; \n c_addr customers.address%type; \nBEGIN \n SELECT name, address INTO c_name, c_addr \n FROM customers \n WHERE id = c_id; \n DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); \n DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); \n\nEXCEPTION \n WHEN no_data_found THEN \n dbms_output.put_line('No such customer!'); \n WHEN others THEN \n dbms_output.put_line('Error!'); \nEND; \n/" }, { "code": null, "e": 3674, "s": 3588, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 3738, "s": 3674, "text": "No such customer! \n\nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 3978, "s": 3738, "text": "The above program displays the name and address of a customer whose ID is given. Since there is no customer with ID value 8 in our database, the program raises the run-time exception NO_DATA_FOUND, which is captured in the EXCEPTION block." }, { "code": null, "e": 4228, "s": 3978, "text": "Exceptions are raised by the database server automatically whenever there is any internal database error, but exceptions can be raised explicitly by the programmer by using the command RAISE. Following is the simple syntax for raising an exception −" }, { "code": null, "e": 4398, "s": 4228, "text": "DECLARE \n exception_name EXCEPTION; \nBEGIN \n IF condition THEN \n RAISE exception_name; \n END IF; \nEXCEPTION \n WHEN exception_name THEN \n statement; \nEND; " }, { "code": null, "e": 4648, "s": 4398, "text": "You can use the above syntax in raising the Oracle standard exception or any user-defined exception. In the next section, we will give you an example on raising a user-defined exception. You can raise the Oracle standard exceptions in a similar way." }, { "code": null, "e": 4892, "s": 4648, "text": "PL/SQL allows you to define your own exceptions according to the need of your program. A user-defined exception must be declared and then raised explicitly, using either a RAISE statement or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR." }, { "code": null, "e": 4935, "s": 4892, "text": "The syntax for declaring an exception is −" }, { "code": null, "e": 4973, "s": 4935, "text": "DECLARE \n my-exception EXCEPTION; \n" }, { "code": null, "e": 5129, "s": 4973, "text": "The following example illustrates the concept. This program asks for a customer ID, when the user enters an invalid ID, the exception invalid_id is raised." }, { "code": null, "e": 5830, "s": 5129, "text": "DECLARE \n c_id customers.id%type := &cc_id; \n c_name customerS.Name%type; \n c_addr customers.address%type; \n -- user defined exception \n ex_invalid_id EXCEPTION; \nBEGIN \n IF c_id <= 0 THEN \n RAISE ex_invalid_id; \n ELSE \n SELECT name, address INTO c_name, c_addr \n FROM customers \n WHERE id = c_id;\n DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name); \n DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr); \n END IF; \n\nEXCEPTION \n WHEN ex_invalid_id THEN \n dbms_output.put_line('ID must be greater than zero!'); \n WHEN no_data_found THEN \n dbms_output.put_line('No such customer!'); \n WHEN others THEN \n dbms_output.put_line('Error!'); \nEND; \n/" }, { "code": null, "e": 5916, "s": 5830, "text": "When the above code is executed at the SQL prompt, it produces the following result −" }, { "code": null, "e": 6126, "s": 5916, "text": "Enter value for cc_id: -6 (let's enter a value -6) \nold 2: c_id customers.id%type := &cc_id; \nnew 2: c_id customers.id%type := -6; \nID must be greater than zero! \n \nPL/SQL procedure successfully completed. \n" }, { "code": null, "e": 6419, "s": 6126, "text": "PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated by a program. For example, the predefined exception NO_DATA_FOUND is raised when a SELECT INTO statement returns no rows. The following table lists few of the important pre-defined exceptions −" }, { "code": null, "e": 6426, "s": 6419, "text": " Print" }, { "code": null, "e": 6437, "s": 6426, "text": " Add Notes" } ]
Alternative of Malloc in C - GeeksforGeeks
28 Jan, 2022 An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers, etc. Given below is the picturesque representation of an array. There are two types of array/ string declaration in C++ as listed as follows Static DeclarationDynamic Declaration Static Declaration Dynamic Declaration Way 1: Static Declaration Methods: The static declaration can be done in 3 ways Array declaration by specifying the size Array declaration by initializing the elements Array declaration by specifying the size and initializing elements Array declaration by specifying the size Syntax: int arr1[10]; // Array declaration by specifying size int n = 10; int arr2[n]; Note: With recent C/C++ versions, we can also declare an array of user-specified size Array declaration by initializing the elements int arr[] = {10, 20, 30, 40}; // Array declaration by initializing elements Compiler creates an array of size 4. This is same as “int arr[4] = {10, 20, 30, 40}” Array declaration by specifying the size and initializing elements Syntax: int arr[6] = {10, 20, 30, 40} ; // Array declaration by specifying size // and initializing elements Compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements as above is same as follows: int arr[] = {10, 20, 30, 40, 0, 0}" Note: In a static declaration, the memory will get allocated in the stack memory. Implementation: Below is the C program to demonstrate static declaration Example 1: C // C Program to Implement Static Declaration // Importing standard input output operations file#include <stdio.h> // Main driver methodint main(){ // Static declaration of array so it // will get memory in Stack memory int first_array[2]; // Assign value 10 first_array[0] = 10; // Assign value 20 first_array[1] = 20; // Printing value printf("%d %d", first_array[0], first_array[1]); return 0;} 10 20 Dynamic declaration: Malloc is used for dynamically allocating an array. In this situation, the memory will be allocated in heap. Allocated memory will get free after completion of the program. Example 2: C // C program to implement Dynamic Memory Allocation// using Malloc // Importing standard input output files#include<stdio.h>// Include this library for malloc#include<stdlib.h> // Main driver methodint main(){ // Memory will get allocated in Heap and // RHS is implicitly typecasted to integer as // LHS is having integer as a return type int *first_array = (int*)malloc(sizeof(int)*2); // Creating and initializing array // Custom integer values on indices as specified first_array[0] = 10; first_array[1] = 20; // Printing elements of both the arrays printf("%d %d", first_array[0], first_array[1]); return 0;} 10 20 Now coming to the eccentric goal in figuring an alternative way to allocate the memory instead of Dynamic declaration Example 3: C // C Program to implement Alternative to Malloc // Importing standard input output file#include<stdio.h> // Main driver methodint main(){ // Alternative of Malloc '*' operator refers // to address of array memory block int *first_array = (int[2]){}; // Creating and initializing array together // Custom input element at array indices first_array[0] = 10; first_array[1] = 20; // Printing the array indices as passed in argument printf("%d %d", first_array[0], first_array[1]); return 0;} 10 20 surindertarika1234 kashishsoda simranarora5sos C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Multithreading in C Exception Handling in C++ Arrow operator -> in C/C++ with Examples 'this' pointer in C++ UDP Server-Client implementation in C Understanding "extern" keyword in C Smart Pointers in C++ and How to Use Them Multiple Inheritance in C++ How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 24208, "s": 24180, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24750, "s": 24208, "text": "An array in C or C++ is a collection of items stored at contiguous memory locations and elements can be accessed randomly using indices of an array. They are used for storing similar types of elements as the data type must be the same for all elements. They can be used to store the collection of primitive data types such as int, float, double, char, etc of any particular type. To add to it, an array in C or C++ can store derived data types such as the structures, pointers, etc. Given below is the picturesque representation of an array." }, { "code": null, "e": 24827, "s": 24750, "text": "There are two types of array/ string declaration in C++ as listed as follows" }, { "code": null, "e": 24865, "s": 24827, "text": "Static DeclarationDynamic Declaration" }, { "code": null, "e": 24884, "s": 24865, "text": "Static Declaration" }, { "code": null, "e": 24904, "s": 24884, "text": "Dynamic Declaration" }, { "code": null, "e": 24930, "s": 24904, "text": "Way 1: Static Declaration" }, { "code": null, "e": 24984, "s": 24930, "text": "Methods: The static declaration can be done in 3 ways" }, { "code": null, "e": 25025, "s": 24984, "text": "Array declaration by specifying the size" }, { "code": null, "e": 25072, "s": 25025, "text": "Array declaration by initializing the elements" }, { "code": null, "e": 25139, "s": 25072, "text": "Array declaration by specifying the size and initializing elements" }, { "code": null, "e": 25180, "s": 25139, "text": "Array declaration by specifying the size" }, { "code": null, "e": 25188, "s": 25180, "text": "Syntax:" }, { "code": null, "e": 25242, "s": 25188, "text": "int arr1[10];\n// Array declaration by specifying size" }, { "code": null, "e": 25267, "s": 25242, "text": "int n = 10;\nint arr2[n];" }, { "code": null, "e": 25353, "s": 25267, "text": "Note: With recent C/C++ versions, we can also declare an array of user-specified size" }, { "code": null, "e": 25400, "s": 25353, "text": "Array declaration by initializing the elements" }, { "code": null, "e": 25476, "s": 25400, "text": "int arr[] = {10, 20, 30, 40};\n// Array declaration by initializing elements" }, { "code": null, "e": 25561, "s": 25476, "text": "Compiler creates an array of size 4. This is same as “int arr[4] = {10, 20, 30, 40}”" }, { "code": null, "e": 25628, "s": 25561, "text": "Array declaration by specifying the size and initializing elements" }, { "code": null, "e": 25636, "s": 25628, "text": "Syntax:" }, { "code": null, "e": 25737, "s": 25636, "text": "int arr[6] = {10, 20, 30, 40} ;\n// Array declaration by specifying size\n// and initializing elements" }, { "code": null, "e": 25875, "s": 25737, "text": "Compiler creates an array of size 6, initializes first 4 elements as specified by user and rest two elements as above is same as follows:" }, { "code": null, "e": 25911, "s": 25875, "text": "int arr[] = {10, 20, 30, 40, 0, 0}\"" }, { "code": null, "e": 25993, "s": 25911, "text": "Note: In a static declaration, the memory will get allocated in the stack memory." }, { "code": null, "e": 26066, "s": 25993, "text": "Implementation: Below is the C program to demonstrate static declaration" }, { "code": null, "e": 26077, "s": 26066, "text": "Example 1:" }, { "code": null, "e": 26079, "s": 26077, "text": "C" }, { "code": "// C Program to Implement Static Declaration // Importing standard input output operations file#include <stdio.h> // Main driver methodint main(){ // Static declaration of array so it // will get memory in Stack memory int first_array[2]; // Assign value 10 first_array[0] = 10; // Assign value 20 first_array[1] = 20; // Printing value printf(\"%d %d\", first_array[0], first_array[1]); return 0;}", "e": 26512, "s": 26079, "text": null }, { "code": null, "e": 26518, "s": 26512, "text": "10 20" }, { "code": null, "e": 26712, "s": 26518, "text": "Dynamic declaration: Malloc is used for dynamically allocating an array. In this situation, the memory will be allocated in heap. Allocated memory will get free after completion of the program." }, { "code": null, "e": 26723, "s": 26712, "text": "Example 2:" }, { "code": null, "e": 26725, "s": 26723, "text": "C" }, { "code": "// C program to implement Dynamic Memory Allocation// using Malloc // Importing standard input output files#include<stdio.h>// Include this library for malloc#include<stdlib.h> // Main driver methodint main(){ // Memory will get allocated in Heap and // RHS is implicitly typecasted to integer as // LHS is having integer as a return type int *first_array = (int*)malloc(sizeof(int)*2); // Creating and initializing array // Custom integer values on indices as specified first_array[0] = 10; first_array[1] = 20; // Printing elements of both the arrays printf(\"%d %d\", first_array[0], first_array[1]); return 0;}", "e": 27376, "s": 26725, "text": null }, { "code": null, "e": 27382, "s": 27376, "text": "10 20" }, { "code": null, "e": 27500, "s": 27382, "text": "Now coming to the eccentric goal in figuring an alternative way to allocate the memory instead of Dynamic declaration" }, { "code": null, "e": 27511, "s": 27500, "text": "Example 3:" }, { "code": null, "e": 27513, "s": 27511, "text": "C" }, { "code": "// C Program to implement Alternative to Malloc // Importing standard input output file#include<stdio.h> // Main driver methodint main(){ // Alternative of Malloc '*' operator refers // to address of array memory block int *first_array = (int[2]){}; // Creating and initializing array together // Custom input element at array indices first_array[0] = 10; first_array[1] = 20; // Printing the array indices as passed in argument printf(\"%d %d\", first_array[0], first_array[1]); return 0;}", "e": 28038, "s": 27513, "text": null }, { "code": null, "e": 28044, "s": 28038, "text": "10 20" }, { "code": null, "e": 28063, "s": 28044, "text": "surindertarika1234" }, { "code": null, "e": 28075, "s": 28063, "text": "kashishsoda" }, { "code": null, "e": 28091, "s": 28075, "text": "simranarora5sos" }, { "code": null, "e": 28102, "s": 28091, "text": "C Language" }, { "code": null, "e": 28200, "s": 28102, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28238, "s": 28200, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28258, "s": 28238, "text": "Multithreading in C" }, { "code": null, "e": 28284, "s": 28258, "text": "Exception Handling in C++" }, { "code": null, "e": 28325, "s": 28284, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28347, "s": 28325, "text": "'this' pointer in C++" }, { "code": null, "e": 28385, "s": 28347, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28421, "s": 28385, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 28463, "s": 28421, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 28491, "s": 28463, "text": "Multiple Inheritance in C++" } ]
Setup your home JupyterHub on a Raspberry Pi | by Gerold Busch | Towards Data Science
As a data scientist, I use Jupyter notebooks on a daily basis. Sometimes locally on my notebook, sometimes on a server through JupyterHub. But why not combine both and run a JupyterHub on a Raspberry Pi? This way everyone in the household can start a notebook from every device with a browser. The data always stays home and as Raspberry Pis become more and more powerful, we can actually do real data science on it. Prepare Python environmentInstall JupyterHubSet up as a system serviceUse JupyterLabInstall Python LibrariesUser Management Prepare Python environment Install JupyterHub Set up as a system service Use JupyterLab Install Python Libraries User Management There are many articles out there that describe how to set up JupyterHub, most of them, however, use Anaconda. Unfortunately, Anaconda does not support ARM-systems like the Raspberry Pi and Miniconda, that is often suggested as an alternative, is apparently not further maintained. So let’s go with pip. Did I do something wrong? When I typed “python” in my fresh Raspbian Buster installation, it opened “python2”. Seriously? Isn’t it 2020? So let’s quickly redirect the system to python3: sudo rm /usr/bin/python sudo ln -s /usr/bin/python3 /usr/bin/python and install the python package manager pip: sudo apt-get update sudo apt-get install python3-pip sudo pip3 install --upgrade pip JupyterHub consists of three components: A single-user notebook server that is started for every user on the system when they log in. This is basically what you have installed on your laptop and start with jupyter notebook. The hub that manages the user accounts, authentication and coordinates the single-user notebook servers. A proxy that routes the user requests to the hub and the notebook servers. Accordingly, we need to install these three components. Let’s start with the proxy: sudo apt-get install npm sudo npm install -g configurable-http-proxy Now, we can install JupyterHub and Jupyter Notebook using pip. Since we want to use JupyterHub for multiple users, we need to make sure that the installation is system-wide: sudo -H pip3 install notebook jupyterhub JupyterHub is configured using a python script. You can generate the template using the following command. Afterwards, move it to a location outside your home directory: jupyterhub --generate-config sudo mv jupyterhub_config.py /root In the following steps, when we make changes in the config file, we need to modify this file /root/jupyterhub_config.py. Since it is located in /root, we need to use sudo. For example, by default JupyterHub runs on port 8000. Maybe we already have this port in use, so let’s change it to 8888. For that uncomment the following statement in the config-file and adjust the port: c.JupyterHub.bind_url = 'http://:8888' Our JupyterHub is now ready to go. We could start it with jupyterhub -f /root/jupyterhub_config.py & (where -f points to the config file we just created). However, the hub would only survive until the next restart of the system. Fine for a first try but if we use it on a regular basis, it is certainly better to set up JupyterHub as a system service so that it is automatically launched at system start. To register JupyterHub as a system service, create the file /lib/systemd/system/jupyterhub.service and fill it with: [Unit] Description=JupyterHub Service After=multi-user.target [Service] User=root ExecStart=/usr/local/bin/jupyterhub --config=/root/jupyterhub_config.py Restart=on-failure [Install] WantedBy=multi-user.target Make sure that the line starting with ExecStart contains the correct location of the JupyterHub binary and the config-file or adjust accordingly. Afterwards, run the following commands: sudo systemctl daemon-reload sudo systemctl start jupyterhub sudo systemctl enable jupyterhub sudo systemctl status jupyterhub.service JupyterHub will now launch at system start. The last command shows you the status which is hopefully “active (running)”. If this is the case, go to http://<address of your raspi>:8888. You should see the login page of your JupyterHub. Every system user of the Raspberry Pi can now log in and launch their own notebook server! JupyterLab is the next-generation web-based user interface for Project Jupyter. It allows you to work with documents and notebooks in a very flexible manner. If you are not convinced yet: It even has a dark mode... To use JupyterLab instead of the traditional notebooks, we first have to install it using pip and then enable the extension (use sudo to do it systemwide): sudo -H pip3 install jupyterlab sudo jupyter serverextension enable --py jupyterlab --system Now, we have to add (or uncomment and adjust the respective line) the following in the config-file: c.Spawner.default_url = '/user/:username/lab' To do actual data science, we will certainly need a bit more than just the python standard library. We have essentially two possibilities: We can install them system-wide. Alternatively, every user can install them in their home directory. A reasonable approach would be to install the most often used packages system-wide and let the users install everything else on their own. As an example here is how to install numpy system-wide. For numpy to work, you will also have to install the following system package: sudo apt-get install libatlas-base-dev sudo -H pip3 install numpy Users without sudo-rights can install packages in their home directory with, for example: pip3 install seaborn You can actually open a terminal from within JupyterLab, so there is no need to set up a ssh-connection for “normal” users. Just go to the launcher window and open a terminal. In our current setup, users are managed by the operating system. This means every user of the Raspberry Pi can also start their own notebook server. Admins have additional rights. For example, they can access the Admin Panel from where they can see which users are logged in and start and stop their servers. Admin rights are handled through groups. For example, if we wanted to nominate the user “gerold” as admin, we would first create a group (we could also use a pre-existing one) and add the user to it. This is done as usual in Unix-systems: sudo addgroup jupyter_admin sudo usermod -aG jupyter_admin gerold Then, we need to add this group as an admin-group in the config-file: c.PAMAuthenticator.admin_groups = {'jupyter_admin'} The admin panel can be reached under http://<address of your raspi>:8888/hub/admin .
[ { "code": null, "e": 588, "s": 171, "text": "As a data scientist, I use Jupyter notebooks on a daily basis. Sometimes locally on my notebook, sometimes on a server through JupyterHub. But why not combine both and run a JupyterHub on a Raspberry Pi? This way everyone in the household can start a notebook from every device with a browser. The data always stays home and as Raspberry Pis become more and more powerful, we can actually do real data science on it." }, { "code": null, "e": 712, "s": 588, "text": "Prepare Python environmentInstall JupyterHubSet up as a system serviceUse JupyterLabInstall Python LibrariesUser Management" }, { "code": null, "e": 739, "s": 712, "text": "Prepare Python environment" }, { "code": null, "e": 758, "s": 739, "text": "Install JupyterHub" }, { "code": null, "e": 785, "s": 758, "text": "Set up as a system service" }, { "code": null, "e": 800, "s": 785, "text": "Use JupyterLab" }, { "code": null, "e": 825, "s": 800, "text": "Install Python Libraries" }, { "code": null, "e": 841, "s": 825, "text": "User Management" }, { "code": null, "e": 1145, "s": 841, "text": "There are many articles out there that describe how to set up JupyterHub, most of them, however, use Anaconda. Unfortunately, Anaconda does not support ARM-systems like the Raspberry Pi and Miniconda, that is often suggested as an alternative, is apparently not further maintained. So let’s go with pip." }, { "code": null, "e": 1331, "s": 1145, "text": "Did I do something wrong? When I typed “python” in my fresh Raspbian Buster installation, it opened “python2”. Seriously? Isn’t it 2020? So let’s quickly redirect the system to python3:" }, { "code": null, "e": 1399, "s": 1331, "text": "sudo rm /usr/bin/python sudo ln -s /usr/bin/python3 /usr/bin/python" }, { "code": null, "e": 1443, "s": 1399, "text": "and install the python package manager pip:" }, { "code": null, "e": 1528, "s": 1443, "text": "sudo apt-get update sudo apt-get install python3-pip sudo pip3 install --upgrade pip" }, { "code": null, "e": 1569, "s": 1528, "text": "JupyterHub consists of three components:" }, { "code": null, "e": 1752, "s": 1569, "text": "A single-user notebook server that is started for every user on the system when they log in. This is basically what you have installed on your laptop and start with jupyter notebook." }, { "code": null, "e": 1857, "s": 1752, "text": "The hub that manages the user accounts, authentication and coordinates the single-user notebook servers." }, { "code": null, "e": 1932, "s": 1857, "text": "A proxy that routes the user requests to the hub and the notebook servers." }, { "code": null, "e": 2016, "s": 1932, "text": "Accordingly, we need to install these three components. Let’s start with the proxy:" }, { "code": null, "e": 2085, "s": 2016, "text": "sudo apt-get install npm sudo npm install -g configurable-http-proxy" }, { "code": null, "e": 2259, "s": 2085, "text": "Now, we can install JupyterHub and Jupyter Notebook using pip. Since we want to use JupyterHub for multiple users, we need to make sure that the installation is system-wide:" }, { "code": null, "e": 2300, "s": 2259, "text": "sudo -H pip3 install notebook jupyterhub" }, { "code": null, "e": 2470, "s": 2300, "text": "JupyterHub is configured using a python script. You can generate the template using the following command. Afterwards, move it to a location outside your home directory:" }, { "code": null, "e": 2534, "s": 2470, "text": "jupyterhub --generate-config sudo mv jupyterhub_config.py /root" }, { "code": null, "e": 2706, "s": 2534, "text": "In the following steps, when we make changes in the config file, we need to modify this file /root/jupyterhub_config.py. Since it is located in /root, we need to use sudo." }, { "code": null, "e": 2911, "s": 2706, "text": "For example, by default JupyterHub runs on port 8000. Maybe we already have this port in use, so let’s change it to 8888. For that uncomment the following statement in the config-file and adjust the port:" }, { "code": null, "e": 2950, "s": 2911, "text": "c.JupyterHub.bind_url = 'http://:8888'" }, { "code": null, "e": 3355, "s": 2950, "text": "Our JupyterHub is now ready to go. We could start it with jupyterhub -f /root/jupyterhub_config.py & (where -f points to the config file we just created). However, the hub would only survive until the next restart of the system. Fine for a first try but if we use it on a regular basis, it is certainly better to set up JupyterHub as a system service so that it is automatically launched at system start." }, { "code": null, "e": 3472, "s": 3355, "text": "To register JupyterHub as a system service, create the file /lib/systemd/system/jupyterhub.service and fill it with:" }, { "code": null, "e": 3684, "s": 3472, "text": "[Unit] Description=JupyterHub Service After=multi-user.target [Service] User=root ExecStart=/usr/local/bin/jupyterhub --config=/root/jupyterhub_config.py Restart=on-failure [Install] WantedBy=multi-user.target" }, { "code": null, "e": 3830, "s": 3684, "text": "Make sure that the line starting with ExecStart contains the correct location of the JupyterHub binary and the config-file or adjust accordingly." }, { "code": null, "e": 3870, "s": 3830, "text": "Afterwards, run the following commands:" }, { "code": null, "e": 4005, "s": 3870, "text": "sudo systemctl daemon-reload sudo systemctl start jupyterhub sudo systemctl enable jupyterhub sudo systemctl status jupyterhub.service" }, { "code": null, "e": 4126, "s": 4005, "text": "JupyterHub will now launch at system start. The last command shows you the status which is hopefully “active (running)”." }, { "code": null, "e": 4331, "s": 4126, "text": "If this is the case, go to http://<address of your raspi>:8888. You should see the login page of your JupyterHub. Every system user of the Raspberry Pi can now log in and launch their own notebook server!" }, { "code": null, "e": 4546, "s": 4331, "text": "JupyterLab is the next-generation web-based user interface for Project Jupyter. It allows you to work with documents and notebooks in a very flexible manner. If you are not convinced yet: It even has a dark mode..." }, { "code": null, "e": 4702, "s": 4546, "text": "To use JupyterLab instead of the traditional notebooks, we first have to install it using pip and then enable the extension (use sudo to do it systemwide):" }, { "code": null, "e": 4796, "s": 4702, "text": "sudo -H pip3 install jupyterlab sudo jupyter serverextension enable --py jupyterlab --system" }, { "code": null, "e": 4896, "s": 4796, "text": "Now, we have to add (or uncomment and adjust the respective line) the following in the config-file:" }, { "code": null, "e": 4942, "s": 4896, "text": "c.Spawner.default_url = '/user/:username/lab'" }, { "code": null, "e": 5182, "s": 4942, "text": "To do actual data science, we will certainly need a bit more than just the python standard library. We have essentially two possibilities: We can install them system-wide. Alternatively, every user can install them in their home directory." }, { "code": null, "e": 5456, "s": 5182, "text": "A reasonable approach would be to install the most often used packages system-wide and let the users install everything else on their own. As an example here is how to install numpy system-wide. For numpy to work, you will also have to install the following system package:" }, { "code": null, "e": 5522, "s": 5456, "text": "sudo apt-get install libatlas-base-dev sudo -H pip3 install numpy" }, { "code": null, "e": 5612, "s": 5522, "text": "Users without sudo-rights can install packages in their home directory with, for example:" }, { "code": null, "e": 5633, "s": 5612, "text": "pip3 install seaborn" }, { "code": null, "e": 5809, "s": 5633, "text": "You can actually open a terminal from within JupyterLab, so there is no need to set up a ssh-connection for “normal” users. Just go to the launcher window and open a terminal." }, { "code": null, "e": 5958, "s": 5809, "text": "In our current setup, users are managed by the operating system. This means every user of the Raspberry Pi can also start their own notebook server." }, { "code": null, "e": 6357, "s": 5958, "text": "Admins have additional rights. For example, they can access the Admin Panel from where they can see which users are logged in and start and stop their servers. Admin rights are handled through groups. For example, if we wanted to nominate the user “gerold” as admin, we would first create a group (we could also use a pre-existing one) and add the user to it. This is done as usual in Unix-systems:" }, { "code": null, "e": 6423, "s": 6357, "text": "sudo addgroup jupyter_admin sudo usermod -aG jupyter_admin gerold" }, { "code": null, "e": 6493, "s": 6423, "text": "Then, we need to add this group as an admin-group in the config-file:" }, { "code": null, "e": 6545, "s": 6493, "text": "c.PAMAuthenticator.admin_groups = {'jupyter_admin'}" } ]
read() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint #include <unistd.h> ssize_t read(int fd, void *buf, size_t count); ssize_t read(int fd, void *buf, size_t count); If count is zero, read() returns zero and has no other results. If count is greater than SSIZE_MAX, the result is unspecified. Many filesystems and disks were considered to be fast enough that the implementation of O_NONBLOCK was deemed unnecessary. So, O_NONBLOCK may not be available on files and/or disks. close (2) close (2) fcntl (2) fcntl (2) ioctl (2) ioctl (2) lseek (2) lseek (2) open (2) open (2) pread (2) pread (2) readdir (2) readdir (2) readlink (2) readlink (2) readv (2) readv (2) select (2) select (2) write (2) write (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2390, "s": 2319, "text": "#include <unistd.h> \n\nssize_t read(int fd, void *buf, size_t count); \n" }, { "code": null, "e": 2440, "s": 2390, "text": "\nssize_t read(int fd, void *buf, size_t count); \n" }, { "code": null, "e": 2569, "s": 2440, "text": "\nIf\ncount is zero, read() returns zero and has no other results.\nIf\ncount is greater than SSIZE_MAX, the result is unspecified.\n" }, { "code": null, "e": 2755, "s": 2571, "text": "\nMany filesystems and disks were considered to be fast enough that the\nimplementation of\nO_NONBLOCK was deemed unnecessary. So, O_NONBLOCK may not be available on files\nand/or disks.\n" }, { "code": null, "e": 2765, "s": 2755, "text": "close (2)" }, { "code": null, "e": 2775, "s": 2765, "text": "close (2)" }, { "code": null, "e": 2785, "s": 2775, "text": "fcntl (2)" }, { "code": null, "e": 2795, "s": 2785, "text": "fcntl (2)" }, { "code": null, "e": 2805, "s": 2795, "text": "ioctl (2)" }, { "code": null, "e": 2815, "s": 2805, "text": "ioctl (2)" }, { "code": null, "e": 2825, "s": 2815, "text": "lseek (2)" }, { "code": null, "e": 2835, "s": 2825, "text": "lseek (2)" }, { "code": null, "e": 2844, "s": 2835, "text": "open (2)" }, { "code": null, "e": 2853, "s": 2844, "text": "open (2)" }, { "code": null, "e": 2863, "s": 2853, "text": "pread (2)" }, { "code": null, "e": 2873, "s": 2863, "text": "pread (2)" }, { "code": null, "e": 2885, "s": 2873, "text": "readdir (2)" }, { "code": null, "e": 2897, "s": 2885, "text": "readdir (2)" }, { "code": null, "e": 2910, "s": 2897, "text": "readlink (2)" }, { "code": null, "e": 2923, "s": 2910, "text": "readlink (2)" }, { "code": null, "e": 2933, "s": 2923, "text": "readv (2)" }, { "code": null, "e": 2943, "s": 2933, "text": "readv (2)" }, { "code": null, "e": 2954, "s": 2943, "text": "select (2)" }, { "code": null, "e": 2965, "s": 2954, "text": "select (2)" }, { "code": null, "e": 2975, "s": 2965, "text": "write (2)" }, { "code": null, "e": 2985, "s": 2975, "text": "write (2)" }, { "code": null, "e": 3002, "s": 2985, "text": "\nAdvertisements\n" }, { "code": null, "e": 3037, "s": 3002, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 3065, "s": 3037, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3099, "s": 3065, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3116, "s": 3099, "text": " Frahaan Hussain" }, { "code": null, "e": 3149, "s": 3116, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 3160, "s": 3149, "text": " Pradeep D" }, { "code": null, "e": 3195, "s": 3160, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3211, "s": 3195, "text": " Musab Zayadneh" }, { "code": null, "e": 3244, "s": 3211, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 3256, "s": 3244, "text": " GUHARAJANM" }, { "code": null, "e": 3288, "s": 3256, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 3296, "s": 3288, "text": " Uplatz" }, { "code": null, "e": 3303, "s": 3296, "text": " Print" }, { "code": null, "e": 3314, "s": 3303, "text": " Add Notes" } ]
crypto.pbkdf2() Method in Node.js
The crypto.pbkdf2(), also known as Password-Based Key Derivation function, provides an asynchronous implementation of the derivative function. A key is derived by using the Hmac digest of a specified algorithm from password, salt and iterations crypto.createHmac(algorithm, key, [options]) The above parameters are described as below − password – Password defined for getting key of the requested byte length. Possible values are of type string, DataView, Buffer, etc. password – Password defined for getting key of the requested byte length. Possible values are of type string, DataView, Buffer, etc. salt – Similar to password for getting the key. Possible values are of type string, DataView, Buffer, etc. salt – Similar to password for getting the key. Possible values are of type string, DataView, Buffer, etc. iterations – Getting the desired key of requested byte length. It accepts the value as number. iterations – Getting the desired key of requested byte length. It accepts the value as number. keylen – This is the requested byte length of the key. It is of type number. keylen – This is the requested byte length of the key. It is of type number. digest – The Hmac algorithm is specified by this digest value. Default value is 'sha1' digest – The Hmac algorithm is specified by this digest value. Default value is 'sha1' callback – If any error occurs in the async mode, it will be handled in the callback callback – If any error occurs in the async mode, it will be handled in the callback Create a file with name – pbkdf2.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below − node pbkdf2.js pbkdf2.js Live Demo // crypto.pbkdf2() demo example // Importing the crypto module const crypto = require('crypto'); // Defining the pbkdf2 with the following options crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; // Printing the derived key console.log("Key Derived: ",derivedKey.toString('hex')); }); C:\home\node>> node pbkdf2.js Key Derived: 3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e8 27304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae Let's take a look at one more example. Live Demo // crypto.pbkdf2() demo example // Importing the crypto module const crypto = require('crypto'); // Defining the pbkdf2 with the following options crypto.pbkdf2('secret', 'salt', 100, 64, 'sha1', (err, derivedKey) => { if (err) throw err; // Printing the derived key console.log("Key Derived: ",derivedKey); console.log("Key Derived in hex: ",derivedKey.toString('hex')); console.log("Key Derived in base64: ",derivedKey.toString('base64')); }); C:\home\node>> node pbkdf2.js Key Derived: <Buffer b7 36 35 f7 c0 88 2e 1f c3 ba 6e 29 b1 4a f1 27 4d f8 48 28 b4 d1 8f cc 22 2e b5 74 45 5f 50 5d 3d 23 19 13 2d 84 e1 91 a7 83 e2 00 73 4e 37 4a 24 b6 ... > Key Derived in hex: b73635f7c0882e1fc3ba6e29b14af1274df84828b4d18fcc222eb574455f505d3d2319132d84e1 91a783e200734e374a24b62cfab65dfb5e9dc28ae147072419 Key Derived in base64: tzY198CILh/Dum4psUrxJ034SCi00Y/MIi61dEVfUF09IxkTLYThkaeD4gBzTjdKJLYs+rZd+16dwo rhRwckGQ==
[ { "code": null, "e": 1307, "s": 1062, "text": "The crypto.pbkdf2(), also known as Password-Based Key Derivation function, provides an asynchronous implementation of the derivative function. A key is derived by using the Hmac digest of a specified algorithm from password, salt and iterations" }, { "code": null, "e": 1352, "s": 1307, "text": "crypto.createHmac(algorithm, key, [options])" }, { "code": null, "e": 1398, "s": 1352, "text": "The above parameters are described as below −" }, { "code": null, "e": 1531, "s": 1398, "text": "password – Password defined for getting key of the requested byte length. Possible values are of type string, DataView, Buffer, etc." }, { "code": null, "e": 1664, "s": 1531, "text": "password – Password defined for getting key of the requested byte length. Possible values are of type string, DataView, Buffer, etc." }, { "code": null, "e": 1771, "s": 1664, "text": "salt – Similar to password for getting the key. Possible values are of type string, DataView, Buffer, etc." }, { "code": null, "e": 1878, "s": 1771, "text": "salt – Similar to password for getting the key. Possible values are of type string, DataView, Buffer, etc." }, { "code": null, "e": 1973, "s": 1878, "text": "iterations – Getting the desired key of requested byte length. It accepts the value as number." }, { "code": null, "e": 2068, "s": 1973, "text": "iterations – Getting the desired key of requested byte length. It accepts the value as number." }, { "code": null, "e": 2145, "s": 2068, "text": "keylen – This is the requested byte length of the key. It is of type number." }, { "code": null, "e": 2222, "s": 2145, "text": "keylen – This is the requested byte length of the key. It is of type number." }, { "code": null, "e": 2309, "s": 2222, "text": "digest – The Hmac algorithm is specified by this digest value. Default value is 'sha1'" }, { "code": null, "e": 2396, "s": 2309, "text": "digest – The Hmac algorithm is specified by this digest value. Default value is 'sha1'" }, { "code": null, "e": 2481, "s": 2396, "text": "callback – If any error occurs in the async mode, it will be handled in the callback" }, { "code": null, "e": 2566, "s": 2481, "text": "callback – If any error occurs in the async mode, it will be handled in the callback" }, { "code": null, "e": 2731, "s": 2566, "text": "Create a file with name – pbkdf2.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −" }, { "code": null, "e": 2746, "s": 2731, "text": "node pbkdf2.js" }, { "code": null, "e": 2756, "s": 2746, "text": "pbkdf2.js" }, { "code": null, "e": 2767, "s": 2756, "text": " Live Demo" }, { "code": null, "e": 3111, "s": 2767, "text": "// crypto.pbkdf2() demo example\n\n// Importing the crypto module\nconst crypto = require('crypto');\n\n// Defining the pbkdf2 with the following options\ncrypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n // Printing the derived key\n console.log(\"Key Derived: \",derivedKey.toString('hex'));\n});" }, { "code": null, "e": 3284, "s": 3111, "text": "C:\\home\\node>> node pbkdf2.js\nKey Derived:\n3745e482c6e0ade35da10139e797157f4a5da669dad7d5da88ef87e47471cc47ed941c7ad618e8\n27304f083f8707f12b7cfdd5f489b782f10cc269e3c08d59ae" }, { "code": null, "e": 3323, "s": 3284, "text": "Let's take a look at one more example." }, { "code": null, "e": 3334, "s": 3323, "text": " Live Demo" }, { "code": null, "e": 3797, "s": 3334, "text": "// crypto.pbkdf2() demo example\n\n// Importing the crypto module\nconst crypto = require('crypto');\n\n// Defining the pbkdf2 with the following options\ncrypto.pbkdf2('secret', 'salt', 100, 64, 'sha1', (err, derivedKey) => {\n if (err) throw err;\n // Printing the derived key\n console.log(\"Key Derived: \",derivedKey);\n console.log(\"Key Derived in hex: \",derivedKey.toString('hex'));\n console.log(\"Key Derived in base64: \",derivedKey.toString('base64'));\n});" }, { "code": null, "e": 4267, "s": 3797, "text": "C:\\home\\node>> node pbkdf2.js\nKey Derived: <Buffer b7 36 35 f7 c0 88 2e 1f c3 ba 6e 29 b1 4a f1 27 4d f8 48 28 b4 d1 8f cc 22 2e b5 74 45 5f 50 5d 3d 23 19 13 2d 84 e1 91 a7 83 e2 00 73 4e 37 4a 24 b6 ... >\nKey Derived in hex:\nb73635f7c0882e1fc3ba6e29b14af1274df84828b4d18fcc222eb574455f505d3d2319132d84e1\n91a783e200734e374a24b62cfab65dfb5e9dc28ae147072419\nKey Derived in base64:\ntzY198CILh/Dum4psUrxJ034SCi00Y/MIi61dEVfUF09IxkTLYThkaeD4gBzTjdKJLYs+rZd+16dwo\nrhRwckGQ==" } ]
Third largest element | Practice | GeeksforGeeks
Given an array of distinct elements. Find the third largest element in it. Suppose you have A[] = {1, 2, 3, 4, 5, 6, 7}, its output will be 5 because it is the 3 largest element in the array A. Example 1: Input: N = 5 A[] = {2,4,1,3,5} Output: 3 Example 2: Input: N = 2 A[] = {10,2} Output: -1 Your Task: Complete the function thirdLargest() which takes the array a[] and the size of the array, n, as input parameters and returns the third largest element in the array. It return -1 if there are less than 3 elements in the given array. Expected Time Complexity: O(N) Expected Auxiliary Space: O(1) Constraints: 1 ≤ N ≤ 105 1 ≤ A[i] ≤ 105 -2 nikhilravi562 days ago O(1) solution class Solution{ int thirdLargest(int a[], int n) { // Your code here if(n<3) return -1; Arrays.sort(a); return a[n-3]; }} -1 manishamali3 days ago int thirdLargest(int a[], int n) { //Your code here sort(a,a+n); return a[n-3]; } +2 goyalharshit1505 days ago int thirdLargest(int a[], int n) { int m1 = a[0], m2=INT_MIN, m3=INT_MIN; for(int i=1;i<n;i++){ if(a[i]>m1){ m3= m2; m2=m1; m1 = a[i]; }else if(a[i]>m2 && a[i]<m1){ m3 = m2; m2 = a[i]; }else if(a[i] > m3) { m3 = a[i]; } } return m3; } +1 rockachi6 days ago Code Works for Distinct Elements:- int thirdLargest(int a[], int n) { //Your code here if(n<3) return -1; int max1=a[0]; for(int i=1;i<n;i++){ if(a[i]>max1) max1=a[i]; } int max2=0; for(int i=0;i<n;i++){ if((a[i]!=max1)&&(a[i]>max2 )) max2=a[i]; } int max3=0; for(int i=0;i<n;i++){ if((a[i]!=max1)&&(a[i]!=max2 )&&(a[i]>max3)) max3=a[i]; } return max3; } Code Works For Duplicate Elements also:- int thirdLargest(int a[], int n) { int temp=0; for(int j=0;j<n-2;j++) { for(int i=0;i<n-1;i++) { if(a[i]>a[i+1]) { temp=a[i]; a[i] = a[i+1]; a[i+1]=temp; } } } return a[n-3]; } 0 theayushsrivastava1 week ago Java Solution Time Complexity: O(n) int thirdLargest(int a[], int n) { // Your code here if(n<3){ return -1; } int f=a[0]; int s=Integer.MIN_VALUE; int t=Integer.MIN_VALUE; for(int i=1;i<n;i++){ if(a[i]>f){ t=s; s=f; f=a[i]; } else if(a[i]>s && a[i]<f){ t=s; s=a[i]; } else if(a[i]>t){ t=a[i]; } } return t; } 0 thecipher1 week ago 0 thecipher1 week ago int thirdLargest(int a[], int n) { sort(a,a+n); for(int i=0;i<n;i++) { return a[n-3]; } return -1; } but i need the solution in O(n) +1 shubhisharma1 week ago JAVA : static int thirdLargest(int a[], int n) { // Your code here if(n<3) { return -1; } else { sort(a,n); return a[n-3]; } } static int[] sort(int a[], int n) { int temp=0; for(int j=0;j<n-2;j++) { for(int i=0;i<n-1;i++) { if(a[i]>a[i+1]) { temp=a[i]; a[i] = a[i+1]; a[i+1]=temp; } } } return a; } 0 krdmicrosoft2 weeks ago In question, they have specified that Its array of distinct elements, but in test cases they give duplicate elements. because my code fails .😿 class Solution { int thirdLargest(int a[], int n) { // Your code here if(n<3) return -1; int max = Integer.MIN_VALUE; for(int i = 0;i< n;i++) { if(a[i]>max) max = a[i]; } int secMax = Integer.MIN_VALUE; for(int i = 0;i< n;i++) { if(a[i]>secMax && a[i]<max) secMax = a[i]; } int thdMax = Integer.MIN_VALUE; for(int i = 0;i< n;i++) { if(a[i]>thdMax && a[i]<secMax) thdMax = a[i]; } return thdMax; } } 0 anu1492642 weeks ago JAVA SOLUTION.............. class Solution{ int thirdLargest(int a[], int n) { // Your code here if(n <= 2){ return -1; } Arrays.sort(a); return a[n-3]; }} 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": 366, "s": 290, "text": "Given an array of distinct elements. Find the third largest element in it. " }, { "code": null, "e": 485, "s": 366, "text": "Suppose you have A[] = {1, 2, 3, 4, 5, 6, 7}, its output will be 5 because it is the 3 largest element in the array A." }, { "code": null, "e": 496, "s": 485, "text": "Example 1:" }, { "code": null, "e": 538, "s": 496, "text": "Input:\nN = 5\nA[] = {2,4,1,3,5}\nOutput: 3\n" }, { "code": null, "e": 549, "s": 538, "text": "Example 2:" }, { "code": null, "e": 586, "s": 549, "text": "Input:\nN = 2\nA[] = {10,2}\nOutput: -1" }, { "code": null, "e": 829, "s": 586, "text": "Your Task:\nComplete the function thirdLargest() which takes the array a[] and the size of the array, n, as input parameters and returns the third largest element in the array. It return -1 if there are less than 3 elements in the given array." }, { "code": null, "e": 891, "s": 829, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 931, "s": 891, "text": "Constraints:\n1 ≤ N ≤ 105\n1 ≤ A[i] ≤ 105" }, { "code": null, "e": 934, "s": 931, "text": "-2" }, { "code": null, "e": 957, "s": 934, "text": "nikhilravi562 days ago" }, { "code": null, "e": 971, "s": 957, "text": "O(1) solution" }, { "code": null, "e": 1126, "s": 973, "text": "class Solution{ int thirdLargest(int a[], int n) { // Your code here if(n<3) return -1; Arrays.sort(a); return a[n-3]; }}" }, { "code": null, "e": 1129, "s": 1126, "text": "-1" }, { "code": null, "e": 1151, "s": 1129, "text": "manishamali3 days ago" }, { "code": null, "e": 1266, "s": 1151, "text": "int thirdLargest(int a[], int n) { //Your code here sort(a,a+n); return a[n-3]; }" }, { "code": null, "e": 1269, "s": 1266, "text": "+2" }, { "code": null, "e": 1295, "s": 1269, "text": "goyalharshit1505 days ago" }, { "code": null, "e": 1696, "s": 1295, "text": "int thirdLargest(int a[], int n) { int m1 = a[0], m2=INT_MIN, m3=INT_MIN; for(int i=1;i<n;i++){ if(a[i]>m1){ m3= m2; m2=m1; m1 = a[i]; }else if(a[i]>m2 && a[i]<m1){ m3 = m2; m2 = a[i]; }else if(a[i] > m3) { m3 = a[i]; } } return m3; }" }, { "code": null, "e": 1699, "s": 1696, "text": "+1" }, { "code": null, "e": 1718, "s": 1699, "text": "rockachi6 days ago" }, { "code": null, "e": 1753, "s": 1718, "text": "Code Works for Distinct Elements:-" }, { "code": null, "e": 2177, "s": 1755, "text": "int thirdLargest(int a[], int n) { //Your code here if(n<3) return -1; int max1=a[0]; for(int i=1;i<n;i++){ if(a[i]>max1) max1=a[i]; } int max2=0; for(int i=0;i<n;i++){ if((a[i]!=max1)&&(a[i]>max2 )) max2=a[i]; } int max3=0; for(int i=0;i<n;i++){ if((a[i]!=max1)&&(a[i]!=max2 )&&(a[i]>max3)) max3=a[i]; } return max3; } " }, { "code": null, "e": 2218, "s": 2177, "text": "Code Works For Duplicate Elements also:-" }, { "code": null, "e": 2531, "s": 2225, "text": " int thirdLargest(int a[], int n) { int temp=0; for(int j=0;j<n-2;j++) { for(int i=0;i<n-1;i++) { if(a[i]>a[i+1]) { temp=a[i]; a[i] = a[i+1]; a[i+1]=temp; } } } return a[n-3]; }" }, { "code": null, "e": 2535, "s": 2533, "text": "0" }, { "code": null, "e": 2564, "s": 2535, "text": "theayushsrivastava1 week ago" }, { "code": null, "e": 2600, "s": 2564, "text": "Java Solution Time Complexity: O(n)" }, { "code": null, "e": 3145, "s": 2606, "text": "int thirdLargest(int a[], int n) { // Your code here if(n<3){ return -1; } int f=a[0]; int s=Integer.MIN_VALUE; int t=Integer.MIN_VALUE; for(int i=1;i<n;i++){ if(a[i]>f){ t=s; s=f; f=a[i]; } else if(a[i]>s && a[i]<f){ t=s; s=a[i]; } else if(a[i]>t){ t=a[i]; } } return t; }" }, { "code": null, "e": 3147, "s": 3145, "text": "0" }, { "code": null, "e": 3167, "s": 3147, "text": "thecipher1 week ago" }, { "code": null, "e": 3169, "s": 3167, "text": "0" }, { "code": null, "e": 3189, "s": 3169, "text": "thecipher1 week ago" }, { "code": null, "e": 3340, "s": 3189, "text": "int thirdLargest(int a[], int n) { sort(a,a+n); for(int i=0;i<n;i++) { return a[n-3]; } return -1; }" }, { "code": null, "e": 3372, "s": 3340, "text": "but i need the solution in O(n)" }, { "code": null, "e": 3375, "s": 3372, "text": "+1" }, { "code": null, "e": 3398, "s": 3375, "text": "shubhisharma1 week ago" }, { "code": null, "e": 3405, "s": 3398, "text": "JAVA :" }, { "code": null, "e": 3915, "s": 3407, "text": " static int thirdLargest(int a[], int n) { // Your code here if(n<3) { return -1; } else { sort(a,n); return a[n-3]; } } static int[] sort(int a[], int n) { int temp=0; for(int j=0;j<n-2;j++) { for(int i=0;i<n-1;i++) { if(a[i]>a[i+1]) { temp=a[i]; a[i] = a[i+1]; a[i+1]=temp; } } } return a; }" }, { "code": null, "e": 3917, "s": 3915, "text": "0" }, { "code": null, "e": 3941, "s": 3917, "text": "krdmicrosoft2 weeks ago" }, { "code": null, "e": 4084, "s": 3941, "text": "In question, they have specified that Its array of distinct elements, but in test cases they give duplicate elements. because my code fails .😿" }, { "code": null, "e": 4629, "s": 4086, "text": "class Solution\n{\n int thirdLargest(int a[], int n)\n {\n\t // Your code here\n\t \n\t if(n<3) return -1;\n\t int max = Integer.MIN_VALUE;\n\t for(int i = 0;i< n;i++)\n\t {\n\t if(a[i]>max) max = a[i];\n\t }\n\t int secMax = Integer.MIN_VALUE;\n\t \n\t for(int i = 0;i< n;i++)\n\t {\n\t if(a[i]>secMax && a[i]<max) secMax = a[i];\n\t }\n\t \n\t int thdMax = Integer.MIN_VALUE;\n\t for(int i = 0;i< n;i++)\n\t {\n\t if(a[i]>thdMax && a[i]<secMax) thdMax = a[i];\n\t }\n\t \n\t return thdMax;\n\t \n }\n}" }, { "code": null, "e": 4631, "s": 4629, "text": "0" }, { "code": null, "e": 4652, "s": 4631, "text": "anu1492642 weeks ago" }, { "code": null, "e": 4680, "s": 4652, "text": "JAVA SOLUTION.............." }, { "code": null, "e": 4838, "s": 4682, "text": "class Solution{ int thirdLargest(int a[], int n) { // Your code here if(n <= 2){ return -1; } Arrays.sort(a); return a[n-3]; }}" }, { "code": null, "e": 4984, "s": 4838, "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": 5020, "s": 4984, "text": " Login to access your submissions. " }, { "code": null, "e": 5030, "s": 5020, "text": "\nProblem\n" }, { "code": null, "e": 5040, "s": 5030, "text": "\nContest\n" }, { "code": null, "e": 5103, "s": 5040, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5251, "s": 5103, "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": 5459, "s": 5251, "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": 5565, "s": 5459, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Reduce every element of the array to it's half retaining the sum zero - GeeksforGeeks
02 Sep, 2021 Given an array arr[] of N integers with total element sum equal to zero. The task is to reduce every element to it’s half such that the total sum remain zero. For every odd element X in the array, it could be reduced to either(X + 1) / 2 or (X – 1) / 2.Examples: Input: arr[] = {-7, 14, -7} Output: -4 7 -3 -4 + 7 -3 = 0Input: arr[] = {-14, 14} Output: -7 7 Approach: All the even elements could be divided by 2 but for odd elements, they have to be alternatively reduced to (X + 1) / 2 and (X – 1) / 2 in order to retain the original sum (i.e. 0) in the final array.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to reduce every// element to it's half such that// the total sum remain zerovoid half(int arr[], int n){ int i; // Flag to switch between alternating // odd numbers in the array int flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) cout << arr[i] / 2 << " "; // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { cout << arr[i] / 2 - 1 << " "; // Switch flag flag = 1; } else { int q = arr[i] / 2; cout<<q <<" "; // Switch flag flag = 0; } } }} // Driver codeint main (){ int arr[] = {-7, 14, -7}; int len = sizeof(arr)/sizeof(arr[0]); half(arr, len) ; return 0;} // This code is contributed by Rajput-Ji // Java implementation of the above approachclass GFG{ // Function to reduce every// element to it's half such that// the total sum remain zerostatic void half(int arr[], int n){ int i; // Flag to switch between alternating // odd numbers in the array int flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) System.out.print(arr[i] / 2 + " "); // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { System.out.print(arr[i] / 2 - 1 + " "); // Switch flag flag = 1; } else { int q = arr[i] / 2; System.out.print(q + " "); // Switch flag flag = 0; } } }} // Driver codepublic static void main (String[] args){ int arr[] = {-7, 14, -7}; int len = arr.length; half(arr, len) ;}} // This code is contributed by AnkitRai01 # Python3 implementation of the approach # Function to reduce every# element to it's half such that# the total sum remain zerodef half(arr, n) : # Flag to switch between alternating # odd numbers in the array flag = 0 # For every element of the array for i in range(n): # If its even then reduce it to half if arr[i] % 2 == 0 : print(arr[i]//2, end =" ") # If its odd else : # Reduce the odd elements # alternatively if flag == 0: print(arr[i]//2, end =" ") # Switch flag flag = 1 else : q = arr[i]//2 q+= 1 print(q, end =" ") # Switch flag flag = 0 # Driver codearr = [-7, 14, -7]half(arr, len(arr)) // C# implementation of the above approachusing System; class GFG{ // Function to reduce every// element to it's half such that// the total sum remain zerostatic void half(int []arr, int n){ int i; // Flag to switch between alternating // odd numbers in the array int flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) Console.Write(arr[i] / 2 + " "); // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { Console.Write(arr[i] / 2 - 1 + " "); // Switch flag flag = 1; } else { int q = arr[i] / 2; Console.Write(q + " "); // Switch flag flag = 0; } } }} // Driver codepublic static void Main (){ int [] arr = {-7, 14, -7}; int len = arr.Length; half(arr, len) ;}} // This code is contributed by mohit kumar 29 <script>// Javascript implementation of the above approach // Function to reduce every// element to it's half such that// the total sum remain zerofunction half(arr, n){ let i; // Flag to switch between alternating // odd numbers in the array let flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) document.write(arr[i] / 2 + " "); // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { document.write(Math.ceil(arr[i] / 2) - 1 + " "); // Switch flag flag = 1; } else { let q = Math.ceil(arr[i] / 2); document.write(q + " "); // Switch flag flag = 0; } } }} // Driver code let arr = [-7, 14, -7]; let len = arr.length; half(arr, len) ; // This code is contributed by _saurabh_jaiswal</script> -4 7 -3 ankthon mohit kumar 29 rehman_00001 Rajput-Ji _saurabh_jaiswal akshaysingh98088 Constructive Algorithms Arrays Python Programs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26423, "s": 26395, "text": "\n02 Sep, 2021" }, { "code": null, "e": 26688, "s": 26423, "text": "Given an array arr[] of N integers with total element sum equal to zero. The task is to reduce every element to it’s half such that the total sum remain zero. For every odd element X in the array, it could be reduced to either(X + 1) / 2 or (X – 1) / 2.Examples: " }, { "code": null, "e": 26785, "s": 26688, "text": "Input: arr[] = {-7, 14, -7} Output: -4 7 -3 -4 + 7 -3 = 0Input: arr[] = {-14, 14} Output: -7 7 " }, { "code": null, "e": 27048, "s": 26787, "text": "Approach: All the even elements could be divided by 2 but for odd elements, they have to be alternatively reduced to (X + 1) / 2 and (X – 1) / 2 in order to retain the original sum (i.e. 0) in the final array.Below is the implementation of the above approach: " }, { "code": null, "e": 27052, "s": 27048, "text": "C++" }, { "code": null, "e": 27057, "s": 27052, "text": "Java" }, { "code": null, "e": 27065, "s": 27057, "text": "Python3" }, { "code": null, "e": 27068, "s": 27065, "text": "C#" }, { "code": null, "e": 27079, "s": 27068, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; // Function to reduce every// element to it's half such that// the total sum remain zerovoid half(int arr[], int n){ int i; // Flag to switch between alternating // odd numbers in the array int flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) cout << arr[i] / 2 << \" \"; // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { cout << arr[i] / 2 - 1 << \" \"; // Switch flag flag = 1; } else { int q = arr[i] / 2; cout<<q <<\" \"; // Switch flag flag = 0; } } }} // Driver codeint main (){ int arr[] = {-7, 14, -7}; int len = sizeof(arr)/sizeof(arr[0]); half(arr, len) ; return 0;} // This code is contributed by Rajput-Ji", "e": 28252, "s": 27079, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to reduce every// element to it's half such that// the total sum remain zerostatic void half(int arr[], int n){ int i; // Flag to switch between alternating // odd numbers in the array int flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) System.out.print(arr[i] / 2 + \" \"); // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { System.out.print(arr[i] / 2 - 1 + \" \"); // Switch flag flag = 1; } else { int q = arr[i] / 2; System.out.print(q + \" \"); // Switch flag flag = 0; } } }} // Driver codepublic static void main (String[] args){ int arr[] = {-7, 14, -7}; int len = arr.length; half(arr, len) ;}} // This code is contributed by AnkitRai01", "e": 29431, "s": 28252, "text": null }, { "code": "# Python3 implementation of the approach # Function to reduce every# element to it's half such that# the total sum remain zerodef half(arr, n) : # Flag to switch between alternating # odd numbers in the array flag = 0 # For every element of the array for i in range(n): # If its even then reduce it to half if arr[i] % 2 == 0 : print(arr[i]//2, end =\" \") # If its odd else : # Reduce the odd elements # alternatively if flag == 0: print(arr[i]//2, end =\" \") # Switch flag flag = 1 else : q = arr[i]//2 q+= 1 print(q, end =\" \") # Switch flag flag = 0 # Driver codearr = [-7, 14, -7]half(arr, len(arr))", "e": 30329, "s": 29431, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to reduce every// element to it's half such that// the total sum remain zerostatic void half(int []arr, int n){ int i; // Flag to switch between alternating // odd numbers in the array int flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) Console.Write(arr[i] / 2 + \" \"); // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { Console.Write(arr[i] / 2 - 1 + \" \"); // Switch flag flag = 1; } else { int q = arr[i] / 2; Console.Write(q + \" \"); // Switch flag flag = 0; } } }} // Driver codepublic static void Main (){ int [] arr = {-7, 14, -7}; int len = arr.Length; half(arr, len) ;}} // This code is contributed by mohit kumar 29", "e": 31503, "s": 30329, "text": null }, { "code": "<script>// Javascript implementation of the above approach // Function to reduce every// element to it's half such that// the total sum remain zerofunction half(arr, n){ let i; // Flag to switch between alternating // odd numbers in the array let flag = 0; // For every element of the array for (i = 0; i < n; i++) { // If its even then reduce it to half if (arr[i] % 2 == 0 ) document.write(arr[i] / 2 + \" \"); // If its odd else { // Reduce the odd elements // alternatively if (flag == 0) { document.write(Math.ceil(arr[i] / 2) - 1 + \" \"); // Switch flag flag = 1; } else { let q = Math.ceil(arr[i] / 2); document.write(q + \" \"); // Switch flag flag = 0; } } }} // Driver code let arr = [-7, 14, -7]; let len = arr.length; half(arr, len) ; // This code is contributed by _saurabh_jaiswal</script>", "e": 32660, "s": 31503, "text": null }, { "code": null, "e": 32668, "s": 32660, "text": "-4 7 -3" }, { "code": null, "e": 32678, "s": 32670, "text": "ankthon" }, { "code": null, "e": 32693, "s": 32678, "text": "mohit kumar 29" }, { "code": null, "e": 32706, "s": 32693, "text": "rehman_00001" }, { "code": null, "e": 32716, "s": 32706, "text": "Rajput-Ji" }, { "code": null, "e": 32733, "s": 32716, "text": "_saurabh_jaiswal" }, { "code": null, "e": 32750, "s": 32733, "text": "akshaysingh98088" }, { "code": null, "e": 32774, "s": 32750, "text": "Constructive Algorithms" }, { "code": null, "e": 32781, "s": 32774, "text": "Arrays" }, { "code": null, "e": 32797, "s": 32781, "text": "Python Programs" }, { "code": null, "e": 32804, "s": 32797, "text": "Arrays" }, { "code": null, "e": 32902, "s": 32804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32970, "s": 32902, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33014, "s": 32970, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33062, "s": 33014, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33085, "s": 33062, "text": "Introduction to Arrays" }, { "code": null, "e": 33117, "s": 33085, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33160, "s": 33117, "text": "Python program to convert a list to string" }, { "code": null, "e": 33182, "s": 33160, "text": "Defaultdict in Python" }, { "code": null, "e": 33221, "s": 33182, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 33267, "s": 33221, "text": "Python | Split string into list of characters" } ]
Transaction Management in JDBC Example | JDBC Transactions | JDBC
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorials, we are going to learn abut Transaction Management in JDBC. A transaction represents a group of operations, used to perform a task. A transaction is a set of commands, it will take our database from one consistent state to another consistent state. Here are the most important points about Transaction Management in JDBC. A transaction means, it is a group of operations used to perform a task. A transaction can reach either success state or failure state. If all operations are completed successfully then the transaction becomes success. If any one of the operation fail then all remaining operations will be cancelled and finally transaction will reach to fail state. The basic transactions are of two types. Local Transactions Global / Distributed Transactions If all the operations are executed on one/same database, then it is called as local transaction. If the operations are executed on more than one database then it is called as global transactions. Example : If we transfer the money from account1 to account2 of same bank, then it is called as local transaction. If we transfer the money from account1 to account2 of different banks, then it is called as global or distributed transaction. We can get the Transaction support in JDBC from Connection interface. The Connection interface given 3 methods to perform Transaction Management in JDBC. setAutoCommit() commit() rollback() Before going to begin the operations, first we need to disable the auto commit mode. This can be done by calling setAutoCommit(false). By default, all operations done from the java program are going to execute permanently in database. Once the permanent execution happened in database, we can’t revert back them (Transaction Management is not possible). If all operations are executed successfully, then we commit a transaction manually by calling the commit() method. If any one of the operation failed, then we cancel the transaction by calling rollback() method. connection.setAutoCommit(false); try{ ---------- ---------- connection.commit(); }catch(Exception e){ connection.rollback(); } package com.onlinetutorialspoint.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; public class Jdbc_TransactionManagement_Example { public static void main(String[] args) throws Exception { Connection connection = null; Statement statement = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connection = DriverManager.getConnection( "jdbc:mysql://localhost:3306/onlinetutorialspoint", "root", "123456"); connection.setAutoCommit(false); statement = connection.createStatement(); statement .executeUpdate("insert person values ('5001','Hyderabad','Chandra Shekhar')"); statement .executeUpdate("insert person values ('5002','Banglore','Ram')"); connection.commit(); System.out.println("Transaction is commited."); statement.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); connection.rollback(); } } } Output: Transaction is committed. If we update with the statements, statement.executeUpdate("insert person values ('5003','Hyderabad','Chandra Shekhar')"); statement.executeUpdate("insert person values ('5001','Banglore','Ram')"); We can get the Exception like below and the transaction will be roll backed. com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '5001' for key 'PRIMARY' Transaction is rollbacked ! Happy Learning 🙂 JDBC Interview Questions and Answers JDBC Select Program Example JDBC Insert Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Scrollable ResultSet Example JDBC Updatable ResultSet Example JDBC Interview Questions and Answers JDBC Select Program Example JDBC Insert Program Example JDBC Update Program Example JDBC Delete Program Example JDBC PreparedStatement Example Program Insert an Image using JDBC in Mysql DB Read an Image in JDBC Example CallableStatement in jdbc Example ResultSetMetaData in JDBC Example DatabaseMetaData in JDBC Example Batch Processing in JDBC Example JDBC Connection with Properties file JDBC Scrollable ResultSet Example JDBC Updatable ResultSet Example Δ JDBC Driver Types Step by Step JDBC Program JDBC Select Program JDBC Insert Program JDBC Update Program JDBC Delete Program JDBC Connection – Properties File JDBC PreparedStatement Program JDBC – CallableStatement Example JDBC – Read an Image from DB JDBC – Insert an Image in DB JDBC – Updatable ResultSet JDBC – Scrollable ResultSet JDBC – ResultSetMetaData JDBC – DatabaseMetaData JDBC – Transaction Management JDBC – Batch Processing JDBC Interview Questions
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 548, "s": 398, "text": "In this tutorials, we are going to learn abut Transaction Management in JDBC. A transaction represents a group of operations, used to perform a task." }, { "code": null, "e": 665, "s": 548, "text": "A transaction is a set of commands, it will take our database from one consistent state to another consistent state." }, { "code": null, "e": 738, "s": 665, "text": "Here are the most important points about Transaction Management in JDBC." }, { "code": null, "e": 811, "s": 738, "text": "A transaction means, it is a group of operations used to perform a task." }, { "code": null, "e": 874, "s": 811, "text": "A transaction can reach either success state or failure state." }, { "code": null, "e": 957, "s": 874, "text": "If all operations are completed successfully then the transaction becomes success." }, { "code": null, "e": 1088, "s": 957, "text": "If any one of the operation fail then all remaining operations will be cancelled and finally transaction will reach to fail state." }, { "code": null, "e": 1129, "s": 1088, "text": "The basic transactions are of two types." }, { "code": null, "e": 1148, "s": 1129, "text": "Local Transactions" }, { "code": null, "e": 1182, "s": 1148, "text": "Global / Distributed Transactions" }, { "code": null, "e": 1279, "s": 1182, "text": "If all the operations are executed on one/same database, then it is called as local transaction." }, { "code": null, "e": 1378, "s": 1279, "text": "If the operations are executed on more than one database then it is called as global transactions." }, { "code": null, "e": 1620, "s": 1378, "text": "Example : If we transfer the money from account1 to account2 of same bank, then it is called as local transaction. If we transfer the money from account1 to account2 of different banks, then it is called as global or distributed transaction." }, { "code": null, "e": 1774, "s": 1620, "text": "We can get the Transaction support in JDBC from Connection interface. The Connection interface given 3 methods to perform Transaction Management in JDBC." }, { "code": null, "e": 1790, "s": 1774, "text": "setAutoCommit()" }, { "code": null, "e": 1799, "s": 1790, "text": "commit()" }, { "code": null, "e": 1810, "s": 1799, "text": "rollback()" }, { "code": null, "e": 1945, "s": 1810, "text": "Before going to begin the operations, first we need to disable the auto commit mode. This can be done by calling setAutoCommit(false)." }, { "code": null, "e": 2164, "s": 1945, "text": "By default, all operations done from the java program are going to execute permanently in database. Once the permanent execution happened in database, we can’t revert back them (Transaction Management is not possible)." }, { "code": null, "e": 2279, "s": 2164, "text": "If all operations are executed successfully, then we commit a transaction manually by calling the commit() method." }, { "code": null, "e": 2376, "s": 2279, "text": "If any one of the operation failed, then we cancel the transaction by calling rollback() method." }, { "code": null, "e": 2509, "s": 2376, "text": "connection.setAutoCommit(false);\n\ntry{\n\n----------\n----------\n\nconnection.commit();\n\n}catch(Exception e){\n\nconnection.rollback();\n\n}" }, { "code": null, "e": 3649, "s": 2509, "text": "package com.onlinetutorialspoint.jdbc;\n\nimport java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.Statement;\n\npublic class Jdbc_TransactionManagement_Example {\n\n public static void main(String[] args) throws Exception {\n Connection connection = null;\n Statement statement = null;\n\n try {\n\n Class.forName(\"sun.jdbc.odbc.JdbcOdbcDriver\");\n connection = DriverManager.getConnection(\n \"jdbc:mysql://localhost:3306/onlinetutorialspoint\", \"root\",\n \"123456\");\n connection.setAutoCommit(false);\n statement = connection.createStatement();\n statement\n .executeUpdate(\"insert person values ('5001','Hyderabad','Chandra Shekhar')\");\n statement\n .executeUpdate(\"insert person values ('5002','Banglore','Ram')\");\n connection.commit();\n System.out.println(\"Transaction is commited.\");\n statement.close();\n connection.close();\n } catch (Exception e) {\n e.printStackTrace();\n connection.rollback();\n }\n }\n}" }, { "code": null, "e": 3657, "s": 3649, "text": "Output:" }, { "code": null, "e": 3683, "s": 3657, "text": "Transaction is committed." }, { "code": null, "e": 3717, "s": 3683, "text": "If we update with the statements," }, { "code": null, "e": 3880, "s": 3717, "text": "statement.executeUpdate(\"insert person values ('5003','Hyderabad','Chandra Shekhar')\");\nstatement.executeUpdate(\"insert person values ('5001','Banglore','Ram')\");" }, { "code": null, "e": 3957, "s": 3880, "text": "We can get the Exception like below and the transaction will be roll backed." }, { "code": null, "e": 4102, "s": 3957, "text": "com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '5001' for key 'PRIMARY'\nTransaction is rollbacked !" }, { "code": null, "e": 4119, "s": 4102, "text": "Happy Learning 🙂" }, { "code": null, "e": 4616, "s": 4119, "text": "\nJDBC Interview Questions and Answers\nJDBC Select Program Example\nJDBC Insert Program Example\nJDBC Update Program Example\nJDBC Delete Program Example\nJDBC PreparedStatement Example Program\nInsert an Image using JDBC in Mysql DB\nRead an Image in JDBC Example\nCallableStatement in jdbc Example\nResultSetMetaData in JDBC Example\nDatabaseMetaData in JDBC Example\nBatch Processing in JDBC Example\nJDBC Connection with Properties file\nJDBC Scrollable ResultSet Example\nJDBC Updatable ResultSet Example\n" }, { "code": null, "e": 4653, "s": 4616, "text": "JDBC Interview Questions and Answers" }, { "code": null, "e": 4681, "s": 4653, "text": "JDBC Select Program Example" }, { "code": null, "e": 4709, "s": 4681, "text": "JDBC Insert Program Example" }, { "code": null, "e": 4737, "s": 4709, "text": "JDBC Update Program Example" }, { "code": null, "e": 4765, "s": 4737, "text": "JDBC Delete Program Example" }, { "code": null, "e": 4804, "s": 4765, "text": "JDBC PreparedStatement Example Program" }, { "code": null, "e": 4843, "s": 4804, "text": "Insert an Image using JDBC in Mysql DB" }, { "code": null, "e": 4873, "s": 4843, "text": "Read an Image in JDBC Example" }, { "code": null, "e": 4907, "s": 4873, "text": "CallableStatement in jdbc Example" }, { "code": null, "e": 4941, "s": 4907, "text": "ResultSetMetaData in JDBC Example" }, { "code": null, "e": 4974, "s": 4941, "text": "DatabaseMetaData in JDBC Example" }, { "code": null, "e": 5007, "s": 4974, "text": "Batch Processing in JDBC Example" }, { "code": null, "e": 5044, "s": 5007, "text": "JDBC Connection with Properties file" }, { "code": null, "e": 5078, "s": 5044, "text": "JDBC Scrollable ResultSet Example" }, { "code": null, "e": 5111, "s": 5078, "text": "JDBC Updatable ResultSet Example" }, { "code": null, "e": 5117, "s": 5115, "text": "Δ" }, { "code": null, "e": 5136, "s": 5117, "text": " JDBC Driver Types" }, { "code": null, "e": 5163, "s": 5136, "text": " Step by Step JDBC Program" }, { "code": null, "e": 5184, "s": 5163, "text": " JDBC Select Program" }, { "code": null, "e": 5205, "s": 5184, "text": " JDBC Insert Program" }, { "code": null, "e": 5226, "s": 5205, "text": " JDBC Update Program" }, { "code": null, "e": 5247, "s": 5226, "text": " JDBC Delete Program" }, { "code": null, "e": 5282, "s": 5247, "text": " JDBC Connection – Properties File" }, { "code": null, "e": 5314, "s": 5282, "text": " JDBC PreparedStatement Program" }, { "code": null, "e": 5348, "s": 5314, "text": " JDBC – CallableStatement Example" }, { "code": null, "e": 5378, "s": 5348, "text": " JDBC – Read an Image from DB" }, { "code": null, "e": 5408, "s": 5378, "text": " JDBC – Insert an Image in DB" }, { "code": null, "e": 5436, "s": 5408, "text": " JDBC – Updatable ResultSet" }, { "code": null, "e": 5465, "s": 5436, "text": " JDBC – Scrollable ResultSet" }, { "code": null, "e": 5491, "s": 5465, "text": " JDBC – ResultSetMetaData" }, { "code": null, "e": 5516, "s": 5491, "text": " JDBC – DatabaseMetaData" }, { "code": null, "e": 5547, "s": 5516, "text": " JDBC – Transaction Management" }, { "code": null, "e": 5572, "s": 5547, "text": " JDBC – Batch Processing" } ]
IPC using Message Queues - GeeksforGeeks
25 Nov, 2020 Prerequisite : Inter Process Communication A message queue is a linked list of messages stored within the kernel and identified by a message queue identifier. A new queue is created or an existing queue opened by msgget(). New messages are added to the end of a queue by msgsnd(). Every message has a positive long integer type field, a non-negative length, and the actual data bytes (corresponding to the length), all of which are specified to msgsnd() when the message is added to a queue. Messages are fetched from a queue by msgrcv(). We don’t have to fetch the messages in a first-in, first-out order. Instead, we can fetch messages based on their type field.All processes can exchange information through access to a common system message queue. The sending process places a message (via some (OS) message-passing module) onto a queue which can be read by another process. Each message is given an identification or type so that processes can select the appropriate message. Process must share a common key in order to gain access to the queue in the first place. System calls used for message queues: ftok(): is use to generate a unique key. msgget(): either returns the message queue identifier for a newly created message queue or returns the identifiers for a queue which exists with the same key value. msgsnd(): Data is placed on to a message queue by calling msgsnd(). msgrcv(): messages are retrieved from a queue. msgctl(): It performs various operations on a queue. Generally it is use to destroy message queue. MESSAGE QUEUE FOR WRITER PROCESS C // C Program for Message Queue (Writer Process)#include <stdio.h>#include <sys/ipc.h>#include <sys/msg.h>#define MAX 10 // structure for message queuestruct mesg_buffer { long mesg_type; char mesg_text[100];} message; int main(){ key_t key; int msgid; // ftok to generate unique key key = ftok("progfile", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); message.mesg_type = 1; printf("Write Data : "); fgets(message.mesg_text,MAX,stdin); // msgsnd to send message msgsnd(msgid, &message, sizeof(message), 0); // display the message printf("Data send is : %s \n", message.mesg_text); return 0;} MESSAGE QUEUE FOR READER PROCESS C // C Program for Message Queue (Reader Process)#include <stdio.h>#include <sys/ipc.h>#include <sys/msg.h> // structure for message queuestruct mesg_buffer { long mesg_type; char mesg_text[100];} message; int main(){ key_t key; int msgid; // ftok to generate unique key key = ftok("progfile", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); // msgrcv to receive message msgrcv(msgid, &message, sizeof(message), 1, 0); // display the message printf("Data Received is : %s \n", message.mesg_text); // to destroy the message queue msgctl(msgid, IPC_RMID, NULL); return 0;} Output: rahulkundu1 system-programming C Language Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Function Pointer in C Substring in C++ std::string class in C++ Command line arguments in C/C++ Enumeration (or enum) in C Banker's Algorithm in Operating System Types of Operating Systems Page Replacement Algorithms in Operating Systems Program for FCFS CPU Scheduling | Set 1 Paging in Operating System
[ { "code": null, "e": 24518, "s": 24490, "text": "\n25 Nov, 2020" }, { "code": null, "e": 25589, "s": 24518, "text": "Prerequisite : Inter Process Communication A message queue is a linked list of messages stored within the kernel and identified by a message queue identifier. A new queue is created or an existing queue opened by msgget(). New messages are added to the end of a queue by msgsnd(). Every message has a positive long integer type field, a non-negative length, and the actual data bytes (corresponding to the length), all of which are specified to msgsnd() when the message is added to a queue. Messages are fetched from a queue by msgrcv(). We don’t have to fetch the messages in a first-in, first-out order. Instead, we can fetch messages based on their type field.All processes can exchange information through access to a common system message queue. The sending process places a message (via some (OS) message-passing module) onto a queue which can be read by another process. Each message is given an identification or type so that processes can select the appropriate message. Process must share a common key in order to gain access to the queue in the first place. " }, { "code": null, "e": 25629, "s": 25589, "text": "System calls used for message queues: " }, { "code": null, "e": 25670, "s": 25629, "text": "ftok(): is use to generate a unique key." }, { "code": null, "e": 25835, "s": 25670, "text": "msgget(): either returns the message queue identifier for a newly created message queue or returns the identifiers for a queue which exists with the same key value." }, { "code": null, "e": 25903, "s": 25835, "text": "msgsnd(): Data is placed on to a message queue by calling msgsnd()." }, { "code": null, "e": 25950, "s": 25903, "text": "msgrcv(): messages are retrieved from a queue." }, { "code": null, "e": 26049, "s": 25950, "text": "msgctl(): It performs various operations on a queue. Generally it is use to destroy message queue." }, { "code": null, "e": 26086, "s": 26051, "text": "MESSAGE QUEUE FOR WRITER PROCESS " }, { "code": null, "e": 26088, "s": 26086, "text": "C" }, { "code": "// C Program for Message Queue (Writer Process)#include <stdio.h>#include <sys/ipc.h>#include <sys/msg.h>#define MAX 10 // structure for message queuestruct mesg_buffer { long mesg_type; char mesg_text[100];} message; int main(){ key_t key; int msgid; // ftok to generate unique key key = ftok(\"progfile\", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); message.mesg_type = 1; printf(\"Write Data : \"); fgets(message.mesg_text,MAX,stdin); // msgsnd to send message msgsnd(msgid, &message, sizeof(message), 0); // display the message printf(\"Data send is : %s \\n\", message.mesg_text); return 0;}", "e": 26803, "s": 26088, "text": null }, { "code": null, "e": 26838, "s": 26803, "text": "MESSAGE QUEUE FOR READER PROCESS " }, { "code": null, "e": 26840, "s": 26838, "text": "C" }, { "code": "// C Program for Message Queue (Reader Process)#include <stdio.h>#include <sys/ipc.h>#include <sys/msg.h> // structure for message queuestruct mesg_buffer { long mesg_type; char mesg_text[100];} message; int main(){ key_t key; int msgid; // ftok to generate unique key key = ftok(\"progfile\", 65); // msgget creates a message queue // and returns identifier msgid = msgget(key, 0666 | IPC_CREAT); // msgrcv to receive message msgrcv(msgid, &message, sizeof(message), 1, 0); // display the message printf(\"Data Received is : %s \\n\", message.mesg_text); // to destroy the message queue msgctl(msgid, IPC_RMID, NULL); return 0;}", "e": 27547, "s": 26840, "text": null }, { "code": null, "e": 27557, "s": 27547, "text": "Output: " }, { "code": null, "e": 27571, "s": 27559, "text": "rahulkundu1" }, { "code": null, "e": 27590, "s": 27571, "text": "system-programming" }, { "code": null, "e": 27601, "s": 27590, "text": "C Language" }, { "code": null, "e": 27619, "s": 27601, "text": "Operating Systems" }, { "code": null, "e": 27637, "s": 27619, "text": "Operating Systems" }, { "code": null, "e": 27735, "s": 27637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27757, "s": 27735, "text": "Function Pointer in C" }, { "code": null, "e": 27774, "s": 27757, "text": "Substring in C++" }, { "code": null, "e": 27799, "s": 27774, "text": "std::string class in C++" }, { "code": null, "e": 27831, "s": 27799, "text": "Command line arguments in C/C++" }, { "code": null, "e": 27858, "s": 27831, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 27897, "s": 27858, "text": "Banker's Algorithm in Operating System" }, { "code": null, "e": 27924, "s": 27897, "text": "Types of Operating Systems" }, { "code": null, "e": 27973, "s": 27924, "text": "Page Replacement Algorithms in Operating Systems" }, { "code": null, "e": 28013, "s": 27973, "text": "Program for FCFS CPU Scheduling | Set 1" } ]
Tailwind CSS Whitespace - GeeksforGeeks
23 Mar, 2022 This class accepts more than one value in tailwind CSS. All the properties are covered in class form. It is the alternative to the CSS white-space property. This class is used to control the text wrapping and white-spacing. There are several types of values in this property to use. Whitespace classes: whitespace-normal whitespace-nowrap whitespace-pre whitespace-pre-line whitespace-pre-wrap whitespace-normal: This is the default value of this class. When the whitespace class of tailwind is set to normal, every sequence of two or more whitespaces will appear as a single whitespace. The content in the element will wrap wherever necessary. Syntax: <element class="whitespace-normal">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class="mx-24 bg-green-200 rounded-lg"> <p class="p-4 whitespace-normal text-justify"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> Output: whitespace-normal whitespace-nowrap: When the whitespace class of tailwind is set to nowrap, every sequence of two or more whitespaces will appear as a single whitespace. The content in the element will not be wrapped to a new line unless explicitly specified. Syntax: <element class="whitespace-nowrap">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class="mx-24 bg-green-200 rounded-lg"> <p class="p-4 whitespace-nowrap text-justify"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> Output: whitespace-nowrap whitespace-pre: This value makes the whitespace have the same effect as the <pre>tag in HTML. The content in the element will wrap only when specified using line breaks. Syntax: <element class="whitespace-pre">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class="mx-24 bg-green-200 rounded-lg"> <p class="p-4 whitespace-pre text-justify"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> Output: whitespace-pre whitespace-pre-line: When the whitespace class of tailwind is set to pre-line value, every sequence of two or more whitespaces will appear as a single whitespace. The content in the element will be wrapped when required and when explicitly specified. Syntax: <element class="whitespace-pre-line">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class="mx-24 bg-green-200 rounded-lg"> <p class="p-4 whitespace-pre-line text-justify"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> Output: whitespace-pre-line whitespace-pre-wrap: When the whitespace class of tailwind is set to a pre-line value, every sequence of whitespaces will appear as it is. The content in the element will be wrapped when required and when explicitly specified. Syntax: <element class="whitespace-pre-wrap">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class="mx-24 bg-green-200 rounded-lg"> <p class="p-4 whitespace-pre-wrap text-justify"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> Output: whitespace-pre-wrap clintra Tailwind CSS Tailwind-Typography CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37495, "s": 37467, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37778, "s": 37495, "text": "This class accepts more than one value in tailwind CSS. All the properties are covered in class form. It is the alternative to the CSS white-space property. This class is used to control the text wrapping and white-spacing. There are several types of values in this property to use." }, { "code": null, "e": 37798, "s": 37778, "text": "Whitespace classes:" }, { "code": null, "e": 37817, "s": 37798, "text": "whitespace-normal " }, { "code": null, "e": 37836, "s": 37817, "text": "whitespace-nowrap " }, { "code": null, "e": 37852, "s": 37836, "text": "whitespace-pre " }, { "code": null, "e": 37873, "s": 37852, "text": "whitespace-pre-line " }, { "code": null, "e": 37894, "s": 37873, "text": "whitespace-pre-wrap " }, { "code": null, "e": 38145, "s": 37894, "text": "whitespace-normal: This is the default value of this class. When the whitespace class of tailwind is set to normal, every sequence of two or more whitespaces will appear as a single whitespace. The content in the element will wrap wherever necessary." }, { "code": null, "e": 38153, "s": 38145, "text": "Syntax:" }, { "code": null, "e": 38202, "s": 38153, "text": "<element class=\"whitespace-normal\">...</element>" }, { "code": null, "e": 38211, "s": 38202, "text": "Example:" }, { "code": null, "e": 38216, "s": 38211, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class=\"mx-24 bg-green-200 rounded-lg\"> <p class=\"p-4 whitespace-normal text-justify\"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> ", "e": 38844, "s": 38216, "text": null }, { "code": null, "e": 38852, "s": 38844, "text": "Output:" }, { "code": null, "e": 38870, "s": 38852, "text": "whitespace-normal" }, { "code": null, "e": 39113, "s": 38870, "text": "whitespace-nowrap: When the whitespace class of tailwind is set to nowrap, every sequence of two or more whitespaces will appear as a single whitespace. The content in the element will not be wrapped to a new line unless explicitly specified." }, { "code": null, "e": 39121, "s": 39113, "text": "Syntax:" }, { "code": null, "e": 39170, "s": 39121, "text": "<element class=\"whitespace-nowrap\">...</element>" }, { "code": null, "e": 39179, "s": 39170, "text": "Example:" }, { "code": null, "e": 39184, "s": 39179, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class=\"mx-24 bg-green-200 rounded-lg\"> <p class=\"p-4 whitespace-nowrap text-justify\"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> ", "e": 39812, "s": 39184, "text": null }, { "code": null, "e": 39820, "s": 39812, "text": "Output:" }, { "code": null, "e": 39838, "s": 39820, "text": "whitespace-nowrap" }, { "code": null, "e": 40008, "s": 39838, "text": "whitespace-pre: This value makes the whitespace have the same effect as the <pre>tag in HTML. The content in the element will wrap only when specified using line breaks." }, { "code": null, "e": 40016, "s": 40008, "text": "Syntax:" }, { "code": null, "e": 40062, "s": 40016, "text": "<element class=\"whitespace-pre\">...</element>" }, { "code": null, "e": 40071, "s": 40062, "text": "Example:" }, { "code": null, "e": 40076, "s": 40071, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class=\"mx-24 bg-green-200 rounded-lg\"> <p class=\"p-4 whitespace-pre text-justify\"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> ", "e": 40701, "s": 40076, "text": null }, { "code": null, "e": 40709, "s": 40701, "text": "Output:" }, { "code": null, "e": 40724, "s": 40709, "text": "whitespace-pre" }, { "code": null, "e": 40975, "s": 40724, "text": "whitespace-pre-line: When the whitespace class of tailwind is set to pre-line value, every sequence of two or more whitespaces will appear as a single whitespace. The content in the element will be wrapped when required and when explicitly specified." }, { "code": null, "e": 40983, "s": 40975, "text": "Syntax:" }, { "code": null, "e": 41034, "s": 40983, "text": "<element class=\"whitespace-pre-line\">...</element>" }, { "code": null, "e": 41043, "s": 41034, "text": "Example:" }, { "code": null, "e": 41048, "s": 41043, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class=\"mx-24 bg-green-200 rounded-lg\"> <p class=\"p-4 whitespace-pre-line text-justify\"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> ", "e": 41678, "s": 41048, "text": null }, { "code": null, "e": 41686, "s": 41678, "text": "Output:" }, { "code": null, "e": 41706, "s": 41686, "text": "whitespace-pre-line" }, { "code": null, "e": 41933, "s": 41706, "text": "whitespace-pre-wrap: When the whitespace class of tailwind is set to a pre-line value, every sequence of whitespaces will appear as it is. The content in the element will be wrapped when required and when explicitly specified." }, { "code": null, "e": 41941, "s": 41933, "text": "Syntax:" }, { "code": null, "e": 41992, "s": 41941, "text": "<element class=\"whitespace-pre-wrap\">...</element>" }, { "code": null, "e": 42001, "s": 41992, "text": "Example:" }, { "code": null, "e": 42006, "s": 42001, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Whitespace Class</b> <div class=\"mx-24 bg-green-200 rounded-lg\"> <p class=\"p-4 whitespace-pre-wrap text-justify\"> Geeksforgeeks: A Computer Science portal for Geeks those who wants to pursue an engineering degree or wants to create a career on engineering field. </p> </div></body> </html> ", "e": 42636, "s": 42006, "text": null }, { "code": null, "e": 42644, "s": 42636, "text": "Output:" }, { "code": null, "e": 42664, "s": 42644, "text": "whitespace-pre-wrap" }, { "code": null, "e": 42672, "s": 42664, "text": "clintra" }, { "code": null, "e": 42685, "s": 42672, "text": "Tailwind CSS" }, { "code": null, "e": 42705, "s": 42685, "text": "Tailwind-Typography" }, { "code": null, "e": 42709, "s": 42705, "text": "CSS" }, { "code": null, "e": 42726, "s": 42709, "text": "Web Technologies" }, { "code": null, "e": 42824, "s": 42726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42874, "s": 42824, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 42936, "s": 42874, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42994, "s": 42936, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 43042, "s": 42994, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 43092, "s": 43042, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 43132, "s": 43092, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 43165, "s": 43132, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 43210, "s": 43165, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 43253, "s": 43210, "text": "How to fetch data from an API in ReactJS ?" } ]
Creating and Training Custom Layers in TensorFlow 2 | by Arjun Sarkar | Towards Data Science
Previously we’ve seen how to create custom loss functions — Creating custom Loss functions using TensorFlow 2Next, I wrote about creating custom Activation Functions using Lambda layers — Creating Custom Activation Functions with Lambda Layers in TensorFlow 2 Previously we’ve seen how to create custom loss functions — Creating custom Loss functions using TensorFlow 2 Next, I wrote about creating custom Activation Functions using Lambda layers — Creating Custom Activation Functions with Lambda Layers in TensorFlow 2 This is the third part of the series, where we create custom Dense Layers and train them in TensorFlow 2. Lambda layers are simple layers in TensorFlow that can be used to create some custom activation functions. But lambda layers have many limitations, especially when it comes to training these layers. So, the idea is to create custom layers that are trainable, using the inheritable Keras layers in TensorFlow — with a special focus on Dense layers. What is a Layer? A layer is a class that receives some parameters, passes them through state and computations, and passes out an output, as required by the neural network. Every model architecture contains multiple layers, be it a Sequential or a Functional API. State — Mostly trainable features which are trained during ‘model.fit’. In a Dense layer, the states constitute the weights and the bias, as shown in Figure 1. These values are updated to give better results as the model trains. In some layers, the state can also contain non-trainable features. Computation — Computation helps in transforming a batch of input data into a batch of output data. In this part of the layer, the calculation takes place. In a Dense layer, the computation does the following computation — Y = (w*X+c), and returns Y. Y is the output, X is the input, w = weights, c = bias. Now that we know what happens inside Dense layers, let’s see how we can create our own Dense layer and use it in a model. import tensorflow as tffrom tensorflow.keras.layers import Layerclass SimpleDense(Layer): def __init__(self, units=32): '''Initializes the instance attributes''' super(SimpleDense, self).__init__() self.units = units def build(self, input_shape): '''Create the state of the layer (weights)''' # initialize the weights w_init = tf.random_normal_initializer() self.w = tf.Variable(name="kernel", initial_value=w_init(shape=(input_shape[-1], self.units), dtype='float32'),trainable=True) # initialize the biases b_init = tf.zeros_initializer() self.b = tf.Variable(name="bias",initial_value=b_init(shape=(self.units,), dtype='float32'),trainable=True) def call(self, inputs): '''Defines the computation from inputs to outputs''' return tf.matmul(inputs, self.w) + self.b Explanation of the code above — The class is named SimpleDense. When we create a custom layer, we have to inherit Keras’s layer class. This is done in the line ‘class SimpleDense(Layer)’. ‘__init__’ is the first method in the class that will help to initialize the class. ‘init’ accepts parameters and converts them to variables that can be used within the class. This is inheriting from the ‘Layer’ class and hence requires some initialization. This initialization is done using the ‘super’ keyword. ‘units’ is a local class variable. This is analogous to the number of units in the Dense layer. The default value is set to 32, but can always be changed when the class is called. ‘build’ is the next method in the class. This is used to specify the states. In the Dense layer, the two states required are ‘w’ and ‘b’, for weights and biases. When the Dense layer is being created, we are not just creating one neuron of the network’s hidden layer, but multiple neurons at one go (in this case 32 neurons will be created). Every neuron in the layer needs to be initialized and given some random weight and bias values. TensorFlow contains many built-in functions to initialize these values. For initializing the weights we use the ‘random_normal_initializer’ function from TensorFlow, which will initialize weights randomly using a normal distribution. ‘self.w’ contains the states of the weights in the form of a tensor variable. These states will initialize using ‘w_init’. The value contained as weights will be in the ‘float_32’ format. It is set to ‘trainable’, which means after every run, these initial weights will be updated in accordance with the loss function and optimizer. The name ‘kernel’ is added so that it can be easily traced later. For initializing the biases, TensorFlow’s ‘zeros_initializer’ function is used. This sets all the initial bias values to zero. ‘self.b’ is a tensor with a size same as the size of the units (here 32), and each of these 32 bias terms are set to zero initially. This is also set to ‘trainable’, so the bias terms will update as training starts. The name ‘bias’ is added to be able to trace it later. ‘call’ is the last method that performs the computation. In this case, as it is a Dense layer, it multiplies the inputs with the weights, adds the bias, and finally returns the output. The ‘matmul’ operation is used as self.w and self.b are tensors and not single numerical values. # declare an instance of the class my_dense = SimpleDense(units=1) # define an input and feed into the layer x = tf.ones((1, 1)) y = my_dense(x) # parameters of the base Layer class like `variables` can be used print(my_dense.variables) Output: [<tf.Variable 'simple_dense/kernel:0' shape=(1, 1) dtype=float32, numpy=array([[0.00382898]], dtype=float32)>, <tf.Variable 'simple_dense/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>] Explanation of the code above — The first line creates a Dense layer containing just one neuron (unit =1). x (input) is a tensor of shape (1,1) with the value 1. Y = my_dense(x), helps initialize the Dense layer. ‘.variables’ helps us to look at the values initialized inside the Dense layers (weights and biases). The output of ‘my_dense.variable’ is shown below the code block. It shows that there are two variables in ‘simple_dense’ called ‘kernel’ and ‘bias’. The kernel ‘w’ is initialized a value 0.0038, a random normal distribution value, and the bias ‘b’ is initialized with the value 0. This is just the initial state of the layer. Once trained, these values will change accordingly. import numpy as np# define the dataset xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float) # use the Sequential API to build a model with our custom layer my_layer = SimpleDense(units=1) model = tf.keras.Sequential([my_layer]) # configure and train the model model.compile(optimizer='sgd', loss='mean_squared_error') model.fit(xs, ys, epochs=500,verbose=0) # perform inference print(model.predict([10.0])) # see the updated state of the variables print(my_layer.variables) Output: [[18.981567]][<tf.Variable 'sequential/simple_dense_1/kernel:0' shape=(1, 1) dtype=float32, numpy=array([[1.9973286]], dtype=float32)>, <tf.Variable 'sequential/simple_dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([-0.99171764], dtype=float32)>] Explanation of the code above —The code used above is a very simple way to check if the custom layers work. Input and output are set, and the model is compiled using the custom layer and finally trained for 500 epochs. What is important to see is that after training the model, the values of the weights and biases have now changed. The weight which was initially set as 0.0038 is now 1.9973, and the bias which was initially set as zero is now -0.9917. Previously we created the custom Dense layer but we did not add any activations along with this layer. Of course to add activation we can just write the activation as a separate line in the model, or add the activation as a Lambda layer. But how do we implement the activation in the same custom layer that we created above. The answer is a simple tweak in the ‘__init__’ and the ‘call’ methods in the custom Dense layer. class SimpleDense(Layer): # add an activation parameter def __init__(self, units=32, activation=None): super(SimpleDense, self).__init__() self.units = units # define the activation to get from the built-in activation layers in Keras self.activation = tf.keras.activations.get(activation) def build(self, input_shape): w_init = tf.random_normal_initializer() self.w = tf.Variable(name="kernel", initial_value=w_init(shape=(input_shape[-1], self.units),dtype='float32'),trainable=True) b_init = tf.zeros_initializer() self.b = tf.Variable(name="bias", initial_value=b_init(shape=(self.units,), dtype='float32'),trainable=True) super().build(input_shape) def call(self, inputs): # pass the computation to the activation layer return self.activation(tf.matmul(inputs, self.w) + self.b) Explanation of the code above — Most of the code is exactly similar to the code that we used before. To add the activation we need to specify in the ‘__init__’ that we need an activation. Either a string or an instance of an activation object can be passed into this activation. It is set to default as None, so if no activation function is mentioned it will not throw an error. Next, we have to initialize the activation function as — ‘tf.keras.activations.get(activation)’. The final edit is in the ‘call’ method where just before the computation of the weights and the biases we need to add self.activation to activate the computation. So now the return is the computation along with the activation. import tensorflow as tffrom tensorflow.keras.layers import Layerclass SimpleDense(Layer):def __init__(self, units=32, activation=None): super(SimpleDense, self).__init__() self.units = units # define the activation to get from the built-in activation layers in Kerasself.activation = tf.keras.activations.get(activation) def build(self, input_shape):w_init = tf.random_normal_initializer() self.w = tf.Variable(name="kernel", initial_value=w_init(shape=(input_shape[-1], self.units),dtype='float32'),trainable=True)b_init = tf.zeros_initializer() self.b = tf.Variable(name="bias", initial_value=b_init(shape=(self.units,), dtype='float32'),trainable=True) super().build(input_shape) def call(self, inputs): # pass the computation to the activation layerreturn self.activation(tf.matmul(inputs, self.w) + self.b)mnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0# build the modelmodel = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), # our custom Dense layer with activation SimpleDense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax')])# compile the modelmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# fit the modelmodel.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test) Training the model with our custom Dense layer and activation gives a training accuracy of 97.8% and a validation accuracy of 97.7%. This is the way to create custom layers in TensorFlow. Even though we only see the working of a Dense Layer, this can easily be replaced by any other layers such as a Quadratic Layer which does the following computation — It has 3 state variables: a,b and c, Computation: Replacing the Dense Layer with a Quadratic layer: import tensorflow as tffrom tensorflow.keras.layers import Layerclass SimpleQuadratic(Layer): def __init__(self, units=32, activation=None): '''Initializes the class and sets up the internal variables''' super(SimpleQuadratic,self).__init__() self.units=units self.activation=tf.keras.activations.get(activation) def build(self, input_shape): '''Create the state of the layer (weights)''' a_init = tf.random_normal_initializer() a_init_val = a_init(shape=(input_shape[-1],self.units),dtype= 'float32') self.a = tf.Variable(initial_value=a_init_val, trainable='true') b_init = tf.random_normal_initializer() b_init_val = b_init(shape=(input_shape[-1],self.units),dtype= 'float32') self.b = tf.Variable(initial_value=b_init_val, trainable='true') c_init= tf.zeros_initializer() c_init_val = c_init(shape=(self.units,),dtype='float32') self.c = tf.Variable(initial_value=c_init_val,trainable='true') def call(self, inputs): '''Defines the computation from inputs to outputs''' x_squared= tf.math.square(inputs) x_squared_times_a = tf.matmul(x_squared,self.a) x_times_b= tf.matmul(inputs,self.b) x2a_plus_xb_plus_c = x_squared_times_a+x_times_b+self.c return self.activation(x2a_plus_xb_plus_c)mnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), SimpleQuadratic(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test) This Quadratic layer gives a validation accuracy of 97.8% on the mnist dataset. Thus, we see we can implement our own layers along with the desired activation into the TensorFlow models to edit or maybe even improve overall accuracies.
[ { "code": null, "e": 432, "s": 172, "text": "Previously we’ve seen how to create custom loss functions — Creating custom Loss functions using TensorFlow 2Next, I wrote about creating custom Activation Functions using Lambda layers — Creating Custom Activation Functions with Lambda Layers in TensorFlow 2" }, { "code": null, "e": 542, "s": 432, "text": "Previously we’ve seen how to create custom loss functions — Creating custom Loss functions using TensorFlow 2" }, { "code": null, "e": 693, "s": 542, "text": "Next, I wrote about creating custom Activation Functions using Lambda layers — Creating Custom Activation Functions with Lambda Layers in TensorFlow 2" }, { "code": null, "e": 799, "s": 693, "text": "This is the third part of the series, where we create custom Dense Layers and train them in TensorFlow 2." }, { "code": null, "e": 1147, "s": 799, "text": "Lambda layers are simple layers in TensorFlow that can be used to create some custom activation functions. But lambda layers have many limitations, especially when it comes to training these layers. So, the idea is to create custom layers that are trainable, using the inheritable Keras layers in TensorFlow — with a special focus on Dense layers." }, { "code": null, "e": 1164, "s": 1147, "text": "What is a Layer?" }, { "code": null, "e": 1410, "s": 1164, "text": "A layer is a class that receives some parameters, passes them through state and computations, and passes out an output, as required by the neural network. Every model architecture contains multiple layers, be it a Sequential or a Functional API." }, { "code": null, "e": 1706, "s": 1410, "text": "State — Mostly trainable features which are trained during ‘model.fit’. In a Dense layer, the states constitute the weights and the bias, as shown in Figure 1. These values are updated to give better results as the model trains. In some layers, the state can also contain non-trainable features." }, { "code": null, "e": 1928, "s": 1706, "text": "Computation — Computation helps in transforming a batch of input data into a batch of output data. In this part of the layer, the calculation takes place. In a Dense layer, the computation does the following computation —" }, { "code": null, "e": 1956, "s": 1928, "text": "Y = (w*X+c), and returns Y." }, { "code": null, "e": 2012, "s": 1956, "text": "Y is the output, X is the input, w = weights, c = bias." }, { "code": null, "e": 2134, "s": 2012, "text": "Now that we know what happens inside Dense layers, let’s see how we can create our own Dense layer and use it in a model." }, { "code": null, "e": 3013, "s": 2134, "text": "import tensorflow as tffrom tensorflow.keras.layers import Layerclass SimpleDense(Layer): def __init__(self, units=32): '''Initializes the instance attributes''' super(SimpleDense, self).__init__() self.units = units def build(self, input_shape): '''Create the state of the layer (weights)''' # initialize the weights w_init = tf.random_normal_initializer() self.w = tf.Variable(name=\"kernel\", initial_value=w_init(shape=(input_shape[-1], self.units), dtype='float32'),trainable=True) # initialize the biases b_init = tf.zeros_initializer() self.b = tf.Variable(name=\"bias\",initial_value=b_init(shape=(self.units,), dtype='float32'),trainable=True) def call(self, inputs): '''Defines the computation from inputs to outputs''' return tf.matmul(inputs, self.w) + self.b" }, { "code": null, "e": 3201, "s": 3013, "text": "Explanation of the code above — The class is named SimpleDense. When we create a custom layer, we have to inherit Keras’s layer class. This is done in the line ‘class SimpleDense(Layer)’." }, { "code": null, "e": 3694, "s": 3201, "text": "‘__init__’ is the first method in the class that will help to initialize the class. ‘init’ accepts parameters and converts them to variables that can be used within the class. This is inheriting from the ‘Layer’ class and hence requires some initialization. This initialization is done using the ‘super’ keyword. ‘units’ is a local class variable. This is analogous to the number of units in the Dense layer. The default value is set to 32, but can always be changed when the class is called." }, { "code": null, "e": 4204, "s": 3694, "text": "‘build’ is the next method in the class. This is used to specify the states. In the Dense layer, the two states required are ‘w’ and ‘b’, for weights and biases. When the Dense layer is being created, we are not just creating one neuron of the network’s hidden layer, but multiple neurons at one go (in this case 32 neurons will be created). Every neuron in the layer needs to be initialized and given some random weight and bias values. TensorFlow contains many built-in functions to initialize these values." }, { "code": null, "e": 4765, "s": 4204, "text": "For initializing the weights we use the ‘random_normal_initializer’ function from TensorFlow, which will initialize weights randomly using a normal distribution. ‘self.w’ contains the states of the weights in the form of a tensor variable. These states will initialize using ‘w_init’. The value contained as weights will be in the ‘float_32’ format. It is set to ‘trainable’, which means after every run, these initial weights will be updated in accordance with the loss function and optimizer. The name ‘kernel’ is added so that it can be easily traced later." }, { "code": null, "e": 5163, "s": 4765, "text": "For initializing the biases, TensorFlow’s ‘zeros_initializer’ function is used. This sets all the initial bias values to zero. ‘self.b’ is a tensor with a size same as the size of the units (here 32), and each of these 32 bias terms are set to zero initially. This is also set to ‘trainable’, so the bias terms will update as training starts. The name ‘bias’ is added to be able to trace it later." }, { "code": null, "e": 5445, "s": 5163, "text": "‘call’ is the last method that performs the computation. In this case, as it is a Dense layer, it multiplies the inputs with the weights, adds the bias, and finally returns the output. The ‘matmul’ operation is used as self.w and self.b are tensors and not single numerical values." }, { "code": null, "e": 5684, "s": 5445, "text": "# declare an instance of the class my_dense = SimpleDense(units=1) # define an input and feed into the layer x = tf.ones((1, 1)) y = my_dense(x) # parameters of the base Layer class like `variables` can be used print(my_dense.variables)" }, { "code": null, "e": 5692, "s": 5684, "text": "Output:" }, { "code": null, "e": 5899, "s": 5692, "text": "[<tf.Variable 'simple_dense/kernel:0' shape=(1, 1) dtype=float32, numpy=array([[0.00382898]], dtype=float32)>, <tf.Variable 'simple_dense/bias:0' shape=(1,) dtype=float32, numpy=array([0.], dtype=float32)>]" }, { "code": null, "e": 6214, "s": 5899, "text": "Explanation of the code above — The first line creates a Dense layer containing just one neuron (unit =1). x (input) is a tensor of shape (1,1) with the value 1. Y = my_dense(x), helps initialize the Dense layer. ‘.variables’ helps us to look at the values initialized inside the Dense layers (weights and biases)." }, { "code": null, "e": 6592, "s": 6214, "text": "The output of ‘my_dense.variable’ is shown below the code block. It shows that there are two variables in ‘simple_dense’ called ‘kernel’ and ‘bias’. The kernel ‘w’ is initialized a value 0.0038, a random normal distribution value, and the bias ‘b’ is initialized with the value 0. This is just the initial state of the layer. Once trained, these values will change accordingly." }, { "code": null, "e": 7140, "s": 6592, "text": "import numpy as np# define the dataset xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-3.0, -1.0, 1.0, 3.0, 5.0, 7.0], dtype=float) # use the Sequential API to build a model with our custom layer my_layer = SimpleDense(units=1) model = tf.keras.Sequential([my_layer]) # configure and train the model model.compile(optimizer='sgd', loss='mean_squared_error') model.fit(xs, ys, epochs=500,verbose=0) # perform inference print(model.predict([10.0])) # see the updated state of the variables print(my_layer.variables)" }, { "code": null, "e": 7148, "s": 7140, "text": "Output:" }, { "code": null, "e": 7402, "s": 7148, "text": "[[18.981567]][<tf.Variable 'sequential/simple_dense_1/kernel:0' shape=(1, 1) dtype=float32, numpy=array([[1.9973286]], dtype=float32)>, <tf.Variable 'sequential/simple_dense_1/bias:0' shape=(1,) dtype=float32, numpy=array([-0.99171764], dtype=float32)>]" }, { "code": null, "e": 7856, "s": 7402, "text": "Explanation of the code above —The code used above is a very simple way to check if the custom layers work. Input and output are set, and the model is compiled using the custom layer and finally trained for 500 epochs. What is important to see is that after training the model, the values of the weights and biases have now changed. The weight which was initially set as 0.0038 is now 1.9973, and the bias which was initially set as zero is now -0.9917." }, { "code": null, "e": 8181, "s": 7856, "text": "Previously we created the custom Dense layer but we did not add any activations along with this layer. Of course to add activation we can just write the activation as a separate line in the model, or add the activation as a Lambda layer. But how do we implement the activation in the same custom layer that we created above." }, { "code": null, "e": 8278, "s": 8181, "text": "The answer is a simple tweak in the ‘__init__’ and the ‘call’ methods in the custom Dense layer." }, { "code": null, "e": 9188, "s": 8278, "text": "class SimpleDense(Layer): # add an activation parameter def __init__(self, units=32, activation=None): super(SimpleDense, self).__init__() self.units = units # define the activation to get from the built-in activation layers in Keras self.activation = tf.keras.activations.get(activation) def build(self, input_shape): w_init = tf.random_normal_initializer() self.w = tf.Variable(name=\"kernel\", initial_value=w_init(shape=(input_shape[-1], self.units),dtype='float32'),trainable=True) b_init = tf.zeros_initializer() self.b = tf.Variable(name=\"bias\", initial_value=b_init(shape=(self.units,), dtype='float32'),trainable=True) super().build(input_shape) def call(self, inputs): # pass the computation to the activation layer return self.activation(tf.matmul(inputs, self.w) + self.b)" }, { "code": null, "e": 9289, "s": 9188, "text": "Explanation of the code above — Most of the code is exactly similar to the code that we used before." }, { "code": null, "e": 9664, "s": 9289, "text": "To add the activation we need to specify in the ‘__init__’ that we need an activation. Either a string or an instance of an activation object can be passed into this activation. It is set to default as None, so if no activation function is mentioned it will not throw an error. Next, we have to initialize the activation function as — ‘tf.keras.activations.get(activation)’." }, { "code": null, "e": 9891, "s": 9664, "text": "The final edit is in the ‘call’ method where just before the computation of the weights and the biases we need to add self.activation to activate the computation. So now the return is the computation along with the activation." }, { "code": null, "e": 11424, "s": 9891, "text": "import tensorflow as tffrom tensorflow.keras.layers import Layerclass SimpleDense(Layer):def __init__(self, units=32, activation=None): super(SimpleDense, self).__init__() self.units = units # define the activation to get from the built-in activation layers in Kerasself.activation = tf.keras.activations.get(activation) def build(self, input_shape):w_init = tf.random_normal_initializer() self.w = tf.Variable(name=\"kernel\", initial_value=w_init(shape=(input_shape[-1], self.units),dtype='float32'),trainable=True)b_init = tf.zeros_initializer() self.b = tf.Variable(name=\"bias\", initial_value=b_init(shape=(self.units,), dtype='float32'),trainable=True) super().build(input_shape) def call(self, inputs): # pass the computation to the activation layerreturn self.activation(tf.matmul(inputs, self.w) + self.b)mnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0# build the modelmodel = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), # our custom Dense layer with activation SimpleDense(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax')])# compile the modelmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])# fit the modelmodel.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)" }, { "code": null, "e": 11557, "s": 11424, "text": "Training the model with our custom Dense layer and activation gives a training accuracy of 97.8% and a validation accuracy of 97.7%." }, { "code": null, "e": 11779, "s": 11557, "text": "This is the way to create custom layers in TensorFlow. Even though we only see the working of a Dense Layer, this can easily be replaced by any other layers such as a Quadratic Layer which does the following computation —" }, { "code": null, "e": 11816, "s": 11779, "text": "It has 3 state variables: a,b and c," }, { "code": null, "e": 11829, "s": 11816, "text": "Computation:" }, { "code": null, "e": 11879, "s": 11829, "text": "Replacing the Dense Layer with a Quadratic layer:" }, { "code": null, "e": 13803, "s": 11879, "text": "import tensorflow as tffrom tensorflow.keras.layers import Layerclass SimpleQuadratic(Layer): def __init__(self, units=32, activation=None): '''Initializes the class and sets up the internal variables''' super(SimpleQuadratic,self).__init__() self.units=units self.activation=tf.keras.activations.get(activation) def build(self, input_shape): '''Create the state of the layer (weights)''' a_init = tf.random_normal_initializer() a_init_val = a_init(shape=(input_shape[-1],self.units),dtype= 'float32') self.a = tf.Variable(initial_value=a_init_val, trainable='true') b_init = tf.random_normal_initializer() b_init_val = b_init(shape=(input_shape[-1],self.units),dtype= 'float32') self.b = tf.Variable(initial_value=b_init_val, trainable='true') c_init= tf.zeros_initializer() c_init_val = c_init(shape=(self.units,),dtype='float32') self.c = tf.Variable(initial_value=c_init_val,trainable='true') def call(self, inputs): '''Defines the computation from inputs to outputs''' x_squared= tf.math.square(inputs) x_squared_times_a = tf.matmul(x_squared,self.a) x_times_b= tf.matmul(inputs,self.b) x2a_plus_xb_plus_c = x_squared_times_a+x_times_b+self.c return self.activation(x2a_plus_xb_plus_c)mnist = tf.keras.datasets.mnist(x_train, y_train),(x_test, y_test) = mnist.load_data()x_train, x_test = x_train / 255.0, x_test / 255.0model = tf.keras.models.Sequential([ tf.keras.layers.Flatten(input_shape=(28, 28)), SimpleQuadratic(128, activation='relu'), tf.keras.layers.Dropout(0.2), tf.keras.layers.Dense(10, activation='softmax')])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])model.fit(x_train, y_train, epochs=5)model.evaluate(x_test, y_test)" }, { "code": null, "e": 13883, "s": 13803, "text": "This Quadratic layer gives a validation accuracy of 97.8% on the mnist dataset." } ]
arecord command in Linux with examples - GeeksforGeeks
07 Apr, 2022 arecord is a command-line sound recorder for ALSA(Advanced Linux Sound Architecture) sound card drivers. It supports several file formats and multiple soundcards with multiple devices. It is basically used to record audio using the command-line interface. Syntax: arecord [flags] [filename] If the filename is not specified then it uses Standard input. Options: -h, –help : It is used to show the help messages and exit. –version : Print current version. -l, –list-devices : List all soundcards and digital audio devices. -L, –list-pcms : List all PCMs(Pulse Code Modulation) defined. -D, –device=NAME : Select PCM by name. -q –quiet : Quiet mode. Suppress messages (not sound :). -t, –file-type TYPE File type (voc, wav, raw or au). If this parameter is omitted the WAVE format is used. -c, –channels=# : The number of channels. The default is one channel. Valid values are 1 through 32. -f –format=FORMAT : If no format is given U8 is used. -r, –rate=# : Sampling rate in Hertz. The default rate is 8000 Hertz. -d, –duration=# : Interrupt after # seconds. -s, –sleep-min=# : Min ticks to sleep. The default is not to sleep. -M, –mmap : Use memory-mapped (mmap) I/O mode for the audio stream. If this option is not set, the read/write I/O mode will be used. -N, –nonblock : Open the audio device in non-blocking mode. If the device is busy the program will exit immediately. Note: It contains various other options that we normally don’t need. If you want to know more about you can simply run following command on the terminal. arecord --help Recognized Sample Formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE DSD_U32_LE DSD_U16_BE DSD_U32_BE Note: Some of these may not be available on selected hardware. Examples: Recording audio through arecord (It will record an audio of 5 secs of U8 format and mp3 type named sample.mp3): Now we will demonstrate how it really sounds like to record. Now we will play that recorded audio using aplay command.(microphone input is off.) rkbhola5 linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C ZIP command in Linux with examples SORT command in Linux/Unix with examples tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C diff command in Linux with examples scp command in Linux with Examples
[ { "code": null, "e": 25599, "s": 25571, "text": "\n07 Apr, 2022" }, { "code": null, "e": 25863, "s": 25599, "text": "arecord is a command-line sound recorder for ALSA(Advanced Linux Sound Architecture) sound card drivers. It supports several file formats and multiple soundcards with multiple devices. It is basically used to record audio using the command-line interface. Syntax:" }, { "code": null, "e": 25890, "s": 25863, "text": "arecord [flags] [filename]" }, { "code": null, "e": 25961, "s": 25890, "text": "If the filename is not specified then it uses Standard input. Options:" }, { "code": null, "e": 26020, "s": 25961, "text": "-h, –help : It is used to show the help messages and exit." }, { "code": null, "e": 26054, "s": 26020, "text": "–version : Print current version." }, { "code": null, "e": 26121, "s": 26054, "text": "-l, –list-devices : List all soundcards and digital audio devices." }, { "code": null, "e": 26184, "s": 26121, "text": "-L, –list-pcms : List all PCMs(Pulse Code Modulation) defined." }, { "code": null, "e": 26223, "s": 26184, "text": "-D, –device=NAME : Select PCM by name." }, { "code": null, "e": 26280, "s": 26223, "text": "-q –quiet : Quiet mode. Suppress messages (not sound :)." }, { "code": null, "e": 26387, "s": 26280, "text": "-t, –file-type TYPE File type (voc, wav, raw or au). If this parameter is omitted the WAVE format is used." }, { "code": null, "e": 26488, "s": 26387, "text": "-c, –channels=# : The number of channels. The default is one channel. Valid values are 1 through 32." }, { "code": null, "e": 26542, "s": 26488, "text": "-f –format=FORMAT : If no format is given U8 is used." }, { "code": null, "e": 26612, "s": 26542, "text": "-r, –rate=# : Sampling rate in Hertz. The default rate is 8000 Hertz." }, { "code": null, "e": 26657, "s": 26612, "text": "-d, –duration=# : Interrupt after # seconds." }, { "code": null, "e": 26725, "s": 26657, "text": "-s, –sleep-min=# : Min ticks to sleep. The default is not to sleep." }, { "code": null, "e": 26858, "s": 26725, "text": "-M, –mmap : Use memory-mapped (mmap) I/O mode for the audio stream. If this option is not set, the read/write I/O mode will be used." }, { "code": null, "e": 26975, "s": 26858, "text": "-N, –nonblock : Open the audio device in non-blocking mode. If the device is busy the program will exit immediately." }, { "code": null, "e": 27129, "s": 26975, "text": "Note: It contains various other options that we normally don’t need. If you want to know more about you can simply run following command on the terminal." }, { "code": null, "e": 27144, "s": 27129, "text": "arecord --help" }, { "code": null, "e": 27641, "s": 27144, "text": "Recognized Sample Formats are: S8 U8 S16_LE S16_BE U16_LE U16_BE S24_LE S24_BE U24_LE U24_BE S32_LE S32_BE U32_LE U32_BE FLOAT_LE FLOAT_BE FLOAT64_LE FLOAT64_BE IEC958_SUBFRAME_LE IEC958_SUBFRAME_BE MU_LAW A_LAW IMA_ADPCM MPEG GSM SPECIAL S24_3LE S24_3BE U24_3LE U24_3BE S20_3LE S20_3BE U20_3LE U20_3BE S18_3LE S18_3BE U18_3LE U18_3BE G723_24 G723_24_1B G723_40 G723_40_1B DSD_U8 DSD_U16_LE DSD_U32_LE DSD_U16_BE DSD_U32_BE Note: Some of these may not be available on selected hardware. Examples:" }, { "code": null, "e": 27754, "s": 27641, "text": "Recording audio through arecord (It will record an audio of 5 secs of U8 format and mp3 type named sample.mp3): " }, { "code": null, "e": 27815, "s": 27754, "text": "Now we will demonstrate how it really sounds like to record." }, { "code": null, "e": 27899, "s": 27815, "text": "Now we will play that recorded audio using aplay command.(microphone input is off.)" }, { "code": null, "e": 27908, "s": 27899, "text": "rkbhola5" }, { "code": null, "e": 27922, "s": 27908, "text": "linux-command" }, { "code": null, "e": 27929, "s": 27922, "text": "Picked" }, { "code": null, "e": 27940, "s": 27929, "text": "Linux-Unix" }, { "code": null, "e": 28038, "s": 27940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28076, "s": 28038, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28111, "s": 28076, "text": "ZIP command in Linux with examples" }, { "code": null, "e": 28152, "s": 28111, "text": "SORT command in Linux/Unix with examples" }, { "code": null, "e": 28187, "s": 28152, "text": "tar command in Linux with examples" }, { "code": null, "e": 28223, "s": 28187, "text": "curl command in Linux with Examples" }, { "code": null, "e": 28261, "s": 28223, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28297, "s": 28261, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28335, "s": 28297, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28371, "s": 28335, "text": "diff command in Linux with examples" } ]
C | Arrays | Question 7 - GeeksforGeeks
03 Aug, 2018 Consider the following declaration of a ‘two-dimensional array in C: char a[100][100]; Assuming that the main memory is byte-addressable and that the array is stored starting from memory address 0, the address of a[40][50] is (GATE CS 2002) (A) 4040(B) 4050(C) 5040(D) 5050Answer: (B)Explanation: Address of a[40][50] = Base address + 40*100*element_size + 50*element_size = 0 + 4000*1 + 50*1 = 4050 Based on row major or column major if row major then the result will be 4050 if column major then Address of a[40][50] = Base address + 50*100*element_size + 40*element_size = 0 + 5000*1 + 40*1 = 5040 Quiz of this Question GehadAhmed Arrays C-Arrays C Language C Quiz Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. fork() in C Function Pointer in C Substring in C++ std::string class in C++ Enumeration (or enum) in C Compiling a C program:- Behind the Scenes Operator Precedence and Associativity in C C | File Handling | Question 1 C | Misc | Question 7 C | Pointer Basics | Question 14
[ { "code": null, "e": 24172, "s": 24144, "text": "\n03 Aug, 2018" }, { "code": null, "e": 24241, "s": 24172, "text": "Consider the following declaration of a ‘two-dimensional array in C:" }, { "code": "char a[100][100]; ", "e": 24260, "s": 24241, "text": null }, { "code": null, "e": 24414, "s": 24260, "text": "Assuming that the main memory is byte-addressable and that the array is stored starting from memory address 0, the address of a[40][50] is (GATE CS 2002)" }, { "code": null, "e": 24470, "s": 24414, "text": "(A) 4040(B) 4050(C) 5040(D) 5050Answer: (B)Explanation:" }, { "code": null, "e": 24616, "s": 24470, "text": "Address of a[40][50] = Base address + 40*100*element_size + 50*element_size\n = 0 + 4000*1 + 50*1\n = 4050" }, { "code": null, "e": 24873, "s": 24616, "text": "Based on row major or column major\nif row major then the result will be 4050\nif column major then \n Address of a[40][50] = Base address + 50*100*element_size + 40*element_size\n = 0 + 5000*1 + 40*1\n = 5040" }, { "code": null, "e": 24895, "s": 24873, "text": "Quiz of this Question" }, { "code": null, "e": 24906, "s": 24895, "text": "GehadAhmed" }, { "code": null, "e": 24913, "s": 24906, "text": "Arrays" }, { "code": null, "e": 24922, "s": 24913, "text": "C-Arrays" }, { "code": null, "e": 24933, "s": 24922, "text": "C Language" }, { "code": null, "e": 24940, "s": 24933, "text": "C Quiz" }, { "code": null, "e": 24947, "s": 24940, "text": "Arrays" }, { "code": null, "e": 25045, "s": 24947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25057, "s": 25045, "text": "fork() in C" }, { "code": null, "e": 25079, "s": 25057, "text": "Function Pointer in C" }, { "code": null, "e": 25096, "s": 25079, "text": "Substring in C++" }, { "code": null, "e": 25121, "s": 25096, "text": "std::string class in C++" }, { "code": null, "e": 25148, "s": 25121, "text": "Enumeration (or enum) in C" }, { "code": null, "e": 25190, "s": 25148, "text": "Compiling a C program:- Behind the Scenes" }, { "code": null, "e": 25233, "s": 25190, "text": "Operator Precedence and Associativity in C" }, { "code": null, "e": 25264, "s": 25233, "text": "C | File Handling | Question 1" }, { "code": null, "e": 25286, "s": 25264, "text": "C | Misc | Question 7" } ]
C++ Program to print current Day, Date and Time - GeeksforGeeks
31 Jul, 2017 In order to facilitate finding the current local day, date and time, C++ has defined several functions in the header file , so functions which will help us in achieving our objective of finding local day, date and time are: time(): It is used to find the current calendar time. Its return type is time_t, which is an arithmetic data type capable of storing time returned by this function. If its argument is not NULL, then it assigns its argument the same value as its return value. localtime(): It uses the argument of time(), which has the same value as the return value of time(), to fill a structure having date and time as its components, with corresponding time in local timezone. asctime(): It is used to convert the contents in the structure filled by localtime into a human-readable version which finally returns day, date and time in the given format:Day Month Date hh:mm:ss Year Day Month Date hh:mm:ss Year // C++ program to find Current Day, Date// and Local Time#include<iostream>#include<ctime>using namespace std;int main(){ // Declaring argument for time() time_t tt; // Declaring variable to store return value of // localtime() struct tm * ti; // Applying time() time (&tt); // Using localtime() ti = localtime(&tt); cout << "Current Day, Date and Time is = " << asctime(ti); return 0;} Output: It will show the current day, date and localtime, in the format Day Month Date hh:mm:ss Year Points to remember: This program will give output different for different time zones as per the time in that time zone.The Day, Date and Time in the output is independent of the system day, date and time. You can change your system date and time settings, but still the output will not be affected, and will give the correct information. This program will give output different for different time zones as per the time in that time zone. The Day, Date and Time in the output is independent of the system day, date and time. You can change your system date and time settings, but still the output will not be affected, and will give the correct information. This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. CPP-Library date-time-program C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Inheritance in C++ Multidimensional Arrays in C / C++ Socket Programming in C/C++ C++ Classes and Objects Operator Overloading in C++ Bitwise Operators in C/C++ Constructors in C++ Virtual Function in C++ Copy Constructor in C++ Templates in C++ with Examples
[ { "code": null, "e": 24624, "s": 24596, "text": "\n31 Jul, 2017" }, { "code": null, "e": 24848, "s": 24624, "text": "In order to facilitate finding the current local day, date and time, C++ has defined several functions in the header file , so functions which will help us in achieving our objective of finding local day, date and time are:" }, { "code": null, "e": 24856, "s": 24848, "text": "time():" }, { "code": null, "e": 24902, "s": 24856, "text": "It is used to find the current calendar time." }, { "code": null, "e": 25013, "s": 24902, "text": "Its return type is time_t, which is an arithmetic data type capable of storing time returned by this function." }, { "code": null, "e": 25107, "s": 25013, "text": "If its argument is not NULL, then it assigns its argument the same value as its return value." }, { "code": null, "e": 25120, "s": 25107, "text": "localtime():" }, { "code": null, "e": 25311, "s": 25120, "text": "It uses the argument of time(), which has the same value as the return value of time(), to fill a structure having date and time as its components, with corresponding time in local timezone." }, { "code": null, "e": 25322, "s": 25311, "text": "asctime():" }, { "code": null, "e": 25515, "s": 25322, "text": "It is used to convert the contents in the structure filled by localtime into a human-readable version which finally returns day, date and time in the given format:Day Month Date hh:mm:ss Year\n" }, { "code": null, "e": 25545, "s": 25515, "text": "Day Month Date hh:mm:ss Year\n" }, { "code": "// C++ program to find Current Day, Date// and Local Time#include<iostream>#include<ctime>using namespace std;int main(){ // Declaring argument for time() time_t tt; // Declaring variable to store return value of // localtime() struct tm * ti; // Applying time() time (&tt); // Using localtime() ti = localtime(&tt); cout << \"Current Day, Date and Time is = \" << asctime(ti); return 0;}", "e": 25982, "s": 25545, "text": null }, { "code": null, "e": 25990, "s": 25982, "text": "Output:" }, { "code": null, "e": 26084, "s": 25990, "text": "It will show the current day, date and localtime, in the\nformat Day Month Date hh:mm:ss Year\n" }, { "code": null, "e": 26104, "s": 26084, "text": "Points to remember:" }, { "code": null, "e": 26422, "s": 26104, "text": "This program will give output different for different time zones as per the time in that time zone.The Day, Date and Time in the output is independent of the system day, date and time. You can change your system date and time settings, but still the output will not be affected, and will give the correct information." }, { "code": null, "e": 26522, "s": 26422, "text": "This program will give output different for different time zones as per the time in that time zone." }, { "code": null, "e": 26741, "s": 26522, "text": "The Day, Date and Time in the output is independent of the system day, date and time. You can change your system date and time settings, but still the output will not be affected, and will give the correct information." }, { "code": null, "e": 27044, "s": 26741, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27169, "s": 27044, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27181, "s": 27169, "text": "CPP-Library" }, { "code": null, "e": 27199, "s": 27181, "text": "date-time-program" }, { "code": null, "e": 27203, "s": 27199, "text": "C++" }, { "code": null, "e": 27207, "s": 27203, "text": "CPP" }, { "code": null, "e": 27305, "s": 27207, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27314, "s": 27305, "text": "Comments" }, { "code": null, "e": 27327, "s": 27314, "text": "Old Comments" }, { "code": null, "e": 27346, "s": 27327, "text": "Inheritance in C++" }, { "code": null, "e": 27381, "s": 27346, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27409, "s": 27381, "text": "Socket Programming in C/C++" }, { "code": null, "e": 27433, "s": 27409, "text": "C++ Classes and Objects" }, { "code": null, "e": 27461, "s": 27433, "text": "Operator Overloading in C++" }, { "code": null, "e": 27488, "s": 27461, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 27508, "s": 27488, "text": "Constructors in C++" }, { "code": null, "e": 27532, "s": 27508, "text": "Virtual Function in C++" }, { "code": null, "e": 27556, "s": 27532, "text": "Copy Constructor in C++" } ]
Sorted insert for circular linked list
28 Jun, 2022 Difficulty Level: Rookie Write a C function to insert a new value in a sorted Circular Linked List (CLL). For example, if the input CLL is following. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Algorithm: Allocate memory for the newly inserted node and put data in the newly allocated node. Let the pointer to the new node be new_node. After memory allocation, following are the three cases that need to be handled. 1) Linked List is empty: a) since new_node is the only node in CLL, make a self loop. new_node->next = new_node; b) change the head pointer to point to new node. *head_ref = new_node; 2) New node is to be inserted just before the head node: (a) Find out the last node using a loop. while(current->next != *head_ref) current = current->next; (b) Change the next of last node. current->next = new_node; (c) Change next of new node to point to head. new_node->next = *head_ref; (d) change the head pointer to point to new node. *head_ref = new_node; 3) New node is to be inserted somewhere after the head: (a) Locate the node after which new node is to be inserted. while ( current->next!= *head_ref && current->next->data < new_node->data) { current = current->next; } (b) Make next of new_node as next of the located pointer new_node->next = current->next; (c) Change the next of the located pointer current->next = new_node; C++ C Java Python3 C# Javascript // C++ program for sorted insert// in circular linked list#include <bits/stdc++.h>using namespace std; /* structure for a node */class Node{ public: int data; Node *next;}; /* function to insert a new_node in a list in sorted way.Note that this function expects a pointer to head nodeas this can modify the head of the input linked list */void sortedInsert(Node** head_ref, Node* new_node){ Node* current = *head_ref; // Case 1 of the above algo if (current == NULL) { new_node->next = new_node; *head_ref = new_node; } // Case 2 of the above algo else if (current->data >= new_node->data) { /* If value is smaller than head's value then we need to change next of last node */ while(current->next != *head_ref) current = current->next; current->next = new_node; new_node->next = *head_ref; *head_ref = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current->next!= *head_ref && current->next->data < new_node->data) current = current->next; new_node->next = current->next; current->next = new_node; }} /* Function to print nodes in a given linked list */void printList(Node *start){ Node *temp; if(start != NULL) { temp = start; do { cout<<temp->data<<" "; temp = temp->next; } while(temp != start); }} /* Driver code */int main(){ int arr[] = {12, 56, 2, 11, 1, 90}; int list_size, i; /* start with empty linked list */ Node *start = NULL; Node *temp; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90 */ for (i = 0; i< 6; i++) { temp = new Node(); temp->data = arr[i]; sortedInsert(&start, temp); } printList(start); return 0;} // This code is contributed by rathbhupendra. #include<stdio.h>#include<stdlib.h> /* structure for a node */struct Node{ int data; struct Node *next;}; /* function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list */void sortedInsert(struct Node** head_ref, struct Node* new_node){ struct Node* current = *head_ref; // Case 1 of the above algo if (current == NULL) { new_node->next = new_node; *head_ref = new_node; } // Case 2 of the above algo else if (current->data >= new_node->data) { /* If value is smaller than head's value then we need to change next of last node */ while(current->next != *head_ref) current = current->next; current->next = new_node; new_node->next = *head_ref; *head_ref = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current->next!= *head_ref && current->next->data < new_node->data) current = current->next; new_node->next = current->next; current->next = new_node; }} /* Function to print nodes in a given linked list */void printList(struct Node *start){ struct Node *temp; if(start != NULL) { temp = start; printf("\n"); do { printf("%d ", temp->data); temp = temp->next; } while(temp != start); }} /* Driver program to test above functions */int main(){ int arr[] = {12, 56, 2, 11, 1, 90}; int list_size, i; /* start with empty linked list */ struct Node *start = NULL; struct Node *temp; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90 */ for (i = 0; i< 6; i++) { temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = arr[i]; sortedInsert(&start, temp); } printList(start); return 0;} // Java program for sorted insert in circular linked list class Node{ int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList{ Node head; // Constructor LinkedList() { head = null; } /* function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list */ void sortedInsert(Node new_node) { Node current = head; // Case 1 of the above algo if (current == null) { new_node.next = new_node; head = new_node; } // Case 2 of the above algo else if (current.data >= new_node.data) { /* If value is smaller than head's value then we need to change next of last node */ while (current.next != head) current = current.next; current.next = new_node; new_node.next = head; head = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current.next != head && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } // Utility method to print a linked list void printList() { if (head != null) { Node temp = head; do { System.out.print(temp.data + " "); temp = temp.next; } while (temp != head); } } // Driver code to test above public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist int arr[] = new int[] {12, 56, 2, 11, 1, 90}; /* start with empty linked list */ Node temp = null; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90*/ for (int i = 0; i < 6; i++) { temp = new Node(arr[i]); list.sortedInsert(temp); } list.printList(); }} // This code has been contributed by Mayank Jaiswal # Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head print(temp.data,end=' ') temp = temp.next while(temp != self.head): print (temp.data,end=' ') temp = temp.next """ function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list """ def sortedInsert(self, new_node): current = self.head # Case 1 of the above algo if current is None: new_node.next = new_node self.head = new_node # Case 2 of the above algo elif (current.data >= new_node.data): # If value is smaller than head's value then we # need to change next of last node while current.next != self.head : current = current.next current.next = new_node new_node.next = self.head self.head = new_node # Case 3 of the above algo else: # Locate the node before the point of insertion while (current.next != self.head and current.next.data < new_node.data): current = current.next new_node.next = current.next current.next = new_node # Driver program to test the above function#llist = LinkedList()arr = [12, 56, 2, 11, 1, 90] list_size = len(arr) # start with empty linked liststart = LinkedList() # Create linked list from the array arr[]# Created linked list will be 1->2->11->12->56->90for i in range(list_size): temp = Node(arr[i]) start.sortedInsert(temp) start.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program for sorted insert// in circular linked listusing System; class LinkedList{ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } Node head; // Constructor LinkedList() { head = null; } /* function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list */ void sortedInsert(Node new_node) { Node current = head; // Case 1 of the above algo if (current == null) { new_node.next = new_node; head = new_node; } // Case 2 of the above algo else if (current.data >= new_node.data) { /* If value is smaller than head's value then we need to change next of last node */ while (current.next != head) current = current.next; current.next = new_node; new_node.next = head; head = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current.next != head && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } // Utility method to print a linked list void printList() { if (head != null) { Node temp = head; do { Console.Write(temp.data + " "); temp = temp.next; } while (temp != head); } } // Driver code public static void Main(String []args) { LinkedList list = new LinkedList(); // Creating the linkedlist int []arr = {12, 56, 2, 11, 1, 90}; /* start with empty linked list */ Node temp = null; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90*/ for (int i = 0; i < 6; i++) { temp = new Node(arr[i]); list.sortedInsert(temp); } list.printList(); }} // This code has been contributed// by Arnab Kundu <script>// javascript program for sorted insert in circular linked list class Node { constructor(val) { this.data = val; this.next = null; }} var head = null; /* * function to insert a new_node in a list in sorted way. * Note that this function expects a pointer to head node * as this can modify the head of the * input linked list */ function sortedInsert(new_node) { var current = head; // Case 1 of the above algo if (current == null) { new_node.next = new_node; head = new_node; } // Case 2 of the above algo else if (current.data >= new_node.data) { /* * If value is smaller than head's value then we * need to change next of last node */ while (current.next != head) current = current.next; current.next = new_node; new_node.next = head; head = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current.next != head && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } // Utility method to print a linked list function printList() { if (head != null) { var temp = head; do { document.write(temp.data + " "); temp = temp.next; } while (temp != head); } } // Driver code to test above // Creating the linkedlist var arr = [ 12, 56, 2, 11, 1, 90 ]; /* start with empty linked list */ var temp = null; /* * Create linked list from the array arr. * Created linked list will be * 1->2->11->12->56->90 */ for (i = 0; i < 6; i++) { temp = new Node(arr[i]); sortedInsert(temp); } printList(); // This code contributed by umadevi9616</script> Output: 1 2 11 12 56 90 Time Complexity: O(n) Here n is the number of nodes in the given linked list. Auxiliary Space: O(1). As constant extra space is used. Case 2 of the above algorithm/code can be optimized. To implement the suggested change we need to modify case 2 to follow. C C++ Java Python3 C# Javascript // Case 2 of the above algoelse if (current->data >= new_node->data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) swap(&(current->data), &(new_node->data)); new_node->next = (*head_ref)->next; (*head_ref)->next = new_node;} // Case 2 of the above algo else if (current->data >= new_node->data) { // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) swap(&(current->data), &(new_node->data)); new_node->next = (*head_ref)->next; (*head_ref)->next = new_node; }// this code is contributed by devendra salunke // Case 2 of the above algoelse if (current.data >= new_node.data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) Node tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node;} // This code is contributed by pratham76. # Case 2 of the above algoelif (current.data >= new_node.data): # swap the data part of head node and new node # assuming that we have a function swap(int *, int *) tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node; # This code is contributed by _saurabh_jaiswal // Case 2 of the above algoelse if (current.data >= new_node.data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) Node tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node;} // This code is contributed by rutvik_56 <script> // Case 2 of the above algoelse if (current.data >= new_node.data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) let tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node;} // This code is contributed by avanitrachhadiya2155 </script> In the previous approach the time complexity of case 2 was O(n) which is reduced to O(1) using this approach. The auxiliary space used here is O(1) which is same as previous approach. Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem. andrew1234 rathbhupendra rutvik_56 pratham76 umadevi9616 avanitrachhadiya2155 _saurabh_jaiswal arorakashish0911 amartyaghoshgfg sambitskd3 rohitsingh07052 devendrasalunke hardikkoriintern abhijeet19403 Amazon circular linked list Microsoft Zoho Linked List Zoho Amazon Microsoft Linked List circular linked list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2022" }, { "code": null, "e": 202, "s": 52, "text": "Difficulty Level: Rookie Write a C function to insert a new value in a sorted Circular Linked List (CLL). For example, if the input CLL is following." }, { "code": null, "e": 211, "s": 202, "text": "Chapters" }, { "code": null, "e": 238, "s": 211, "text": "descriptions off, selected" }, { "code": null, "e": 288, "s": 238, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 311, "s": 288, "text": "captions off, selected" }, { "code": null, "e": 319, "s": 311, "text": "English" }, { "code": null, "e": 343, "s": 319, "text": "This is a modal window." }, { "code": null, "e": 412, "s": 343, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 434, "s": 412, "text": "End of dialog window." }, { "code": null, "e": 446, "s": 434, "text": "Algorithm: " }, { "code": null, "e": 659, "s": 446, "text": "Allocate memory for the newly inserted node and put data in the newly allocated node. Let the pointer to the new node be new_node. After memory allocation, following are the three cases that need to be handled. " }, { "code": null, "e": 1749, "s": 659, "text": "1) Linked List is empty: \n a) since new_node is the only node in CLL, make a self loop. \n new_node->next = new_node; \n b) change the head pointer to point to new node.\n *head_ref = new_node;\n2) New node is to be inserted just before the head node: \n (a) Find out the last node using a loop.\n while(current->next != *head_ref)\n current = current->next;\n (b) Change the next of last node. \n current->next = new_node;\n (c) Change next of new node to point to head.\n new_node->next = *head_ref;\n (d) change the head pointer to point to new node.\n *head_ref = new_node;\n3) New node is to be inserted somewhere after the head: \n (a) Locate the node after which new node is to be inserted.\n while ( current->next!= *head_ref && \n current->next->data < new_node->data)\n { current = current->next; }\n (b) Make next of new_node as next of the located pointer\n new_node->next = current->next;\n (c) Change the next of the located pointer\n current->next = new_node;" }, { "code": null, "e": 1753, "s": 1749, "text": "C++" }, { "code": null, "e": 1755, "s": 1753, "text": "C" }, { "code": null, "e": 1760, "s": 1755, "text": "Java" }, { "code": null, "e": 1768, "s": 1760, "text": "Python3" }, { "code": null, "e": 1771, "s": 1768, "text": "C#" }, { "code": null, "e": 1782, "s": 1771, "text": "Javascript" }, { "code": "// C++ program for sorted insert// in circular linked list#include <bits/stdc++.h>using namespace std; /* structure for a node */class Node{ public: int data; Node *next;}; /* function to insert a new_node in a list in sorted way.Note that this function expects a pointer to head nodeas this can modify the head of the input linked list */void sortedInsert(Node** head_ref, Node* new_node){ Node* current = *head_ref; // Case 1 of the above algo if (current == NULL) { new_node->next = new_node; *head_ref = new_node; } // Case 2 of the above algo else if (current->data >= new_node->data) { /* If value is smaller than head's value then we need to change next of last node */ while(current->next != *head_ref) current = current->next; current->next = new_node; new_node->next = *head_ref; *head_ref = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current->next!= *head_ref && current->next->data < new_node->data) current = current->next; new_node->next = current->next; current->next = new_node; }} /* Function to print nodes in a given linked list */void printList(Node *start){ Node *temp; if(start != NULL) { temp = start; do { cout<<temp->data<<\" \"; temp = temp->next; } while(temp != start); }} /* Driver code */int main(){ int arr[] = {12, 56, 2, 11, 1, 90}; int list_size, i; /* start with empty linked list */ Node *start = NULL; Node *temp; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90 */ for (i = 0; i< 6; i++) { temp = new Node(); temp->data = arr[i]; sortedInsert(&start, temp); } printList(start); return 0;} // This code is contributed by rathbhupendra.", "e": 3774, "s": 1782, "text": null }, { "code": "#include<stdio.h>#include<stdlib.h> /* structure for a node */struct Node{ int data; struct Node *next;}; /* function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list */void sortedInsert(struct Node** head_ref, struct Node* new_node){ struct Node* current = *head_ref; // Case 1 of the above algo if (current == NULL) { new_node->next = new_node; *head_ref = new_node; } // Case 2 of the above algo else if (current->data >= new_node->data) { /* If value is smaller than head's value then we need to change next of last node */ while(current->next != *head_ref) current = current->next; current->next = new_node; new_node->next = *head_ref; *head_ref = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current->next!= *head_ref && current->next->data < new_node->data) current = current->next; new_node->next = current->next; current->next = new_node; }} /* Function to print nodes in a given linked list */void printList(struct Node *start){ struct Node *temp; if(start != NULL) { temp = start; printf(\"\\n\"); do { printf(\"%d \", temp->data); temp = temp->next; } while(temp != start); }} /* Driver program to test above functions */int main(){ int arr[] = {12, 56, 2, 11, 1, 90}; int list_size, i; /* start with empty linked list */ struct Node *start = NULL; struct Node *temp; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90 */ for (i = 0; i< 6; i++) { temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = arr[i]; sortedInsert(&start, temp); } printList(start); return 0;}", "e": 5606, "s": 3774, "text": null }, { "code": "// Java program for sorted insert in circular linked list class Node{ int data; Node next; Node(int d) { data = d; next = null; }} class LinkedList{ Node head; // Constructor LinkedList() { head = null; } /* function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list */ void sortedInsert(Node new_node) { Node current = head; // Case 1 of the above algo if (current == null) { new_node.next = new_node; head = new_node; } // Case 2 of the above algo else if (current.data >= new_node.data) { /* If value is smaller than head's value then we need to change next of last node */ while (current.next != head) current = current.next; current.next = new_node; new_node.next = head; head = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current.next != head && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } // Utility method to print a linked list void printList() { if (head != null) { Node temp = head; do { System.out.print(temp.data + \" \"); temp = temp.next; } while (temp != head); } } // Driver code to test above public static void main(String[] args) { LinkedList list = new LinkedList(); // Creating the linkedlist int arr[] = new int[] {12, 56, 2, 11, 1, 90}; /* start with empty linked list */ Node temp = null; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90*/ for (int i = 0; i < 6; i++) { temp = new Node(arr[i]); list.sortedInsert(temp); } list.printList(); }} // This code has been contributed by Mayank Jaiswal", "e": 7877, "s": 5606, "text": null }, { "code": "# Node classclass Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Utility function to print the linked LinkedList def printList(self): temp = self.head print(temp.data,end=' ') temp = temp.next while(temp != self.head): print (temp.data,end=' ') temp = temp.next \"\"\" function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list \"\"\" def sortedInsert(self, new_node): current = self.head # Case 1 of the above algo if current is None: new_node.next = new_node self.head = new_node # Case 2 of the above algo elif (current.data >= new_node.data): # If value is smaller than head's value then we # need to change next of last node while current.next != self.head : current = current.next current.next = new_node new_node.next = self.head self.head = new_node # Case 3 of the above algo else: # Locate the node before the point of insertion while (current.next != self.head and current.next.data < new_node.data): current = current.next new_node.next = current.next current.next = new_node # Driver program to test the above function#llist = LinkedList()arr = [12, 56, 2, 11, 1, 90] list_size = len(arr) # start with empty linked liststart = LinkedList() # Create linked list from the array arr[]# Created linked list will be 1->2->11->12->56->90for i in range(list_size): temp = Node(arr[i]) start.sortedInsert(temp) start.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 10113, "s": 7877, "text": null }, { "code": "// C# program for sorted insert// in circular linked listusing System; class LinkedList{ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } Node head; // Constructor LinkedList() { head = null; } /* function to insert a new_node in a list in sorted way. Note that this function expects a pointer to head node as this can modify the head of the input linked list */ void sortedInsert(Node new_node) { Node current = head; // Case 1 of the above algo if (current == null) { new_node.next = new_node; head = new_node; } // Case 2 of the above algo else if (current.data >= new_node.data) { /* If value is smaller than head's value then we need to change next of last node */ while (current.next != head) current = current.next; current.next = new_node; new_node.next = head; head = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current.next != head && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } // Utility method to print a linked list void printList() { if (head != null) { Node temp = head; do { Console.Write(temp.data + \" \"); temp = temp.next; } while (temp != head); } } // Driver code public static void Main(String []args) { LinkedList list = new LinkedList(); // Creating the linkedlist int []arr = {12, 56, 2, 11, 1, 90}; /* start with empty linked list */ Node temp = null; /* Create linked list from the array arr[]. Created linked list will be 1->2->11->12->56->90*/ for (int i = 0; i < 6; i++) { temp = new Node(arr[i]); list.sortedInsert(temp); } list.printList(); }} // This code has been contributed// by Arnab Kundu", "e": 12505, "s": 10113, "text": null }, { "code": "<script>// javascript program for sorted insert in circular linked list class Node { constructor(val) { this.data = val; this.next = null; }} var head = null; /* * function to insert a new_node in a list in sorted way. * Note that this function expects a pointer to head node * as this can modify the head of the * input linked list */ function sortedInsert(new_node) { var current = head; // Case 1 of the above algo if (current == null) { new_node.next = new_node; head = new_node; } // Case 2 of the above algo else if (current.data >= new_node.data) { /* * If value is smaller than head's value then we * need to change next of last node */ while (current.next != head) current = current.next; current.next = new_node; new_node.next = head; head = new_node; } // Case 3 of the above algo else { /* Locate the node before the point of insertion */ while (current.next != head && current.next.data < new_node.data) current = current.next; new_node.next = current.next; current.next = new_node; } } // Utility method to print a linked list function printList() { if (head != null) { var temp = head; do { document.write(temp.data + \" \"); temp = temp.next; } while (temp != head); } } // Driver code to test above // Creating the linkedlist var arr = [ 12, 56, 2, 11, 1, 90 ]; /* start with empty linked list */ var temp = null; /* * Create linked list from the array arr. * Created linked list will be * 1->2->11->12->56->90 */ for (i = 0; i < 6; i++) { temp = new Node(arr[i]); sortedInsert(temp); } printList(); // This code contributed by umadevi9616</script>", "e": 14587, "s": 12505, "text": null }, { "code": null, "e": 14597, "s": 14587, "text": "Output: " }, { "code": null, "e": 14613, "s": 14597, "text": "1 2 11 12 56 90" }, { "code": null, "e": 14635, "s": 14613, "text": "Time Complexity: O(n)" }, { "code": null, "e": 14691, "s": 14635, "text": "Here n is the number of nodes in the given linked list." }, { "code": null, "e": 14714, "s": 14691, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 14747, "s": 14714, "text": "As constant extra space is used." }, { "code": null, "e": 14871, "s": 14747, "text": "Case 2 of the above algorithm/code can be optimized. To implement the suggested change we need to modify case 2 to follow. " }, { "code": null, "e": 14873, "s": 14871, "text": "C" }, { "code": null, "e": 14877, "s": 14873, "text": "C++" }, { "code": null, "e": 14882, "s": 14877, "text": "Java" }, { "code": null, "e": 14890, "s": 14882, "text": "Python3" }, { "code": null, "e": 14893, "s": 14890, "text": "C#" }, { "code": null, "e": 14904, "s": 14893, "text": "Javascript" }, { "code": "// Case 2 of the above algoelse if (current->data >= new_node->data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) swap(&(current->data), &(new_node->data)); new_node->next = (*head_ref)->next; (*head_ref)->next = new_node;}", "e": 15193, "s": 14904, "text": null }, { "code": " // Case 2 of the above algo else if (current->data >= new_node->data) { // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) swap(&(current->data), &(new_node->data)); new_node->next = (*head_ref)->next; (*head_ref)->next = new_node; }// this code is contributed by devendra salunke", "e": 15547, "s": 15193, "text": null }, { "code": "// Case 2 of the above algoelse if (current.data >= new_node.data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) Node tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node;} // This code is contributed by pratham76.", "e": 15905, "s": 15547, "text": null }, { "code": "# Case 2 of the above algoelif (current.data >= new_node.data): # swap the data part of head node and new node # assuming that we have a function swap(int *, int *) tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node; # This code is contributed by _saurabh_jaiswal", "e": 16259, "s": 15905, "text": null }, { "code": "// Case 2 of the above algoelse if (current.data >= new_node.data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) Node tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node;} // This code is contributed by rutvik_56", "e": 16616, "s": 16259, "text": null }, { "code": "<script> // Case 2 of the above algoelse if (current.data >= new_node.data){ // swap the data part of head node and new node // assuming that we have a function swap(int *, int *) let tmp = current.data; current.data = new_node.data; new_node.data = tmp; new_node.next = (head_ref).next; (head_ref).next = new_node;} // This code is contributed by avanitrachhadiya2155 </script>", "e": 17004, "s": 16616, "text": null }, { "code": null, "e": 17114, "s": 17004, "text": "In the previous approach the time complexity of case 2 was O(n) which is reduced to O(1) using this approach." }, { "code": null, "e": 17188, "s": 17114, "text": "The auxiliary space used here is O(1) which is same as previous approach." }, { "code": null, "e": 17305, "s": 17188, "text": "Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem. " }, { "code": null, "e": 17316, "s": 17305, "text": "andrew1234" }, { "code": null, "e": 17330, "s": 17316, "text": "rathbhupendra" }, { "code": null, "e": 17340, "s": 17330, "text": "rutvik_56" }, { "code": null, "e": 17350, "s": 17340, "text": "pratham76" }, { "code": null, "e": 17362, "s": 17350, "text": "umadevi9616" }, { "code": null, "e": 17383, "s": 17362, "text": "avanitrachhadiya2155" }, { "code": null, "e": 17400, "s": 17383, "text": "_saurabh_jaiswal" }, { "code": null, "e": 17417, "s": 17400, "text": "arorakashish0911" }, { "code": null, "e": 17433, "s": 17417, "text": "amartyaghoshgfg" }, { "code": null, "e": 17444, "s": 17433, "text": "sambitskd3" }, { "code": null, "e": 17460, "s": 17444, "text": "rohitsingh07052" }, { "code": null, "e": 17476, "s": 17460, "text": "devendrasalunke" }, { "code": null, "e": 17493, "s": 17476, "text": "hardikkoriintern" }, { "code": null, "e": 17507, "s": 17493, "text": "abhijeet19403" }, { "code": null, "e": 17514, "s": 17507, "text": "Amazon" }, { "code": null, "e": 17535, "s": 17514, "text": "circular linked list" }, { "code": null, "e": 17545, "s": 17535, "text": "Microsoft" }, { "code": null, "e": 17550, "s": 17545, "text": "Zoho" }, { "code": null, "e": 17562, "s": 17550, "text": "Linked List" }, { "code": null, "e": 17567, "s": 17562, "text": "Zoho" }, { "code": null, "e": 17574, "s": 17567, "text": "Amazon" }, { "code": null, "e": 17584, "s": 17574, "text": "Microsoft" }, { "code": null, "e": 17596, "s": 17584, "text": "Linked List" }, { "code": null, "e": 17617, "s": 17596, "text": "circular linked list" } ]
Sublist Search (Search a linked list in another list)
06 Jul, 2022 Given two linked lists, the task is to check whether the first list is present in 2nd list or not. Examples: Input : list1 = 10->20 list2 = 5->10->20 Output : LIST FOUND Input : list1 = 1->2->3->4 list2 = 1->2->1->2->3->4 Output : LIST FOUND Input : list1 = 1->2->3->4 list2 = 1->2->2->1->2->3 Output : LIST NOT FOUND Algorithm: Take first node of second list. Start matching the first list from this first node. If whole lists match return true. Else break and take first list to the first node again. And take second list to its second node. Repeat these steps until any of linked lists becomes empty. If first list becomes empty then list found else not. Take first node of second list. Start matching the first list from this first node. If whole lists match return true. Else break and take first list to the first node again. And take second list to its second node. Repeat these steps until any of linked lists becomes empty. If first list becomes empty then list found else not. Below is the implementation. C++ Java Python3 C# Javascript // C++ program to find a list in second list#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node{ int data; Node* next;}; // Returns true if first list is present in second// listbool findList(Node* first, Node* second){ Node* ptr1 = first, *ptr2 = second; // If both linked lists are empty, return true if (first == NULL && second == NULL) return true; // Else If one is empty and other is not return // false if ( first == NULL || (first != NULL && second == NULL)) return false; // Traverse the second list by picking nodes // one by one while (second != NULL) { // Initialize ptr2 with current node of second ptr2 = second; // Start matching first list with second list while (ptr1 != NULL) { // If second list becomes empty and first // not then return false if (ptr2 == NULL) return false; // If data part is same, go to next // of both lists else if (ptr1->data == ptr2->data) { ptr1 = ptr1->next; ptr2 = ptr2->next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == NULL) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second->next; } return false;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // Function to add new node to linked listsNode *newNode(int key){ Node *temp = new Node; temp-> data= key; temp->next = NULL; return temp;} /* Driver program to test above functions*/int main(){ /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node *a = newNode(1); a->next = newNode(2); a->next->next = newNode(3); a->next->next->next = newNode(4); Node *b = newNode(1); b->next = newNode(2); b->next->next = newNode(1); b->next->next->next = newNode(2); b->next->next->next->next = newNode(3); b->next->next->next->next->next = newNode(4); findList(a,b) ? cout << "LIST FOUND" : cout << "LIST NOT FOUND"; return 0;} // Java program to find a list in second listimport java.util.*;class GFG{ // A Linked List nodestatic class Node{ int data; Node next;}; // Returns true if first list is// present in second liststatic boolean findList(Node first, Node second){ Node ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false;} /* Function to print nodes in a given linked list */static void printList(Node node){ while (node != null) { System.out.printf("%d ", node.data); node = node.next; }} // Function to add new node to linked listsstatic Node newNode(int key){ Node temp = new Node(); temp.data= key; temp.next = null; return temp;} // Driver Codepublic static void main(String[] args){ /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); Node b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if(findList(a, b) == true) System.out.println("LIST FOUND"); else System.out.println("LIST NOT FOUND");}} // This code is contributed by Princi Singh # Python3 program to find a list in second listclass Node: def __init__(self, value = 0): self.value = value self.next = None # Returns true if first list is# present in second listdef findList(first, second): # If both linked lists are empty/None, # return True if not first and not second: return True # If ONLY one of them is empty, # return False if not first or not second: return False ptr1 = first ptr2 = second # Traverse the second LL by # picking nodes one by one while ptr2: # Initialize 'ptr2' with current # node of 'second' ptr2 = second # Start matching first LL # with second LL while ptr1: # If second LL become empty and # first not, return False, # since first LL has not been # traversed completely if not ptr2: return False # If value of both nodes from both # LLs are equal, increment pointers # for both LLs so that next value # can be matched else if ptr1.value == ptr2.value: ptr1 = ptr1.next ptr2 = ptr2.next # If a single mismatch is found # OR ptr1 is None/empty,break out # of the while loop and do some checks else: break # check 1 : # If 'ptr1' is None/empty,that means # the 'first LL' has been completely # traversed and matched so return True if not ptr1: return True # If check 1 fails, that means, some # items for 'first' LL are still yet # to be matched, so start again by # bringing back the 'ptr1' to point # to 1st node of 'first' LL ptr1 = first # And increment second node element to next second = second.next return False # Driver Code # Let us create two linked lists to# test the above functions.# Created lists would be be# node_a: 1->2->3->4# node_b: 1->2->1->2->3->4node_a = Node(1)node_a.next = Node(2)node_a.next.next = Node(3)node_a.next.next.next = Node(4) node_b = Node(1)node_b.next = Node(2)node_b.next.next = Node(1)node_b.next.next.next = Node(2)node_b.next.next.next.next = Node(3)node_b.next.next.next.next.next = Node(4) if findList(node_a, node_b): print("LIST FOUND")else: print("LIST NOT FOUND") # This code is contributed by GauriShankarBadola // C# program to find a list in second listusing System; class GFG{ // A Linked List nodeclass Node{ public int data; public Node next;}; // Returns true if first list is// present in second liststatic Boolean findList(Node first, Node second){ Node ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false;} /* Function to print nodesin a given linked list */static void printList(Node node){ while (node != null) { Console.Write("{0} ", node.data); node = node.next; }} // Function to add new node to linked listsstatic Node newNode(int key){ Node temp = new Node(); temp.data= key; temp.next = null; return temp;} // Driver Codepublic static void Main(String[] args){ /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); Node b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if(findList(a, b) == true) Console.Write("LIST FOUND"); else Console.Write("LIST NOT FOUND");}} // This code is contributed by Rajput-Ji <script> // JavaScript program to find a// list in second list // A Linked List node class Node { constructor() { this.data = 0; this.next = null; }} // Returns true if first list is // present in second list function findList(first, second) { var ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false; } /* Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write("%d ", node.data); node = node.next; } } // Function to add new node to linked lists function newNode(key) { var temp = new Node(); temp.data = key; temp.next = null; return temp; } // Driver Code /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4 */ var a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); var b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if (findList(a, b) == true) document.write("LIST FOUND"); else document.write("LIST NOT FOUND"); // This code contributed by gauravrajput1 </script> LIST FOUND Time Complexity: O(m*n) where m is the number of nodes in second list and n in first. Optimization : Above code can be optimized by using extra space i.e. stores the list into two strings and apply KMP algorithm. Refer https://ide.geeksforgeeks.org/3fXUaV for implementation provided by Nishant Singh This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. princi singh Rajput-Ji GauriShankarBadola GauravRajput1 simmytarika5 hardikkoriintern Linked List Searching Linked List Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) LinkedList in Java Maximum and minimum of an array using minimum number of comparisons K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array Search, insert and delete in an unsorted array Find the Missing Number
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 152, "s": 52, "text": "Given two linked lists, the task is to check whether the first list is present in 2nd list or not. " }, { "code": null, "e": 162, "s": 152, "text": "Examples:" }, { "code": null, "e": 409, "s": 162, "text": "Input : list1 = 10->20\n list2 = 5->10->20\nOutput : LIST FOUND\n\nInput : list1 = 1->2->3->4\n list2 = 1->2->1->2->3->4\nOutput : LIST FOUND\n\nInput : list1 = 1->2->3->4\n list2 = 1->2->2->1->2->3\nOutput : LIST NOT FOUND" }, { "code": null, "e": 421, "s": 409, "text": "Algorithm: " }, { "code": null, "e": 750, "s": 421, "text": "Take first node of second list. Start matching the first list from this first node. If whole lists match return true. Else break and take first list to the first node again. And take second list to its second node. Repeat these steps until any of linked lists becomes empty. If first list becomes empty then list found else not." }, { "code": null, "e": 783, "s": 750, "text": "Take first node of second list. " }, { "code": null, "e": 836, "s": 783, "text": "Start matching the first list from this first node. " }, { "code": null, "e": 871, "s": 836, "text": "If whole lists match return true. " }, { "code": null, "e": 928, "s": 871, "text": "Else break and take first list to the first node again. " }, { "code": null, "e": 970, "s": 928, "text": "And take second list to its second node. " }, { "code": null, "e": 1031, "s": 970, "text": "Repeat these steps until any of linked lists becomes empty. " }, { "code": null, "e": 1085, "s": 1031, "text": "If first list becomes empty then list found else not." }, { "code": null, "e": 1114, "s": 1085, "text": "Below is the implementation." }, { "code": null, "e": 1118, "s": 1114, "text": "C++" }, { "code": null, "e": 1123, "s": 1118, "text": "Java" }, { "code": null, "e": 1131, "s": 1123, "text": "Python3" }, { "code": null, "e": 1134, "s": 1131, "text": "C#" }, { "code": null, "e": 1145, "s": 1134, "text": "Javascript" }, { "code": "// C++ program to find a list in second list#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node{ int data; Node* next;}; // Returns true if first list is present in second// listbool findList(Node* first, Node* second){ Node* ptr1 = first, *ptr2 = second; // If both linked lists are empty, return true if (first == NULL && second == NULL) return true; // Else If one is empty and other is not return // false if ( first == NULL || (first != NULL && second == NULL)) return false; // Traverse the second list by picking nodes // one by one while (second != NULL) { // Initialize ptr2 with current node of second ptr2 = second; // Start matching first list with second list while (ptr1 != NULL) { // If second list becomes empty and first // not then return false if (ptr2 == NULL) return false; // If data part is same, go to next // of both lists else if (ptr1->data == ptr2->data) { ptr1 = ptr1->next; ptr2 = ptr2->next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == NULL) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second->next; } return false;} /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // Function to add new node to linked listsNode *newNode(int key){ Node *temp = new Node; temp-> data= key; temp->next = NULL; return temp;} /* Driver program to test above functions*/int main(){ /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node *a = newNode(1); a->next = newNode(2); a->next->next = newNode(3); a->next->next->next = newNode(4); Node *b = newNode(1); b->next = newNode(2); b->next->next = newNode(1); b->next->next->next = newNode(2); b->next->next->next->next = newNode(3); b->next->next->next->next->next = newNode(4); findList(a,b) ? cout << \"LIST FOUND\" : cout << \"LIST NOT FOUND\"; return 0;}", "e": 3677, "s": 1145, "text": null }, { "code": "// Java program to find a list in second listimport java.util.*;class GFG{ // A Linked List nodestatic class Node{ int data; Node next;}; // Returns true if first list is// present in second liststatic boolean findList(Node first, Node second){ Node ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false;} /* Function to print nodes in a given linked list */static void printList(Node node){ while (node != null) { System.out.printf(\"%d \", node.data); node = node.next; }} // Function to add new node to linked listsstatic Node newNode(int key){ Node temp = new Node(); temp.data= key; temp.next = null; return temp;} // Driver Codepublic static void main(String[] args){ /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); Node b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if(findList(a, b) == true) System.out.println(\"LIST FOUND\"); else System.out.println(\"LIST NOT FOUND\");}} // This code is contributed by Princi Singh", "e": 6310, "s": 3677, "text": null }, { "code": "# Python3 program to find a list in second listclass Node: def __init__(self, value = 0): self.value = value self.next = None # Returns true if first list is# present in second listdef findList(first, second): # If both linked lists are empty/None, # return True if not first and not second: return True # If ONLY one of them is empty, # return False if not first or not second: return False ptr1 = first ptr2 = second # Traverse the second LL by # picking nodes one by one while ptr2: # Initialize 'ptr2' with current # node of 'second' ptr2 = second # Start matching first LL # with second LL while ptr1: # If second LL become empty and # first not, return False, # since first LL has not been # traversed completely if not ptr2: return False # If value of both nodes from both # LLs are equal, increment pointers # for both LLs so that next value # can be matched else if ptr1.value == ptr2.value: ptr1 = ptr1.next ptr2 = ptr2.next # If a single mismatch is found # OR ptr1 is None/empty,break out # of the while loop and do some checks else: break # check 1 : # If 'ptr1' is None/empty,that means # the 'first LL' has been completely # traversed and matched so return True if not ptr1: return True # If check 1 fails, that means, some # items for 'first' LL are still yet # to be matched, so start again by # bringing back the 'ptr1' to point # to 1st node of 'first' LL ptr1 = first # And increment second node element to next second = second.next return False # Driver Code # Let us create two linked lists to# test the above functions.# Created lists would be be# node_a: 1->2->3->4# node_b: 1->2->1->2->3->4node_a = Node(1)node_a.next = Node(2)node_a.next.next = Node(3)node_a.next.next.next = Node(4) node_b = Node(1)node_b.next = Node(2)node_b.next.next = Node(1)node_b.next.next.next = Node(2)node_b.next.next.next.next = Node(3)node_b.next.next.next.next.next = Node(4) if findList(node_a, node_b): print(\"LIST FOUND\")else: print(\"LIST NOT FOUND\") # This code is contributed by GauriShankarBadola", "e": 8792, "s": 6310, "text": null }, { "code": "// C# program to find a list in second listusing System; class GFG{ // A Linked List nodeclass Node{ public int data; public Node next;}; // Returns true if first list is// present in second liststatic Boolean findList(Node first, Node second){ Node ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false;} /* Function to print nodesin a given linked list */static void printList(Node node){ while (node != null) { Console.Write(\"{0} \", node.data); node = node.next; }} // Function to add new node to linked listsstatic Node newNode(int key){ Node temp = new Node(); temp.data= key; temp.next = null; return temp;} // Driver Codepublic static void Main(String[] args){ /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4*/ Node a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); Node b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if(findList(a, b) == true) Console.Write(\"LIST FOUND\"); else Console.Write(\"LIST NOT FOUND\");}} // This code is contributed by Rajput-Ji", "e": 11408, "s": 8792, "text": null }, { "code": "<script> // JavaScript program to find a// list in second list // A Linked List node class Node { constructor() { this.data = 0; this.next = null; }} // Returns true if first list is // present in second list function findList(first, second) { var ptr1 = first, ptr2 = second; // If both linked lists are empty, // return true if (first == null && second == null) return true; // Else If one is empty and // other is not, return false if (first == null || (first != null && second == null)) return false; // Traverse the second list by // picking nodes one by one while (second != null) { // Initialize ptr2 with // current node of second ptr2 = second; // Start matching first list // with second list while (ptr1 != null) { // If second list becomes empty and // first not then return false if (ptr2 == null) return false; // If data part is same, go to next // of both lists else if (ptr1.data == ptr2.data) { ptr1 = ptr1.next; ptr2 = ptr2.next; } // If not equal then break the loop else break; } // Return true if first list gets traversed // completely that means it is matched. if (ptr1 == null) return true; // Initialize ptr1 with first again ptr1 = first; // And go to next node of second list second = second.next; } return false; } /* Function to print nodes in a given linked list */ function printList(node) { while (node != null) { document.write(\"%d \", node.data); node = node.next; } } // Function to add new node to linked lists function newNode(key) { var temp = new Node(); temp.data = key; temp.next = null; return temp; } // Driver Code /* Let us create two linked lists to test the above functions. Created lists shall be a: 1->2->3->4 b: 1->2->1->2->3->4 */ var a = newNode(1); a.next = newNode(2); a.next.next = newNode(3); a.next.next.next = newNode(4); var b = newNode(1); b.next = newNode(2); b.next.next = newNode(1); b.next.next.next = newNode(2); b.next.next.next.next = newNode(3); b.next.next.next.next.next = newNode(4); if (findList(a, b) == true) document.write(\"LIST FOUND\"); else document.write(\"LIST NOT FOUND\"); // This code contributed by gauravrajput1 </script>", "e": 14292, "s": 11408, "text": null }, { "code": null, "e": 14303, "s": 14292, "text": "LIST FOUND" }, { "code": null, "e": 14389, "s": 14303, "text": "Time Complexity: O(m*n) where m is the number of nodes in second list and n in first." }, { "code": null, "e": 14405, "s": 14389, "text": "Optimization : " }, { "code": null, "e": 14605, "s": 14405, "text": "Above code can be optimized by using extra space i.e. stores the list into two strings and apply KMP algorithm. Refer https://ide.geeksforgeeks.org/3fXUaV for implementation provided by Nishant Singh" }, { "code": null, "e": 14910, "s": 14605, "text": "This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 14923, "s": 14910, "text": "princi singh" }, { "code": null, "e": 14933, "s": 14923, "text": "Rajput-Ji" }, { "code": null, "e": 14952, "s": 14933, "text": "GauriShankarBadola" }, { "code": null, "e": 14966, "s": 14952, "text": "GauravRajput1" }, { "code": null, "e": 14979, "s": 14966, "text": "simmytarika5" }, { "code": null, "e": 14996, "s": 14979, "text": "hardikkoriintern" }, { "code": null, "e": 15008, "s": 14996, "text": "Linked List" }, { "code": null, "e": 15018, "s": 15008, "text": "Searching" }, { "code": null, "e": 15030, "s": 15018, "text": "Linked List" }, { "code": null, "e": 15040, "s": 15030, "text": "Searching" }, { "code": null, "e": 15138, "s": 15040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15173, "s": 15138, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 15212, "s": 15173, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 15234, "s": 15212, "text": "Reverse a linked list" }, { "code": null, "e": 15282, "s": 15234, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 15301, "s": 15282, "text": "LinkedList in Java" }, { "code": null, "e": 15369, "s": 15301, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 15425, "s": 15369, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 15473, "s": 15425, "text": "Search an element in a sorted and rotated array" }, { "code": null, "e": 15520, "s": 15473, "text": "Search, insert and delete in an unsorted array" } ]
Equivalent Serial Schedule of Conflict Serializable Schedule in DBMS
30 Sep, 2021 Prerequisite: Conflict Serializability, Precedence Graph Conflict Serializable Schedule: A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. The serial schedule of the Conflict Serializable Schedule can be found by applying topological Sorting on the Precedence Graph of the Conflict Serializable Schedule. Note: Precedence Graph of Conflict Serial Schedule is always directed acyclic graph. Approach: Follow to below steps to find topological sorting of Precedence Graph: Find the indegree of all nodes for the given Precedence Graph and store it in an auxiliary array. Now For each node having indegree 0 perform the following:Print the current node T as the order of the topological sort.Let the node T be the node with in-degree 0.Remove T and all edges connecting to T from the graph.Update indegree of all nodes after the above steps. Print the current node T as the order of the topological sort. Let the node T be the node with in-degree 0. Remove T and all edges connecting to T from the graph. Update indegree of all nodes after the above steps. After the above steps, the topological sort of the given precedence graph can be calculated. Below is the illustration of the above approach: Let, the Conflict Serial Schedule be S: R2(A) W2(A) R3(C) W2(B) W3(A) W3(C) R1(A) R2(B) W1(A) W2(B) Here node T2 has indegree 0. So, select T2 and remove T2 and all edges connecting from it. Now T3 has indegree 0. So, select T3 and remove the edge T3→T1. At the end select T3. So the topological Sorting is T2, T3, T1. Hence, the equivalent serial schedule of given conflict serializable schedule is T2→T3→T1, i.e., S2: R2(A) W2(A) W2(B) R3(C) W3(A) W3(C) R1(A) R2(B) W1(A) W1(B). There may be more than one equivalent serial schedule of the conflict serializable schedule. Below is the implementation to get the Serial Schedule of CSS using Topological Sorting: C++ // C++ program to print serial schedule// of CSS using Topological sorting#include <bits/stdc++.h>using namespace std; class PrecedenceGraph { // No. of vertices int V; // Pointer to an array containing // adjacency vector vector<int>* adj; // Vector to store SerialSchedule vector<int> serialSchedule; // Function declarations void computeIndegree(int* indegree); int findZeroIndegree(int* indegree, bool* visited); public: // Constructor PrecedenceGraph(int V); // Function declarations void addEdge(int v, int w); void topologicalSort(); void printSchedule();}; // Function to create the precedence// graphPrecedenceGraph::PrecedenceGraph(int V){ this->V = V; adj = new vector<int>[V];} // Function to add the edge to the// precedence graphvoid PrecedenceGraph::addEdge(int v, int w){ adj[v].push_back(w);} // Function to compute indegree of nodesvoid PrecedenceGraph::computeIndegree( int* indegree){ for (int i = 1; i < V; i++) { // Traverse the adjacency list // of node i for (int j = 0; j < adj[i].size(); j++) { int node = adj[i][j]; // Update the indegree // of node indegree[node]++; } }} // Function to find node with// zero indegreeint PrecedenceGraph::findZeroIndegree( int* indegree, bool* visited){ for (int i = 1; i < V; i++) { // If node is not visited // and have indegree 0 if (!visited[i] && indegree[i] == 0) { // Mark node visited visited[i] = true; // Return node return i; } } // All nodes are visited return -1;} // Function to find the topological// Sorting of the given graphvoid PrecedenceGraph::topologicalSort(){ // Create and initialize // visited array bool* visited = new bool[V](); // Create and initialize // indegree array int* indegree = new int[V](); computeIndegree(indegree); // Check if the node with // indegree 0 is available int node = findZeroIndegree( indegree, visited); bool nodeAvailable = false; if (node != -1) { nodeAvailable = true; } while (nodeAvailable) { // Add node to serial schedule serialSchedule.push_back(node); for (int i = 0; i < adj[node].size(); i++) { // Delete all edges of current // node and update indegree indegree[adj[node][i]]--; } // Find next node with indegree 0 node = findZeroIndegree(indegree, visited); if (node == -1) { // Node with zero indegree // not available nodeAvailable = false; } }} // Function to print the serial schedulevoid PrecedenceGraph::printSchedule(){ for (int i : serialSchedule) { cout << "T" << i << " "; }} // Driver Codeint main(){ // Create a precedence graph // given in the above diagram PrecedenceGraph graph(4); graph.addEdge(2, 1); graph.addEdge(2, 3); graph.addEdge(3, 1); // Find topological ordereing graph.topologicalSort(); // Print Schedule cout << "Equivalent Serial" << " Schedule is :"; graph.printSchedule();} Equivalent Serial Schedule is :T2 T3 T1 Time Complexity: O(N)Auxiliary Space: O(N) adnanirshad158 DBMS-Transactions and Concurrency Control Topological Sorting DBMS Graph Graph DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Difference between OLAP and OLTP in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? SQL | DDL, DML, TCL and DCL Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Find if there is a path between two vertices in a directed graph Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Sep, 2021" }, { "code": null, "e": 109, "s": 52, "text": "Prerequisite: Conflict Serializability, Precedence Graph" }, { "code": null, "e": 438, "s": 109, "text": "Conflict Serializable Schedule: A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. The serial schedule of the Conflict Serializable Schedule can be found by applying topological Sorting on the Precedence Graph of the Conflict Serializable Schedule." }, { "code": null, "e": 523, "s": 438, "text": "Note: Precedence Graph of Conflict Serial Schedule is always directed acyclic graph." }, { "code": null, "e": 604, "s": 523, "text": "Approach: Follow to below steps to find topological sorting of Precedence Graph:" }, { "code": null, "e": 702, "s": 604, "text": "Find the indegree of all nodes for the given Precedence Graph and store it in an auxiliary array." }, { "code": null, "e": 972, "s": 702, "text": "Now For each node having indegree 0 perform the following:Print the current node T as the order of the topological sort.Let the node T be the node with in-degree 0.Remove T and all edges connecting to T from the graph.Update indegree of all nodes after the above steps." }, { "code": null, "e": 1035, "s": 972, "text": "Print the current node T as the order of the topological sort." }, { "code": null, "e": 1080, "s": 1035, "text": "Let the node T be the node with in-degree 0." }, { "code": null, "e": 1135, "s": 1080, "text": "Remove T and all edges connecting to T from the graph." }, { "code": null, "e": 1187, "s": 1135, "text": "Update indegree of all nodes after the above steps." }, { "code": null, "e": 1280, "s": 1187, "text": "After the above steps, the topological sort of the given precedence graph can be calculated." }, { "code": null, "e": 1329, "s": 1280, "text": "Below is the illustration of the above approach:" }, { "code": null, "e": 1429, "s": 1329, "text": "Let, the Conflict Serial Schedule be S: R2(A) W2(A) R3(C) W2(B) W3(A) W3(C) R1(A) R2(B) W1(A) W2(B)" }, { "code": null, "e": 1458, "s": 1429, "text": "Here node T2 has indegree 0." }, { "code": null, "e": 1520, "s": 1458, "text": "So, select T2 and remove T2 and all edges connecting from it." }, { "code": null, "e": 1584, "s": 1520, "text": "Now T3 has indegree 0. So, select T3 and remove the edge T3→T1." }, { "code": null, "e": 1648, "s": 1584, "text": "At the end select T3. So the topological Sorting is T2, T3, T1." }, { "code": null, "e": 1810, "s": 1648, "text": "Hence, the equivalent serial schedule of given conflict serializable schedule is T2→T3→T1, i.e., S2: R2(A) W2(A) W2(B) R3(C) W3(A) W3(C) R1(A) R2(B) W1(A) W1(B)." }, { "code": null, "e": 1903, "s": 1810, "text": "There may be more than one equivalent serial schedule of the conflict serializable schedule." }, { "code": null, "e": 1992, "s": 1903, "text": "Below is the implementation to get the Serial Schedule of CSS using Topological Sorting:" }, { "code": null, "e": 1996, "s": 1992, "text": "C++" }, { "code": "// C++ program to print serial schedule// of CSS using Topological sorting#include <bits/stdc++.h>using namespace std; class PrecedenceGraph { // No. of vertices int V; // Pointer to an array containing // adjacency vector vector<int>* adj; // Vector to store SerialSchedule vector<int> serialSchedule; // Function declarations void computeIndegree(int* indegree); int findZeroIndegree(int* indegree, bool* visited); public: // Constructor PrecedenceGraph(int V); // Function declarations void addEdge(int v, int w); void topologicalSort(); void printSchedule();}; // Function to create the precedence// graphPrecedenceGraph::PrecedenceGraph(int V){ this->V = V; adj = new vector<int>[V];} // Function to add the edge to the// precedence graphvoid PrecedenceGraph::addEdge(int v, int w){ adj[v].push_back(w);} // Function to compute indegree of nodesvoid PrecedenceGraph::computeIndegree( int* indegree){ for (int i = 1; i < V; i++) { // Traverse the adjacency list // of node i for (int j = 0; j < adj[i].size(); j++) { int node = adj[i][j]; // Update the indegree // of node indegree[node]++; } }} // Function to find node with// zero indegreeint PrecedenceGraph::findZeroIndegree( int* indegree, bool* visited){ for (int i = 1; i < V; i++) { // If node is not visited // and have indegree 0 if (!visited[i] && indegree[i] == 0) { // Mark node visited visited[i] = true; // Return node return i; } } // All nodes are visited return -1;} // Function to find the topological// Sorting of the given graphvoid PrecedenceGraph::topologicalSort(){ // Create and initialize // visited array bool* visited = new bool[V](); // Create and initialize // indegree array int* indegree = new int[V](); computeIndegree(indegree); // Check if the node with // indegree 0 is available int node = findZeroIndegree( indegree, visited); bool nodeAvailable = false; if (node != -1) { nodeAvailable = true; } while (nodeAvailable) { // Add node to serial schedule serialSchedule.push_back(node); for (int i = 0; i < adj[node].size(); i++) { // Delete all edges of current // node and update indegree indegree[adj[node][i]]--; } // Find next node with indegree 0 node = findZeroIndegree(indegree, visited); if (node == -1) { // Node with zero indegree // not available nodeAvailable = false; } }} // Function to print the serial schedulevoid PrecedenceGraph::printSchedule(){ for (int i : serialSchedule) { cout << \"T\" << i << \" \"; }} // Driver Codeint main(){ // Create a precedence graph // given in the above diagram PrecedenceGraph graph(4); graph.addEdge(2, 1); graph.addEdge(2, 3); graph.addEdge(3, 1); // Find topological ordereing graph.topologicalSort(); // Print Schedule cout << \"Equivalent Serial\" << \" Schedule is :\"; graph.printSchedule();}", "e": 5334, "s": 1996, "text": null }, { "code": null, "e": 5374, "s": 5334, "text": "Equivalent Serial Schedule is :T2 T3 T1" }, { "code": null, "e": 5419, "s": 5376, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 5434, "s": 5419, "text": "adnanirshad158" }, { "code": null, "e": 5476, "s": 5434, "text": "DBMS-Transactions and Concurrency Control" }, { "code": null, "e": 5496, "s": 5476, "text": "Topological Sorting" }, { "code": null, "e": 5501, "s": 5496, "text": "DBMS" }, { "code": null, "e": 5507, "s": 5501, "text": "Graph" }, { "code": null, "e": 5513, "s": 5507, "text": "Graph" }, { "code": null, "e": 5518, "s": 5513, "text": "DBMS" }, { "code": null, "e": 5616, "s": 5518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5657, "s": 5616, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 5698, "s": 5657, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 5735, "s": 5698, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 5767, "s": 5735, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 5795, "s": 5767, "text": "SQL | DDL, DML, TCL and DCL" }, { "code": null, "e": 5835, "s": 5795, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 5873, "s": 5835, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 5924, "s": 5873, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 5989, "s": 5924, "text": "Find if there is a path between two vertices in a directed graph" } ]
What does main() return in C and C++?
19 Sep, 2019 C According to coding standards, a good return program must exit the main function with 0. Although we are using void main() in C, In which we have not suppose to write any kind of return statement but that doesn’t mean that C code doesn’t require 0 as exit code. Let’s see one example to clear our thinking about need of return 0 statement in our code. Example #1 : #include <stdio.h> void main(){ // This code will run properly // but in the end, // it will demand an exit code. printf("It works fine");} It works fine Runtime Error: NZEC As we can see in the output the compiler throws a runtime error NZEC, Which means that Non Zero Exit Code. That means that our main program exited with non zero exiting code so if we want to be a developer than we make these small things in our mind. Correct Code for C : #include <stdio.h> int main(){ // This code will run properly // but in the end, // it will demand an exit code. printf("This is correct output"); return 0;} This is correct output Note: Returning value other than zero will throw the same runtime error. So make sure our code return only 0. Example #2 : #include <stdio.h> int main(){ printf("GeeksforGeeks"); return "gfg";} It works fine Runtime Error: NZEC Correct Code for C : #include <stdio.h> int main(){ printf("GeeksforGeeks"); return 0;} GeeksforGeeks C++ In case of C++, We are not able to use void keyword with our main() function according to coding namespace standards that’s why we only intend to use int keyword only with main function in C++. Let’s see some examples to justify these statements. Example #3 : #include <iostream>using namespace std; void main(){ cout << "GeeksforGeeks";} prog.cpp:4:11: error: '::main' must return 'int' void main() ^ Correct Code for C++ : #include <iostream>using namespace std; int main(){ cout << "GeeksforGeeks"; return 0;} GeeksforGeeks Example #4 : #include <iostream>using namespace std; char main(){ cout << "GeeksforGeeks"; return "gfg";} prog.cpp:4:11: error: '::main' must return 'int' char main() ^ prog.cpp: In function 'int main()': prog.cpp:7:9: error: invalid conversion from 'const char*' to 'int' [-fpermissive] return "gfg"; ^ Correct Code for C++ : #include <iostream>using namespace std; int main(){ cout << "GeeksforGeeks"; return 0;} GeeksforGeeks cooldude69 main Picked return C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n19 Sep, 2019" }, { "code": null, "e": 55, "s": 53, "text": "C" }, { "code": null, "e": 407, "s": 55, "text": "According to coding standards, a good return program must exit the main function with 0. Although we are using void main() in C, In which we have not suppose to write any kind of return statement but that doesn’t mean that C code doesn’t require 0 as exit code. Let’s see one example to clear our thinking about need of return 0 statement in our code." }, { "code": null, "e": 420, "s": 407, "text": "Example #1 :" }, { "code": "#include <stdio.h> void main(){ // This code will run properly // but in the end, // it will demand an exit code. printf(\"It works fine\");}", "e": 575, "s": 420, "text": null }, { "code": null, "e": 589, "s": 575, "text": "It works fine" }, { "code": null, "e": 604, "s": 589, "text": "Runtime Error:" }, { "code": null, "e": 609, "s": 604, "text": "NZEC" }, { "code": null, "e": 860, "s": 609, "text": "As we can see in the output the compiler throws a runtime error NZEC, Which means that Non Zero Exit Code. That means that our main program exited with non zero exiting code so if we want to be a developer than we make these small things in our mind." }, { "code": null, "e": 881, "s": 860, "text": "Correct Code for C :" }, { "code": "#include <stdio.h> int main(){ // This code will run properly // but in the end, // it will demand an exit code. printf(\"This is correct output\"); return 0;}", "e": 1057, "s": 881, "text": null }, { "code": null, "e": 1080, "s": 1057, "text": "This is correct output" }, { "code": null, "e": 1190, "s": 1080, "text": "Note: Returning value other than zero will throw the same runtime error. So make sure our code return only 0." }, { "code": null, "e": 1203, "s": 1190, "text": "Example #2 :" }, { "code": "#include <stdio.h> int main(){ printf(\"GeeksforGeeks\"); return \"gfg\";}", "e": 1283, "s": 1203, "text": null }, { "code": null, "e": 1297, "s": 1283, "text": "It works fine" }, { "code": null, "e": 1312, "s": 1297, "text": "Runtime Error:" }, { "code": null, "e": 1317, "s": 1312, "text": "NZEC" }, { "code": null, "e": 1338, "s": 1317, "text": "Correct Code for C :" }, { "code": "#include <stdio.h> int main(){ printf(\"GeeksforGeeks\"); return 0;}", "e": 1414, "s": 1338, "text": null }, { "code": null, "e": 1428, "s": 1414, "text": "GeeksforGeeks" }, { "code": null, "e": 1432, "s": 1428, "text": "C++" }, { "code": null, "e": 1679, "s": 1432, "text": "In case of C++, We are not able to use void keyword with our main() function according to coding namespace standards that’s why we only intend to use int keyword only with main function in C++. Let’s see some examples to justify these statements." }, { "code": null, "e": 1692, "s": 1679, "text": "Example #3 :" }, { "code": "#include <iostream>using namespace std; void main(){ cout << \"GeeksforGeeks\";}", "e": 1775, "s": 1692, "text": null }, { "code": null, "e": 1851, "s": 1775, "text": "prog.cpp:4:11: error: '::main' must return 'int'\n void main()\n ^\n" }, { "code": null, "e": 1874, "s": 1851, "text": "Correct Code for C++ :" }, { "code": "#include <iostream>using namespace std; int main(){ cout << \"GeeksforGeeks\"; return 0;}", "e": 1969, "s": 1874, "text": null }, { "code": null, "e": 1983, "s": 1969, "text": "GeeksforGeeks" }, { "code": null, "e": 1996, "s": 1983, "text": "Example #4 :" }, { "code": "#include <iostream>using namespace std; char main(){ cout << \"GeeksforGeeks\"; return \"gfg\";}", "e": 2096, "s": 1996, "text": null }, { "code": null, "e": 2318, "s": 2096, "text": "prog.cpp:4:11: error: '::main' must return 'int'\n char main()\n ^\nprog.cpp: In function 'int main()':\nprog.cpp:7:9: error: invalid conversion from 'const char*' to 'int' [-fpermissive]\n return \"gfg\";\n ^\n" }, { "code": null, "e": 2341, "s": 2318, "text": "Correct Code for C++ :" }, { "code": "#include <iostream>using namespace std; int main(){ cout << \"GeeksforGeeks\"; return 0;}", "e": 2436, "s": 2341, "text": null }, { "code": null, "e": 2450, "s": 2436, "text": "GeeksforGeeks" }, { "code": null, "e": 2461, "s": 2450, "text": "cooldude69" }, { "code": null, "e": 2466, "s": 2461, "text": "main" }, { "code": null, "e": 2473, "s": 2466, "text": "Picked" }, { "code": null, "e": 2480, "s": 2473, "text": "return" }, { "code": null, "e": 2491, "s": 2480, "text": "C Language" }, { "code": null, "e": 2495, "s": 2491, "text": "C++" }, { "code": null, "e": 2499, "s": 2495, "text": "CPP" } ]
Find missing elements from an Array
19 Jun, 2022 Given a list of integers from the range [1, N] with some of the elements missing. The task is to find the missing elements. Note that there can be duplicates in the list.Examples: Input: arr[] = {1, 3, 3, 3, 5} Output: 2 4 Input: arr[] = {1, 2, 3, 4, 4, 7, 7} Output: 5 6 Approach1: In the given range [1, N] there should be an element corresponding to each index. If an element is missing then its index will never be visited. Traverse the array: For each element: if array[element] > 0: Mark the element as visited Again, traverse the array: if element isNot Visited: add it as missing element Below is the implementation of the above approach: C++ C Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvector<int> missing_elements(vector<int> vec){ // Vector to store the list // of missing elements vector<int> mis; // For every given element for (int i = 0; i < vec.size(); i++) { // Find its index int temp = abs(vec[i]) - 1; // Update the element at the found index vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp]; } for (int i = 0; i < vec.size(); i++) // Current element was not present // in the original vector if (vec[i] > 0) mis.push_back(i + 1); return mis;} // Driver codeint main(){ vector<int> vec = { 3, 3, 3, 5, 1 }; // Vector to store the returned // list of missing elements vector<int> miss_ele = missing_elements(vec); // Print the list of elements for (int i = 0; i < miss_ele.size(); i++) cout << miss_ele[i] << " "; return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // C implementation of the approach#include <stdio.h>#include <stdlib.h> // Function to find the missing elementsvoid missing_elements(int vec[], int n){ int mis[n]; for (int i = 0; i < n; i++) mis[i] = -1; // For every given element for (int i = 0; i < n; i++) { // Find its index int temp = abs(vec[i]) - 1; // Update the element at the found index vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp]; } // Current element was not present in the original // vector for (int i = 0; i < n; i++) if (vec[i] > 0) mis[i] = (i + 1); int miss_ele_size = sizeof(mis) / sizeof(mis[0]); for (int i = 0; i < miss_ele_size; i++) { if (mis[i] != -1) printf("%d ", mis[i]); }} // Driver codeint main(){ int vec[] = { 3, 3, 3, 5, 1 }; int vec_size = sizeof(vec) / sizeof(vec[0]); missing_elements(vec, vec_size); return 0;} // This code is contributed by Aditya Kumar (adityakumar129) // Java implementation of the above approachimport java.util.*; class GFG { // Function to find the missing elements static Vector missing_elements(Vector vec) { // Vector to store the list // of missing elements Vector mis = new Vector(); // For every given element for (int i = 0; i < vec.size(); i++) { // Find its index int temp = Math.abs((int)vec.get(i)) - 1; // Update the element at the found index if ((int)vec.get(temp) > 0) vec.set(temp, -(int)vec.get(temp)); else vec.set(temp, vec.get(temp)); } for (int i = 0; i < vec.size(); i++) { // Current element was not present // in the original vector if ((int)vec.get(i) > 0) mis.add(i + 1); } return mis; } // Driver code public static void main(String args[]) { Vector vec = new Vector(); vec.add(3); vec.add(3); vec.add(3); vec.add(5); vec.add(1); // Vector to store the returned // list of missing elements Vector miss_ele = missing_elements(vec); // Print the list of elements for (int i = 0; i < miss_ele.size(); i++) System.out.print(miss_ele.get(i) + " "); }} // This code is contributed by Aditya Kumar (adityakumar129) # Python3 implementation of the approach # Function to find the missing elementsdef missing_elements(vec): # Vector to store the list # of missing elements mis = [] # For every given element for i in range(len(vec)): # Find its index temp = abs(vec[i]) - 1 # Update the element at the found index if vec[temp] > 0: vec[temp] = -vec[temp] for i in range(len(vec)): # Current element was not present # in the original vector if (vec[i] > 0): mis.append(i + 1) return mis # Driver codevec = [3, 3, 3, 5, 1] # Vector to store the returned# list of missing elementsmiss_ele = missing_elements(vec) # Print the list of elementsfor i in range(len(miss_ele)): print(miss_ele[i], end = " ") # This code is contributed by Mohit Kumar // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to find the missing elements static List<int> missing_elements(List<int> vec) { // List<int> to store the list // of missing elements List<int> mis = new List<int>(); // For every given element for (int i = 0; i < vec.Count; i++) { // Find its index int temp = Math.Abs((int)vec[i]) - 1; // Update the element at the found index if ((int)vec[temp] > 0) vec[temp] = -(int)vec[temp]; else vec[temp] = vec[temp]; } for (int i = 0; i < vec.Count; i++) { // Current element was not present // in the original vector if ((int)vec[i] > 0) mis.Add(i + 1); } return mis; } // Driver code public static void Main(String []args) { List<int> vec = new List<int>(); vec.Add(3); vec.Add(3); vec.Add(3); vec.Add(5); vec.Add(1); // List to store the returned // list of missing elements List<int> miss_ele = missing_elements(vec); // Print the list of elements for (int i = 0; i < miss_ele.Count; i++) Console.Write(miss_ele[i] + " "); }} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach // Function to find the missing elements function missing_elements(vec) { // Vector to store the list // of missing elements let mis = []; // For every given element for (let i = 0; i < vec.length; i++) { // Find its index let temp = Math.abs(vec[i]) - 1; // Update the element at the found index vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp]; } for (let i = 0; i < vec.length; i++) // Current element was not present // in the original vector if (vec[i] > 0) mis.push(i + 1); return mis; } let vec = [ 3, 3, 3, 5, 1 ]; // Vector to store the returned // list of missing elements let miss_ele = missing_elements(vec); // Print the list of elements for (let i = 0; i < miss_ele.length; i++) document.write(miss_ele[i] + " "); </script> 2 4 Time Complexity: O(N), where N is the length of the vector vec. Auxiliary Space: O(N) More Efficient Approach: Approach2: In the given range [1, N] there should be an element corresponding to each index. So if it’s in sorted fashion in O(N) time, then those elements that are not there can be easily found. Algorithm: Keep an i pointer from 0 to N-1If the element is in the correct position then don’t swap, increment iElse make a swap with the correct position.Correct Position means Element should be in Element -1 index in our caseIt can handle duplicates too.Then make a for loop,IF we find Arr[i] = i+1, then i+1 is present.Else i+1 is missing. Keep an i pointer from 0 to N-1 If the element is in the correct position then don’t swap, increment i Else make a swap with the correct position. Correct Position means Element should be in Element -1 index in our case It can handle duplicates too. Then make a for loop, IF we find Arr[i] = i+1, then i+1 is present. Else i+1 is missing. The CRUX is: If an element is missing, someone in the 1 to N range duplicate is occupying that place. Example Run Through (Manual): Example on own by R.Balakrishnan from lucidchart tool Below is the CODE implementation of the above approach with all test cases: C++ // C++ program to Find missing elements from an Array#include <algorithm>#include <iostream>#include <vector>using namespace std; // Complexities// O(N+N) = O(N) time and O(1) Spacevoid FindMissing(vector<int> arr){ int i = 0; int N = arr.size(); while (i < N) { int correct = arr[i] - 1; // as 0 based indxing if (arr[i] != arr[correct]) { swap(arr[i], arr[correct]); } else { i++; } } for (i = 0; i < N; i++) { if (arr[i] != i + 1) { cout << i + 1 << " "; } } cout << "\n";} int main(){ // Diff Test cases vector<int> nums = { 3, 3, 3, 5, 1 }; FindMissing(nums); vector<int> nums2 = { 1, 3, 3, 3, 5 }; FindMissing(nums2); vector<int> nums3 = { 1, 2, 3, 4, 4, 7, 7 }; FindMissing(nums3);} // Code done by R.Balakrishnan (rbkraj000) 2 4 2 4 5 6 Time Complexity: O(N), where N is the length of the input vector. Even in the worst case, there will be N-1 Swaps + N-1 Comparisons done. So asymptotically it’s O(N). Auxiliary Space: O(1) mohit kumar 29 ankthon 29AjayKumar subhammahato348 divyesh072019 adityakumar129 rbkraj000 Constructive Algorithms Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jun, 2022" }, { "code": null, "e": 235, "s": 54, "text": "Given a list of integers from the range [1, N] with some of the elements missing. The task is to find the missing elements. Note that there can be duplicates in the list.Examples: " }, { "code": null, "e": 329, "s": 235, "text": "Input: arr[] = {1, 3, 3, 3, 5}\nOutput: 2 4\n\nInput: arr[] = {1, 2, 3, 4, 4, 7, 7} \nOutput: 5 6" }, { "code": null, "e": 487, "s": 329, "text": "Approach1: In the given range [1, N] there should be an element corresponding to each index. If an element is missing then its index will never be visited. " }, { "code": null, "e": 685, "s": 487, "text": "Traverse the array:\nFor each element:\n if array[element] > 0:\n Mark the element as visited\nAgain, traverse the array:\n if element isNot Visited:\n add it as missing element" }, { "code": null, "e": 738, "s": 685, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 742, "s": 738, "text": "C++" }, { "code": null, "e": 744, "s": 742, "text": "C" }, { "code": null, "e": 749, "s": 744, "text": "Java" }, { "code": null, "e": 757, "s": 749, "text": "Python3" }, { "code": null, "e": 760, "s": 757, "text": "C#" }, { "code": null, "e": 771, "s": 760, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the missing elementsvector<int> missing_elements(vector<int> vec){ // Vector to store the list // of missing elements vector<int> mis; // For every given element for (int i = 0; i < vec.size(); i++) { // Find its index int temp = abs(vec[i]) - 1; // Update the element at the found index vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp]; } for (int i = 0; i < vec.size(); i++) // Current element was not present // in the original vector if (vec[i] > 0) mis.push_back(i + 1); return mis;} // Driver codeint main(){ vector<int> vec = { 3, 3, 3, 5, 1 }; // Vector to store the returned // list of missing elements vector<int> miss_ele = missing_elements(vec); // Print the list of elements for (int i = 0; i < miss_ele.size(); i++) cout << miss_ele[i] << \" \"; return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 1826, "s": 771, "text": null }, { "code": "// C implementation of the approach#include <stdio.h>#include <stdlib.h> // Function to find the missing elementsvoid missing_elements(int vec[], int n){ int mis[n]; for (int i = 0; i < n; i++) mis[i] = -1; // For every given element for (int i = 0; i < n; i++) { // Find its index int temp = abs(vec[i]) - 1; // Update the element at the found index vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp]; } // Current element was not present in the original // vector for (int i = 0; i < n; i++) if (vec[i] > 0) mis[i] = (i + 1); int miss_ele_size = sizeof(mis) / sizeof(mis[0]); for (int i = 0; i < miss_ele_size; i++) { if (mis[i] != -1) printf(\"%d \", mis[i]); }} // Driver codeint main(){ int vec[] = { 3, 3, 3, 5, 1 }; int vec_size = sizeof(vec) / sizeof(vec[0]); missing_elements(vec, vec_size); return 0;} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2815, "s": 1826, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*; class GFG { // Function to find the missing elements static Vector missing_elements(Vector vec) { // Vector to store the list // of missing elements Vector mis = new Vector(); // For every given element for (int i = 0; i < vec.size(); i++) { // Find its index int temp = Math.abs((int)vec.get(i)) - 1; // Update the element at the found index if ((int)vec.get(temp) > 0) vec.set(temp, -(int)vec.get(temp)); else vec.set(temp, vec.get(temp)); } for (int i = 0; i < vec.size(); i++) { // Current element was not present // in the original vector if ((int)vec.get(i) > 0) mis.add(i + 1); } return mis; } // Driver code public static void main(String args[]) { Vector vec = new Vector(); vec.add(3); vec.add(3); vec.add(3); vec.add(5); vec.add(1); // Vector to store the returned // list of missing elements Vector miss_ele = missing_elements(vec); // Print the list of elements for (int i = 0; i < miss_ele.size(); i++) System.out.print(miss_ele.get(i) + \" \"); }} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 4217, "s": 2815, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the missing elementsdef missing_elements(vec): # Vector to store the list # of missing elements mis = [] # For every given element for i in range(len(vec)): # Find its index temp = abs(vec[i]) - 1 # Update the element at the found index if vec[temp] > 0: vec[temp] = -vec[temp] for i in range(len(vec)): # Current element was not present # in the original vector if (vec[i] > 0): mis.append(i + 1) return mis # Driver codevec = [3, 3, 3, 5, 1] # Vector to store the returned# list of missing elementsmiss_ele = missing_elements(vec) # Print the list of elementsfor i in range(len(miss_ele)): print(miss_ele[i], end = \" \") # This code is contributed by Mohit Kumar", "e": 5043, "s": 4217, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to find the missing elements static List<int> missing_elements(List<int> vec) { // List<int> to store the list // of missing elements List<int> mis = new List<int>(); // For every given element for (int i = 0; i < vec.Count; i++) { // Find its index int temp = Math.Abs((int)vec[i]) - 1; // Update the element at the found index if ((int)vec[temp] > 0) vec[temp] = -(int)vec[temp]; else vec[temp] = vec[temp]; } for (int i = 0; i < vec.Count; i++) { // Current element was not present // in the original vector if ((int)vec[i] > 0) mis.Add(i + 1); } return mis; } // Driver code public static void Main(String []args) { List<int> vec = new List<int>(); vec.Add(3); vec.Add(3); vec.Add(3); vec.Add(5); vec.Add(1); // List to store the returned // list of missing elements List<int> miss_ele = missing_elements(vec); // Print the list of elements for (int i = 0; i < miss_ele.Count; i++) Console.Write(miss_ele[i] + \" \"); }} // This code is contributed by 29AjayKumar", "e": 6493, "s": 5043, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to find the missing elements function missing_elements(vec) { // Vector to store the list // of missing elements let mis = []; // For every given element for (let i = 0; i < vec.length; i++) { // Find its index let temp = Math.abs(vec[i]) - 1; // Update the element at the found index vec[temp] = vec[temp] > 0 ? -vec[temp] : vec[temp]; } for (let i = 0; i < vec.length; i++) // Current element was not present // in the original vector if (vec[i] > 0) mis.push(i + 1); return mis; } let vec = [ 3, 3, 3, 5, 1 ]; // Vector to store the returned // list of missing elements let miss_ele = missing_elements(vec); // Print the list of elements for (let i = 0; i < miss_ele.length; i++) document.write(miss_ele[i] + \" \"); </script>", "e": 7526, "s": 6493, "text": null }, { "code": null, "e": 7531, "s": 7526, "text": "2 4 " }, { "code": null, "e": 7595, "s": 7531, "text": "Time Complexity: O(N), where N is the length of the vector vec." }, { "code": null, "e": 7617, "s": 7595, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 7642, "s": 7617, "text": "More Efficient Approach:" }, { "code": null, "e": 7838, "s": 7642, "text": "Approach2: In the given range [1, N] there should be an element corresponding to each index. So if it’s in sorted fashion in O(N) time, then those elements that are not there can be easily found." }, { "code": null, "e": 7849, "s": 7838, "text": "Algorithm:" }, { "code": null, "e": 8181, "s": 7849, "text": "Keep an i pointer from 0 to N-1If the element is in the correct position then don’t swap, increment iElse make a swap with the correct position.Correct Position means Element should be in Element -1 index in our caseIt can handle duplicates too.Then make a for loop,IF we find Arr[i] = i+1, then i+1 is present.Else i+1 is missing." }, { "code": null, "e": 8213, "s": 8181, "text": "Keep an i pointer from 0 to N-1" }, { "code": null, "e": 8284, "s": 8213, "text": "If the element is in the correct position then don’t swap, increment i" }, { "code": null, "e": 8328, "s": 8284, "text": "Else make a swap with the correct position." }, { "code": null, "e": 8401, "s": 8328, "text": "Correct Position means Element should be in Element -1 index in our case" }, { "code": null, "e": 8431, "s": 8401, "text": "It can handle duplicates too." }, { "code": null, "e": 8453, "s": 8431, "text": "Then make a for loop," }, { "code": null, "e": 8499, "s": 8453, "text": "IF we find Arr[i] = i+1, then i+1 is present." }, { "code": null, "e": 8520, "s": 8499, "text": "Else i+1 is missing." }, { "code": null, "e": 8622, "s": 8520, "text": "The CRUX is: If an element is missing, someone in the 1 to N range duplicate is occupying that place." }, { "code": null, "e": 8652, "s": 8622, "text": "Example Run Through (Manual):" }, { "code": null, "e": 8707, "s": 8652, "text": "Example on own by R.Balakrishnan from lucidchart tool " }, { "code": null, "e": 8785, "s": 8707, "text": "Below is the CODE implementation of the above approach with all test cases: " }, { "code": null, "e": 8789, "s": 8785, "text": "C++" }, { "code": "// C++ program to Find missing elements from an Array#include <algorithm>#include <iostream>#include <vector>using namespace std; // Complexities// O(N+N) = O(N) time and O(1) Spacevoid FindMissing(vector<int> arr){ int i = 0; int N = arr.size(); while (i < N) { int correct = arr[i] - 1; // as 0 based indxing if (arr[i] != arr[correct]) { swap(arr[i], arr[correct]); } else { i++; } } for (i = 0; i < N; i++) { if (arr[i] != i + 1) { cout << i + 1 << \" \"; } } cout << \"\\n\";} int main(){ // Diff Test cases vector<int> nums = { 3, 3, 3, 5, 1 }; FindMissing(nums); vector<int> nums2 = { 1, 3, 3, 3, 5 }; FindMissing(nums2); vector<int> nums3 = { 1, 2, 3, 4, 4, 7, 7 }; FindMissing(nums3);} // Code done by R.Balakrishnan (rbkraj000)", "e": 9648, "s": 8789, "text": null }, { "code": null, "e": 9664, "s": 9648, "text": "2 4 \n2 4 \n5 6 \n" }, { "code": null, "e": 9730, "s": 9664, "text": "Time Complexity: O(N), where N is the length of the input vector." }, { "code": null, "e": 9831, "s": 9730, "text": "Even in the worst case, there will be N-1 Swaps + N-1 Comparisons done. So asymptotically it’s O(N)." }, { "code": null, "e": 9854, "s": 9831, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 9869, "s": 9854, "text": "mohit kumar 29" }, { "code": null, "e": 9877, "s": 9869, "text": "ankthon" }, { "code": null, "e": 9889, "s": 9877, "text": "29AjayKumar" }, { "code": null, "e": 9905, "s": 9889, "text": "subhammahato348" }, { "code": null, "e": 9919, "s": 9905, "text": "divyesh072019" }, { "code": null, "e": 9934, "s": 9919, "text": "adityakumar129" }, { "code": null, "e": 9944, "s": 9934, "text": "rbkraj000" }, { "code": null, "e": 9968, "s": 9944, "text": "Constructive Algorithms" }, { "code": null, "e": 9975, "s": 9968, "text": "Arrays" }, { "code": null, "e": 9980, "s": 9975, "text": "Hash" }, { "code": null, "e": 9987, "s": 9980, "text": "Arrays" }, { "code": null, "e": 9992, "s": 9987, "text": "Hash" } ]
Java Program for Left Rotation and Right Rotation of a String
27 May, 2022 Given a string of size n, write functions to perform the following operations on a string- Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n). Left (Or anticlockwise) rotate the given string by d elements (where d <= n) Right (Or clockwise) rotate the given string by d elements (where d <= n). Examples: Input : s = "GeeksforGeeks" d = 2 Output : Left Rotation : "eksforGeeksGe" Right Rotation : "ksGeeksforGee" Input : s = "qwertyu" d = 2 Output : Left rotation : "ertyuqw" Right rotation : "yuqwert" A Simple Solution is to use a temporary string to do rotations. For left rotation, first, copy last n-d characters, then copy first d characters in order to the temporary string. For right rotation, first, copy last d characters, then copy n-d characters. Can we do both rotations in-place and O(n) time? The idea is based on a reversal algorithm for rotation. // Left rotate string s by d (Assuming d <= n) leftRotate(s, d) reverse(s, 0, d-1); // Reverse substring s[0..d-1] reverse(s, d, n-1); // Reverse substring s[d..n-1] reverse(s, 0, n-1); // Reverse whole string. // Right rotate string s by d (Assuming d <= n) rightRotate(s, d) // We can also call above reverse steps // with d = n-d. leftRotate(s, n-d) Below is the implementation of the above steps : Java // Java program for Left Rotation and Right// Rotation of a Stringimport java.util.*;import java.io.*; class GFG{ // function that rotates s towards left by d static String leftrotate(String str, int d) { String ans = str.substring(d) + str.substring(0, d); return ans; } // function that rotates s towards right by d static String rightrotate(String str, int d) { return leftrotate(str, str.length() - d); } // Driver code public static void main(String args[]) { String str1 = "GeeksforGeeks"; System.out.println(leftrotate(str1, 2)); String str2 = "GeeksforGeeks"; System.out.println(rightrotate(str2, 2)); }} // This code is contributed by rachana soma Output: Left rotation: eksforGeeksGe Right rotation: ksGeeksforGee Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space. Please refer complete article on Left Rotation and Right Rotation of a String for more details! rohitsingh57 rohan07 rotation Java Java Programs Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n27 May, 2022" }, { "code": null, "e": 143, "s": 52, "text": "Given a string of size n, write functions to perform the following operations on a string-" }, { "code": null, "e": 294, "s": 143, "text": "Left (Or anticlockwise) rotate the given string by d elements (where d <= n)Right (Or clockwise) rotate the given string by d elements (where d <= n)." }, { "code": null, "e": 371, "s": 294, "text": "Left (Or anticlockwise) rotate the given string by d elements (where d <= n)" }, { "code": null, "e": 446, "s": 371, "text": "Right (Or clockwise) rotate the given string by d elements (where d <= n)." }, { "code": null, "e": 457, "s": 446, "text": "Examples: " }, { "code": null, "e": 696, "s": 457, "text": "Input : s = \"GeeksforGeeks\"\n d = 2\nOutput : Left Rotation : \"eksforGeeksGe\" \n Right Rotation : \"ksGeeksforGee\" \n\n\nInput : s = \"qwertyu\" \n d = 2\nOutput : Left rotation : \"ertyuqw\"\n Right rotation : \"yuqwert\"" }, { "code": null, "e": 953, "s": 696, "text": "A Simple Solution is to use a temporary string to do rotations. For left rotation, first, copy last n-d characters, then copy first d characters in order to the temporary string. For right rotation, first, copy last d characters, then copy n-d characters. " }, { "code": null, "e": 1058, "s": 953, "text": "Can we do both rotations in-place and O(n) time? The idea is based on a reversal algorithm for rotation." }, { "code": null, "e": 1429, "s": 1058, "text": "// Left rotate string s by d (Assuming d <= n)\nleftRotate(s, d)\n reverse(s, 0, d-1); // Reverse substring s[0..d-1]\n reverse(s, d, n-1); // Reverse substring s[d..n-1]\n reverse(s, 0, n-1); // Reverse whole string. \n\n// Right rotate string s by d (Assuming d <= n)\nrightRotate(s, d)\n\n // We can also call above reverse steps\n // with d = n-d.\n leftRotate(s, n-d) " }, { "code": null, "e": 1479, "s": 1429, "text": "Below is the implementation of the above steps : " }, { "code": null, "e": 1484, "s": 1479, "text": "Java" }, { "code": "// Java program for Left Rotation and Right// Rotation of a Stringimport java.util.*;import java.io.*; class GFG{ // function that rotates s towards left by d static String leftrotate(String str, int d) { String ans = str.substring(d) + str.substring(0, d); return ans; } // function that rotates s towards right by d static String rightrotate(String str, int d) { return leftrotate(str, str.length() - d); } // Driver code public static void main(String args[]) { String str1 = \"GeeksforGeeks\"; System.out.println(leftrotate(str1, 2)); String str2 = \"GeeksforGeeks\"; System.out.println(rightrotate(str2, 2)); }} // This code is contributed by rachana soma", "e": 2266, "s": 1484, "text": null }, { "code": null, "e": 2275, "s": 2266, "text": "Output: " }, { "code": null, "e": 2353, "s": 2275, "text": "Left rotation: eksforGeeksGe\nRight rotation: ksGeeksforGee " }, { "code": null, "e": 2508, "s": 2353, "text": "Time Complexity: O(N), as we are using a loop to traverse N times so it will cost us O(N) time.Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 2604, "s": 2508, "text": "Please refer complete article on Left Rotation and Right Rotation of a String for more details!" }, { "code": null, "e": 2617, "s": 2604, "text": "rohitsingh57" }, { "code": null, "e": 2625, "s": 2617, "text": "rohan07" }, { "code": null, "e": 2634, "s": 2625, "text": "rotation" }, { "code": null, "e": 2639, "s": 2634, "text": "Java" }, { "code": null, "e": 2653, "s": 2639, "text": "Java Programs" }, { "code": null, "e": 2661, "s": 2653, "text": "Strings" }, { "code": null, "e": 2669, "s": 2661, "text": "Strings" }, { "code": null, "e": 2674, "s": 2669, "text": "Java" } ]
std::iter_swap in C++
06 Sep, 2019 std::swap is used for swapping of elements between two containers. One of the other way of doing this same thing is facilitated by std::iter_swap, which as the name suggests is used for swapping the elements with the help of an iterator. It simply exchanges the values of the elements pointed to by the iterators. If we look at its internal working, we will find that this function itself uses std::swap(). Syntax: void iter_swap (ForwardIterator1 a, ForwardIterator2 b); Here, a and b are forward iterators. Returns: It has a void return type, so it does not return any value. // C++ program to demonstrate the use of std::iter_swap#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ // Declaring first vector vector<int> v1; int i; for (i = 0; i < 10; ++i) { v1.push_back(i); } // v1 contains 0 1 2 3 4 5 6 7 8 9 vector<int>::iterator i1, i2; i1 = v1.begin(); i2 = v1.end() - 1; // Performing swap between first and last element // of vector std::iter_swap(i1, i2); // Displaying v1 after swapping for (i = 0; i < 10; ++i) { cout << v1[i] << " "; } return 0;} Output: 9 1 2 3 4 5 6 7 8 0 Here, in this program we have swapped elements from v1 with the help of two iterators, one of them pointing at the beginning of v1 and the other one pointing at the end of v1. std::iter_swap vs std::swap After coming to know that iter_swap is used to swap the values, just like std::swap(), the question now arises is why should we learn iter_swap, if we have already something called swap(). Some of the reasons in support of iter_swap are: Optimization for node-based sequences: Most STL algorithms operate on iterator ranges. It therefore makes sense to use iter_swap when swapping elements within those ranges, swapping the elements pointed to by two iterators. This allows optimization for node-based sequences such as std::list, whereby the nodes are just relinked, rather than the data actually being swapped. Use in STL definition: Some STL algorithm like std::reverse involve the use of std::iter_swap in its definition. Therefore, one should have knowledge about this in order to understand these definition.// Definition of std::reverse()template void reverse(BidirectionalIterator first, BidirectionalIterator last){ while ((first != last) && (first != --last)) { std::iter_swap(first, last); ++first; }} // Definition of std::reverse()template void reverse(BidirectionalIterator first, BidirectionalIterator last){ while ((first != last) && (first != --last)) { std::iter_swap(first, last); ++first; }} Providing abstraction: iter_swap usefully encapsulates the part of the swappable interface which you would otherwise implement every time. This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet cpp-algorithm-library STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Sep, 2019" }, { "code": null, "e": 292, "s": 54, "text": "std::swap is used for swapping of elements between two containers. One of the other way of doing this same thing is facilitated by std::iter_swap, which as the name suggests is used for swapping the elements with the help of an iterator." }, { "code": null, "e": 461, "s": 292, "text": "It simply exchanges the values of the elements pointed to by the iterators. If we look at its internal working, we will find that this function itself uses std::swap()." }, { "code": null, "e": 469, "s": 461, "text": "Syntax:" }, { "code": null, "e": 637, "s": 469, "text": "void iter_swap (ForwardIterator1 a, ForwardIterator2 b);\n\nHere, a and b are forward iterators.\n\nReturns: It has a void return type, so it does not \nreturn any value.\n\n" }, { "code": "// C++ program to demonstrate the use of std::iter_swap#include <iostream>#include <algorithm>#include <vector>using namespace std;int main(){ // Declaring first vector vector<int> v1; int i; for (i = 0; i < 10; ++i) { v1.push_back(i); } // v1 contains 0 1 2 3 4 5 6 7 8 9 vector<int>::iterator i1, i2; i1 = v1.begin(); i2 = v1.end() - 1; // Performing swap between first and last element // of vector std::iter_swap(i1, i2); // Displaying v1 after swapping for (i = 0; i < 10; ++i) { cout << v1[i] << \" \"; } return 0;}", "e": 1231, "s": 637, "text": null }, { "code": null, "e": 1239, "s": 1231, "text": "Output:" }, { "code": null, "e": 1260, "s": 1239, "text": "9 1 2 3 4 5 6 7 8 0\n" }, { "code": null, "e": 1436, "s": 1260, "text": "Here, in this program we have swapped elements from v1 with the help of two iterators, one of them pointing at the beginning of v1 and the other one pointing at the end of v1." }, { "code": null, "e": 1464, "s": 1436, "text": "std::iter_swap vs std::swap" }, { "code": null, "e": 1702, "s": 1464, "text": "After coming to know that iter_swap is used to swap the values, just like std::swap(), the question now arises is why should we learn iter_swap, if we have already something called swap(). Some of the reasons in support of iter_swap are:" }, { "code": null, "e": 2077, "s": 1702, "text": "Optimization for node-based sequences: Most STL algorithms operate on iterator ranges. It therefore makes sense to use iter_swap when swapping elements within those ranges, swapping the elements pointed to by two iterators. This allows optimization for node-based sequences such as std::list, whereby the nodes are just relinked, rather than the data actually being swapped." }, { "code": null, "e": 2524, "s": 2077, "text": "Use in STL definition: Some STL algorithm like std::reverse involve the use of std::iter_swap in its definition. Therefore, one should have knowledge about this in order to understand these definition.// Definition of std::reverse()template void reverse(BidirectionalIterator first, BidirectionalIterator last){ while ((first != last) && (first != --last)) { std::iter_swap(first, last); ++first; }}" }, { "code": "// Definition of std::reverse()template void reverse(BidirectionalIterator first, BidirectionalIterator last){ while ((first != last) && (first != --last)) { std::iter_swap(first, last); ++first; }}", "e": 2770, "s": 2524, "text": null }, { "code": null, "e": 2909, "s": 2770, "text": "Providing abstraction: iter_swap usefully encapsulates the part of the swappable interface which you would otherwise implement every time." }, { "code": null, "e": 3212, "s": 2909, "text": "This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3337, "s": 3212, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3348, "s": 3337, "text": "nidhi_biet" }, { "code": null, "e": 3370, "s": 3348, "text": "cpp-algorithm-library" }, { "code": null, "e": 3374, "s": 3370, "text": "STL" }, { "code": null, "e": 3378, "s": 3374, "text": "C++" }, { "code": null, "e": 3382, "s": 3378, "text": "STL" }, { "code": null, "e": 3386, "s": 3382, "text": "CPP" } ]
Draw Ellipse Using Turtle in Python
29 Sep, 2021 Prerequisite: Turtle Programming Basics Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc. Approach: The following steps are used : Import turtle Divide the ellipse into four arcs Define a method to form these arc in pair Call the function. Below is the implementation : Python3 # import packageimport turtle # method to draw ellipsedef draw(rad): # rad --> radius of arc for i in range(2): # two arcs turtle.circle(rad,90) turtle.circle(rad//2,90) # Main section# tilt the shape to negative 45turtle.seth(-45) # calling draw methoddraw(100) Output : The following steps are used : Import turtle Set Screen Divide the ellipse into four arcs Define a method to form these arc in pair Call the function multiple times for different colors. Below is the implementation : Python3 # import package and making objectimport turtlescreen = turtle.Screen() # method to draw ellipsedef draw(rad): # rad --> radius for arc for i in range(2): turtle.circle(rad,90) turtle.circle(rad//2,90) # Main Section# Set screen sizescreen.setup(500,500) # Set screen colorscreen.bgcolor('black') # Colorscol=['violet','blue','green','yellow', 'orange','red'] # some integersval=10ind=0 # turtle speedturtle.speed(100) # loop for multiple ellipsefor i in range(36): # oriented the ellipse at angle = -val turtle.seth(-val) # color of ellipse turtle.color(col[ind]) # to access different color if ind==5: ind=0 else: ind+=1 # calling method draw(80) # orientation change val+=10 # for hiding the turtleturtle.hideturtle() Output : sweetyty Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Sep, 2021" }, { "code": null, "e": 68, "s": 28, "text": "Prerequisite: Turtle Programming Basics" }, { "code": null, "e": 312, "s": 68, "text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle (pen). To move turtle, there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 322, "s": 312, "text": "Approach:" }, { "code": null, "e": 353, "s": 322, "text": "The following steps are used :" }, { "code": null, "e": 367, "s": 353, "text": "Import turtle" }, { "code": null, "e": 401, "s": 367, "text": "Divide the ellipse into four arcs" }, { "code": null, "e": 443, "s": 401, "text": "Define a method to form these arc in pair" }, { "code": null, "e": 462, "s": 443, "text": "Call the function." }, { "code": null, "e": 492, "s": 462, "text": "Below is the implementation :" }, { "code": null, "e": 500, "s": 492, "text": "Python3" }, { "code": "# import packageimport turtle # method to draw ellipsedef draw(rad): # rad --> radius of arc for i in range(2): # two arcs turtle.circle(rad,90) turtle.circle(rad//2,90) # Main section# tilt the shape to negative 45turtle.seth(-45) # calling draw methoddraw(100)", "e": 784, "s": 500, "text": null }, { "code": null, "e": 793, "s": 784, "text": "Output :" }, { "code": null, "e": 824, "s": 793, "text": "The following steps are used :" }, { "code": null, "e": 838, "s": 824, "text": "Import turtle" }, { "code": null, "e": 849, "s": 838, "text": "Set Screen" }, { "code": null, "e": 883, "s": 849, "text": "Divide the ellipse into four arcs" }, { "code": null, "e": 925, "s": 883, "text": "Define a method to form these arc in pair" }, { "code": null, "e": 980, "s": 925, "text": "Call the function multiple times for different colors." }, { "code": null, "e": 1010, "s": 980, "text": "Below is the implementation :" }, { "code": null, "e": 1018, "s": 1010, "text": "Python3" }, { "code": "# import package and making objectimport turtlescreen = turtle.Screen() # method to draw ellipsedef draw(rad): # rad --> radius for arc for i in range(2): turtle.circle(rad,90) turtle.circle(rad//2,90) # Main Section# Set screen sizescreen.setup(500,500) # Set screen colorscreen.bgcolor('black') # Colorscol=['violet','blue','green','yellow', 'orange','red'] # some integersval=10ind=0 # turtle speedturtle.speed(100) # loop for multiple ellipsefor i in range(36): # oriented the ellipse at angle = -val turtle.seth(-val) # color of ellipse turtle.color(col[ind]) # to access different color if ind==5: ind=0 else: ind+=1 # calling method draw(80) # orientation change val+=10 # for hiding the turtleturtle.hideturtle()", "e": 1838, "s": 1018, "text": null }, { "code": null, "e": 1847, "s": 1838, "text": "Output :" }, { "code": null, "e": 1858, "s": 1849, "text": "sweetyty" }, { "code": null, "e": 1872, "s": 1858, "text": "Python-turtle" }, { "code": null, "e": 1879, "s": 1872, "text": "Python" } ]
numpy.append() in Python
04 Dec, 2020 The numpy.append() appends values along the mentioned axis at the end of the arraySyntax : numpy.append(array, values, axis = None) Parameters : array : [array_like]Input array. values : [array_like]values to be added in the arr. Values should be shaped so that arr[...,obj,...] = values. If the axis is defined values can be of any shape as it will be flattened before use. axis : Axis along which we want to insert the values. By default, array is flattened. Return : An copy of array with values being appended at the end as per the mentioned object along a given axis. Code 1 : Appending arrays # Python Program illustrating# numpy.append() import numpy as geek #Working on 1Darr1 = geek.arange(5)print("1D arr1 : ", arr1)print("Shape : ", arr1.shape) arr2 = geek.arange(8, 12)print("\n1D arr2 : ", arr2)print("Shape : ", arr2.shape) # appending the arraysarr3 = geek.append(arr1, arr2)print("\nAppended arr3 : ", arr3) Output : 1D arr1 : [0 1 2 3 4] Shape : (5,) 1D arr2 : [ 8 9 10 11] Shape : (4,) Appended arr3 : [ 0 1 2 3 4 8 9 10 11] Code 2 : Playing with axis # Python Program illustrating# numpy.append() import numpy as geek #Working on 1Darr1 = geek.arange(8).reshape(2, 4)print("2D arr1 : \n", arr1)print("Shape : ", arr1.shape) arr2 = geek.arange(8, 16).reshape(2, 4)print("\n2D arr2 : \n", arr2)print("Shape : ", arr2.shape) # appending the arraysarr3 = geek.append(arr1, arr2)print("\nAppended arr3 by flattened : ", arr3) # appending the arrays with axis = 0arr3 = geek.append(arr1, arr2, axis = 0)print("\nAppended arr3 with axis 0 : \n", arr3) # appending the arrays with axis = 1arr3 = geek.append(arr1, arr2, axis = 1)print("\nAppended arr3 with axis 1 : \n", arr3) Output : 2D arr1 : [[0 1 2 3] [4 5 6 7]] Shape : (2, 4) 2D arr2 : [[ 8 9 10 11] [12 13 14 15]] Shape : (2, 4) Appended arr3 by flattened : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15] Appended arr3 with axis 0 : [[ 0 1 2 3] [ 4 5 6 7] [ 8 9 10 11] [12 13 14 15]] Appended arr3 with axis 1 : [[ 0 1 2 3 8 9 10 11] [ 4 5 6 7 12 13 14 15]] References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.append.html#numpy.append.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Python numpy-arrayManipulation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 119, "s": 28, "text": "The numpy.append() appends values along the mentioned axis at the end of the arraySyntax :" }, { "code": null, "e": 160, "s": 119, "text": "numpy.append(array, values, axis = None)" }, { "code": null, "e": 173, "s": 160, "text": "Parameters :" }, { "code": null, "e": 517, "s": 173, "text": "array : [array_like]Input array. \nvalues : [array_like]values to be added in the arr. Values should be \n shaped so that arr[...,obj,...] = values. If the axis is defined values can be of any\n shape as it will be flattened before use.\naxis : Axis along which we want to insert the values. By default, array\n is flattened. \n" }, { "code": null, "e": 526, "s": 517, "text": "Return :" }, { "code": null, "e": 631, "s": 526, "text": "An copy of array with values being appended at the end as per the mentioned object\nalong a given axis. \n" }, { "code": null, "e": 657, "s": 631, "text": "Code 1 : Appending arrays" }, { "code": "# Python Program illustrating# numpy.append() import numpy as geek #Working on 1Darr1 = geek.arange(5)print(\"1D arr1 : \", arr1)print(\"Shape : \", arr1.shape) arr2 = geek.arange(8, 12)print(\"\\n1D arr2 : \", arr2)print(\"Shape : \", arr2.shape) # appending the arraysarr3 = geek.append(arr1, arr2)print(\"\\nAppended arr3 : \", arr3)", "e": 990, "s": 657, "text": null }, { "code": null, "e": 999, "s": 990, "text": "Output :" }, { "code": null, "e": 1125, "s": 999, "text": "1D arr1 : [0 1 2 3 4]\nShape : (5,)\n\n1D arr2 : [ 8 9 10 11]\nShape : (4,)\n\nAppended arr3 : [ 0 1 2 3 4 8 9 10 11]\n\n" }, { "code": null, "e": 1152, "s": 1125, "text": "Code 2 : Playing with axis" }, { "code": "# Python Program illustrating# numpy.append() import numpy as geek #Working on 1Darr1 = geek.arange(8).reshape(2, 4)print(\"2D arr1 : \\n\", arr1)print(\"Shape : \", arr1.shape) arr2 = geek.arange(8, 16).reshape(2, 4)print(\"\\n2D arr2 : \\n\", arr2)print(\"Shape : \", arr2.shape) # appending the arraysarr3 = geek.append(arr1, arr2)print(\"\\nAppended arr3 by flattened : \", arr3) # appending the arrays with axis = 0arr3 = geek.append(arr1, arr2, axis = 0)print(\"\\nAppended arr3 with axis 0 : \\n\", arr3) # appending the arrays with axis = 1arr3 = geek.append(arr1, arr2, axis = 1)print(\"\\nAppended arr3 with axis 1 : \\n\", arr3)", "e": 1780, "s": 1152, "text": null }, { "code": null, "e": 1789, "s": 1780, "text": "Output :" }, { "code": null, "e": 2160, "s": 1789, "text": "2D arr1 : \n [[0 1 2 3]\n [4 5 6 7]]\nShape : (2, 4)\n\n2D arr2 : \n [[ 8 9 10 11]\n [12 13 14 15]]\nShape : (2, 4)\n\nAppended arr3 by flattened : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]\n\nAppended arr3 with axis 0 : \n [[ 0 1 2 3]\n [ 4 5 6 7]\n [ 8 9 10 11]\n [12 13 14 15]]\n\nAppended arr3 with axis 1 : \n [[ 0 1 2 3 8 9 10 11]\n [ 4 5 6 7 12 13 14 15]]\n" }, { "code": null, "e": 2564, "s": 2160, "text": "References :https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.append.html#numpy.append.This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 2689, "s": 2564, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2720, "s": 2689, "text": "Python numpy-arrayManipulation" }, { "code": null, "e": 2733, "s": 2720, "text": "Python-numpy" }, { "code": null, "e": 2740, "s": 2733, "text": "Python" } ]
Insertion and Deletion in STL Set C++
23 Aug, 2019 Set is a container implemented in C++ language in STL and has a concept similar to how set is defined in mathematics. The facts that separates set from the other containers is that is it contains only the distinct elements and elements can be traversed in sorted order. Having the strong hold on sets is useful in competitive programming and solving algorithmic problems. The insertion and deletion in STL sets are discussed in this article. Using insert() : Insert function is used to insert the elements in the set. After insertion, the reordering of elements takes place and the set is sorted. This function is implemented in 3 ways. insert(ele) : This function inserts the element in set. The insertion only takes place when the element passed is not already in set. It returns a pointer pair . First element pointing to the element already present or newly inserted. Second element returning the boolean status “true” or “false”. insert(hint, ele) : In this implementation, the hint pointer is sent with the element to be inserted. The use of hint pointer is to help insert() know where the actual insertion has to take place. Hence, trying to reduce time to allocate the element. Hint pointer does not force the insertion at specific position. This function returns the pointer to the position where element is inserted. insert(beg_ptr, end_ptr) : This type of insertion is required to insert the elements of other container into set. The repeated elements are not inserted if they are present in the source container. // C++ code to demonstrate the working of insert()#include<iostream>#include<set> // for set operationsusing namespace std; int main(){ // declaring set set<int> st; // declaring iterators set<int>::iterator it = st.begin(); set<int>::iterator it1, it2; // declaring pair for return value of set containing // set iterator and bool pair< set<int>::iterator,bool> ptr; // using insert() to insert single element // inserting 20 ptr = st.insert(20); // checking if the element was already present or newly inserted if (ptr.second) cout << "The element was newly inserted" ; else cout << "The element was already present" ; // printing set elements after insertion cout << "\nThe set elements after 1st insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; // inserting set elements using hint st.insert(it, 24); // printing set elements after insertion cout << "\nThe set elements after 2nd insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; // inserting array elements in set // 24 is not inserted again int arr[3] = { 25, 24, 26 }; st.insert(arr, arr+3); // printing set elements after insertion cout << "\nThe set elements after 3rd insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; } Output: The element was newly inserted The set elements after 1st insertion are : 20 The set elements after 2nd insertion are : 20 24 The set elements after 3rd insertion are : 20 24 25 26 Using emplace : emplace is also used to insert the element into the Set. This function is similar to “insert()” discussed above, the only difference being that “in-place” construction of element takes place at the position of element insertion contrary to insert() which copies or movies existing object. emplace() : Inserts element using in-place construction strategy. Increases the size of set by 1. returns a pointer pair. 1st element of which is iterator pointing to the position of inserted element. 2nd returns a boolean variable indicating an already present or newly created element. emplace_hint() : Takes a “hint_iterator” to get a hint of position of insertion to possibly reduce the time required to insert the element inserted. This does not effect the position of insertion. It takes place where it is defined to internally. // C++ code to demonstrate the working of emplace()// and emplace_hint()#include<iostream>#include<set> // for set operationsusing namespace std; int main(){ // declaring set set<int> st; // declaring iterators set<int>::iterator it = st.begin(); set<int>::iterator it1, it2; // declaring pair for return value of set containing // set iterator and bool pair< set<int>::iterator,bool> ptr; // using emplace() to insert single element // inserting 24 ptr = st.emplace(24); // checking if the element was already present or // newly inserted returns true. newly inserted if (ptr.second) cout << "The element was newly inserted" ; else cout << "The element was already present" ; // printing set elements after insertion cout << "\nThe set elements after 1st insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; // using emplace() to insert single element // inserting 24 // not inserted this time ptr = st.emplace(24); // checking if the element was already present or // newly inserted returns false. already inserted if (ptr.second) cout << "\nThe element was newly inserted" ; else cout << "\nThe element was already present" ; // printing set elements after insertion cout << "\nThe set elements after 2nd insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; // inserting set elements using hint st.emplace_hint(it,25); // printing set elements after insertion cout << "\nThe set elements after 3rd insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " ";} Output: The element was newly inserted The set elements after 1st insertion are : 24 The element was already present The set elements after 2nd insertion are : 24 The set elements after 3rd insertion are : 24 25 Using erase() : erase() is used to erase the element in set mentioned in argument, either its position, its value or a range of number. erase(num) : Erases the value mentioned in its argument. reorders the set after deletion. erase(iter) : Erases the value at the position pointed by the iterator mentioned in its argument. erase(strt_iter,end_iter) : Erases the range of elements starting from “strt_iter” to the “end_iter”. // C++ code to demonstrate the working of erase()#include<iostream>#include<set> // for set operationsusing namespace std; int main(){ // declaring set set<int> st; // declaring iterators set<int>::iterator it; set<int>::iterator it1; set<int>::iterator it2; // declaring pair for return value of set containing // set iterator and bool pair< set<int>::iterator,bool> ptr; // inserting values in set for (int i=1; i<10; i++) st.insert(i*5); // printing initial set elements cout << "The set elements after insertion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; it = st.begin(); cout << endl; // erasing element using iterator // erases 2nd element i.e., 10 ++it; st.erase(it); // printing set elements after deletion cout << "The set elements after 1st deletion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; // erasing element using value st.erase(40); // printing set elements after deletion cout << "\nThe set elements after 2nd deletion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; ++it; ++it; ++it; ++it; // erasing element using range iterator // deletes 25 - last(45) st.erase(it, st.end()); // printing set elements 3rd deletion cout << "\nThe set elements after 3rd deletion are : "; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << " "; cout << endl;} Output: The set elements after insertion are : 5 10 15 20 25 30 35 40 45 The set elements after 1st deletion are : 5 15 20 25 30 35 40 45 The set elements after 2nd deletion are : 5 15 20 25 30 35 45 The set elements after 3rd deletion are : 5 15 20 This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nidhi_biet STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Aug, 2019" }, { "code": null, "e": 494, "s": 52, "text": "Set is a container implemented in C++ language in STL and has a concept similar to how set is defined in mathematics. The facts that separates set from the other containers is that is it contains only the distinct elements and elements can be traversed in sorted order. Having the strong hold on sets is useful in competitive programming and solving algorithmic problems. The insertion and deletion in STL sets are discussed in this article." }, { "code": null, "e": 689, "s": 494, "text": "Using insert() : Insert function is used to insert the elements in the set. After insertion, the reordering of elements takes place and the set is sorted. This function is implemented in 3 ways." }, { "code": null, "e": 987, "s": 689, "text": "insert(ele) : This function inserts the element in set. The insertion only takes place when the element passed is not already in set. It returns a pointer pair . First element pointing to the element already present or newly inserted. Second element returning the boolean status “true” or “false”." }, { "code": null, "e": 1379, "s": 987, "text": "insert(hint, ele) : In this implementation, the hint pointer is sent with the element to be inserted. The use of hint pointer is to help insert() know where the actual insertion has to take place. Hence, trying to reduce time to allocate the element. Hint pointer does not force the insertion at specific position. This function returns the pointer to the position where element is inserted." }, { "code": null, "e": 1577, "s": 1379, "text": "insert(beg_ptr, end_ptr) : This type of insertion is required to insert the elements of other container into set. The repeated elements are not inserted if they are present in the source container." }, { "code": "// C++ code to demonstrate the working of insert()#include<iostream>#include<set> // for set operationsusing namespace std; int main(){ // declaring set set<int> st; // declaring iterators set<int>::iterator it = st.begin(); set<int>::iterator it1, it2; // declaring pair for return value of set containing // set iterator and bool pair< set<int>::iterator,bool> ptr; // using insert() to insert single element // inserting 20 ptr = st.insert(20); // checking if the element was already present or newly inserted if (ptr.second) cout << \"The element was newly inserted\" ; else cout << \"The element was already present\" ; // printing set elements after insertion cout << \"\\nThe set elements after 1st insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; // inserting set elements using hint st.insert(it, 24); // printing set elements after insertion cout << \"\\nThe set elements after 2nd insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; // inserting array elements in set // 24 is not inserted again int arr[3] = { 25, 24, 26 }; st.insert(arr, arr+3); // printing set elements after insertion cout << \"\\nThe set elements after 3rd insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; }", "e": 3002, "s": 1577, "text": null }, { "code": null, "e": 3010, "s": 3002, "text": "Output:" }, { "code": null, "e": 3195, "s": 3010, "text": "The element was newly inserted\nThe set elements after 1st insertion are : 20 \nThe set elements after 2nd insertion are : 20 24 \nThe set elements after 3rd insertion are : 20 24 25 26 \n" }, { "code": null, "e": 3500, "s": 3195, "text": "Using emplace : emplace is also used to insert the element into the Set. This function is similar to “insert()” discussed above, the only difference being that “in-place” construction of element takes place at the position of element insertion contrary to insert() which copies or movies existing object." }, { "code": null, "e": 3788, "s": 3500, "text": "emplace() : Inserts element using in-place construction strategy. Increases the size of set by 1. returns a pointer pair. 1st element of which is iterator pointing to the position of inserted element. 2nd returns a boolean variable indicating an already present or newly created element." }, { "code": null, "e": 4035, "s": 3788, "text": "emplace_hint() : Takes a “hint_iterator” to get a hint of position of insertion to possibly reduce the time required to insert the element inserted. This does not effect the position of insertion. It takes place where it is defined to internally." }, { "code": "// C++ code to demonstrate the working of emplace()// and emplace_hint()#include<iostream>#include<set> // for set operationsusing namespace std; int main(){ // declaring set set<int> st; // declaring iterators set<int>::iterator it = st.begin(); set<int>::iterator it1, it2; // declaring pair for return value of set containing // set iterator and bool pair< set<int>::iterator,bool> ptr; // using emplace() to insert single element // inserting 24 ptr = st.emplace(24); // checking if the element was already present or // newly inserted returns true. newly inserted if (ptr.second) cout << \"The element was newly inserted\" ; else cout << \"The element was already present\" ; // printing set elements after insertion cout << \"\\nThe set elements after 1st insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; // using emplace() to insert single element // inserting 24 // not inserted this time ptr = st.emplace(24); // checking if the element was already present or // newly inserted returns false. already inserted if (ptr.second) cout << \"\\nThe element was newly inserted\" ; else cout << \"\\nThe element was already present\" ; // printing set elements after insertion cout << \"\\nThe set elements after 2nd insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; // inserting set elements using hint st.emplace_hint(it,25); // printing set elements after insertion cout << \"\\nThe set elements after 3rd insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \";}", "e": 5746, "s": 4035, "text": null }, { "code": null, "e": 5754, "s": 5746, "text": "Output:" }, { "code": null, "e": 5962, "s": 5754, "text": "The element was newly inserted\nThe set elements after 1st insertion are : 24 \nThe element was already present\nThe set elements after 2nd insertion are : 24 \nThe set elements after 3rd insertion are : 24 25 \n" }, { "code": null, "e": 6098, "s": 5962, "text": "Using erase() : erase() is used to erase the element in set mentioned in argument, either its position, its value or a range of number." }, { "code": null, "e": 6188, "s": 6098, "text": "erase(num) : Erases the value mentioned in its argument. reorders the set after deletion." }, { "code": null, "e": 6286, "s": 6188, "text": "erase(iter) : Erases the value at the position pointed by the iterator mentioned in its argument." }, { "code": null, "e": 6388, "s": 6286, "text": "erase(strt_iter,end_iter) : Erases the range of elements starting from “strt_iter” to the “end_iter”." }, { "code": "// C++ code to demonstrate the working of erase()#include<iostream>#include<set> // for set operationsusing namespace std; int main(){ // declaring set set<int> st; // declaring iterators set<int>::iterator it; set<int>::iterator it1; set<int>::iterator it2; // declaring pair for return value of set containing // set iterator and bool pair< set<int>::iterator,bool> ptr; // inserting values in set for (int i=1; i<10; i++) st.insert(i*5); // printing initial set elements cout << \"The set elements after insertion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; it = st.begin(); cout << endl; // erasing element using iterator // erases 2nd element i.e., 10 ++it; st.erase(it); // printing set elements after deletion cout << \"The set elements after 1st deletion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; // erasing element using value st.erase(40); // printing set elements after deletion cout << \"\\nThe set elements after 2nd deletion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; ++it; ++it; ++it; ++it; // erasing element using range iterator // deletes 25 - last(45) st.erase(it, st.end()); // printing set elements 3rd deletion cout << \"\\nThe set elements after 3rd deletion are : \"; for (it1 = st.begin(); it1!=st.end(); ++it1) cout << *it1 << \" \"; cout << endl;}", "e": 7935, "s": 6388, "text": null }, { "code": null, "e": 7943, "s": 7935, "text": "Output:" }, { "code": null, "e": 8190, "s": 7943, "text": "The set elements after insertion are : 5 10 15 20 25 30 35 40 45 \nThe set elements after 1st deletion are : 5 15 20 25 30 35 40 45 \nThe set elements after 2nd deletion are : 5 15 20 25 30 35 45 \nThe set elements after 3rd deletion are : 5 15 20 \n" }, { "code": null, "e": 8491, "s": 8190, "text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 8616, "s": 8491, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8627, "s": 8616, "text": "nidhi_biet" }, { "code": null, "e": 8631, "s": 8627, "text": "STL" }, { "code": null, "e": 8635, "s": 8631, "text": "C++" }, { "code": null, "e": 8639, "s": 8635, "text": "STL" }, { "code": null, "e": 8643, "s": 8639, "text": "CPP" } ]
How to Use try – catch as an Expression in Kotlin?
13 Jan, 2022 The try statement consists of a try-block, which contains one or more statements. { } must always be used, even for single statements. A catch-block, a finally-block, or both must be present. This gives us three forms for the try statement: try...catch try...finally try...catch...finally A catch-block contains statements that specify what to do if an exception is thrown in the try-block. If any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block. If no exception is thrown in the try-block, the catch-block is skipped. You can nest one or more try statements. If an inner try statement does not have a catch-block, the enclosing try statement’s catch block is used instead. The finally-block will always execute after the try-block and catch-block(s) have finished executing. It always executes, regardless of whether an exception was thrown or caught. Exceptions in Kotlin are both similar and different compared to those in Java. In Kotlin, throwable is the superclass of all the exceptions, and every exception has a stack trace, message, and an optional cause. The structure of try-catch is also similar to that used in Java. In Kotlin, here’s how a try-catch statement looks: Kotlin try { // some code to execute catch (e: SomeException) { // exception handle } finally { // oprional finally block} At least one catch block is mandatory and the finally block is optional, and so it can be omitted. In Kotlin, try-catch is special as it enables it to be used as an expression. In this article, we will see how we can use try-catch as an expression. Let’s write a simple program that takes in a number as an input and assigns its value to a variable. If the entered value is not a number, we catch the NumberFormatException exception and assign -1 to that variable: Kotlin fun main (args: Array<String>) { val str="23" val a: Int? = try { str. toInt () } catch (e: NumberFormatException) {-1} println (a)} Output: 23 Now, let’s try something crazy and deliberately try to throw the exception: Kotlin fun main (args: Array<String>){ val str="abc" val a: Int? = try { str. toInt () } catch (e: NumberFormatException) { -1 } printin (a)} Output: -1 The usage of try-catch will help you a lot in edge cases as they can be used as an expression. The reason we can use try-catch as an expression is that both try and throw are expressions in Kotlin and hence can be assigned to a variable. When you use try-catch as an expression, the last line of the try or catch block is returned. That’s why, in the first example, we got 23 as the returned value and we got -1 in the second example. Here, one thing to note is that the same thing doesn’t apply to the finally block – that is, writing the finally block will not affect the result: Kotlin fun main (args: Array<String>) { val str="abc" val a: Int = try { str.toInt () } catch (e: NumberFormatException) { -1 } finally { -2 } printIn (a)} Output: -1 As you can see, writing the finally block doesn’t change anything. In Kotlin, all the exceptions are unchecked, which means that we don’t need to apply try-catch at all. This is quite different than Java, where if a method throws an exception, we need to surround it with try-catch. Here’s an example of an IO operation in Kotlin: Kotlin fun fileToString(file: File) : String {// readAllBytes throws TOException,// but we can omit catching itfileContent = Files.readAllBytes (file)return String (fileContent)} As you can see, we don’t need to wrap things with try-catch if we don’t want to. In Java, we couldn’t proceed without handling this exception. Kotlin Exception-Handling Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 269, "s": 28, "text": "The try statement consists of a try-block, which contains one or more statements. { } must always be used, even for single statements. A catch-block, a finally-block, or both must be present. This gives us three forms for the try statement:" }, { "code": null, "e": 281, "s": 269, "text": "try...catch" }, { "code": null, "e": 295, "s": 281, "text": "try...finally" }, { "code": null, "e": 317, "s": 295, "text": "try...catch...finally" }, { "code": null, "e": 987, "s": 317, "text": "A catch-block contains statements that specify what to do if an exception is thrown in the try-block. If any statement within the try-block (or in a function called from within the try-block) throws an exception, control is immediately shifted to the catch-block. If no exception is thrown in the try-block, the catch-block is skipped. You can nest one or more try statements. If an inner try statement does not have a catch-block, the enclosing try statement’s catch block is used instead. The finally-block will always execute after the try-block and catch-block(s) have finished executing. It always executes, regardless of whether an exception was thrown or caught." }, { "code": null, "e": 1315, "s": 987, "text": "Exceptions in Kotlin are both similar and different compared to those in Java. In Kotlin, throwable is the superclass of all the exceptions, and every exception has a stack trace, message, and an optional cause. The structure of try-catch is also similar to that used in Java. In Kotlin, here’s how a try-catch statement looks:" }, { "code": null, "e": 1322, "s": 1315, "text": "Kotlin" }, { "code": "try { // some code to execute catch (e: SomeException) { // exception handle } finally { // oprional finally block}", "e": 1444, "s": 1322, "text": null }, { "code": null, "e": 1693, "s": 1444, "text": "At least one catch block is mandatory and the finally block is optional, and so it can be omitted. In Kotlin, try-catch is special as it enables it to be used as an expression. In this article, we will see how we can use try-catch as an expression." }, { "code": null, "e": 1909, "s": 1693, "text": "Let’s write a simple program that takes in a number as an input and assigns its value to a variable. If the entered value is not a number, we catch the NumberFormatException exception and assign -1 to that variable:" }, { "code": null, "e": 1916, "s": 1909, "text": "Kotlin" }, { "code": "fun main (args: Array<String>) { val str=\"23\" val a: Int? = try { str. toInt () } catch (e: NumberFormatException) {-1} println (a)}", "e": 2053, "s": 1916, "text": null }, { "code": null, "e": 2061, "s": 2053, "text": "Output:" }, { "code": null, "e": 2064, "s": 2061, "text": "23" }, { "code": null, "e": 2140, "s": 2064, "text": "Now, let’s try something crazy and deliberately try to throw the exception:" }, { "code": null, "e": 2147, "s": 2140, "text": "Kotlin" }, { "code": "fun main (args: Array<String>){ val str=\"abc\" val a: Int? = try { str. toInt () } catch (e: NumberFormatException) { -1 } printin (a)}", "e": 2286, "s": 2147, "text": null }, { "code": null, "e": 2294, "s": 2286, "text": "Output:" }, { "code": null, "e": 2297, "s": 2294, "text": "-1" }, { "code": null, "e": 2392, "s": 2297, "text": "The usage of try-catch will help you a lot in edge cases as they can be used as an expression." }, { "code": null, "e": 2732, "s": 2392, "text": "The reason we can use try-catch as an expression is that both try and throw are expressions in Kotlin and hence can be assigned to a variable. When you use try-catch as an expression, the last line of the try or catch block is returned. That’s why, in the first example, we got 23 as the returned value and we got -1 in the second example." }, { "code": null, "e": 2879, "s": 2732, "text": "Here, one thing to note is that the same thing doesn’t apply to the finally block – that is, writing the finally block will not affect the result:" }, { "code": null, "e": 2886, "s": 2879, "text": "Kotlin" }, { "code": "fun main (args: Array<String>) { val str=\"abc\" val a: Int = try { str.toInt () } catch (e: NumberFormatException) { -1 } finally { -2 } printIn (a)}", "e": 3050, "s": 2886, "text": null }, { "code": null, "e": 3058, "s": 3050, "text": "Output:" }, { "code": null, "e": 3061, "s": 3058, "text": "-1" }, { "code": null, "e": 3128, "s": 3061, "text": "As you can see, writing the finally block doesn’t change anything." }, { "code": null, "e": 3392, "s": 3128, "text": "In Kotlin, all the exceptions are unchecked, which means that we don’t need to apply try-catch at all. This is quite different than Java, where if a method throws an exception, we need to surround it with try-catch. Here’s an example of an IO operation in Kotlin:" }, { "code": null, "e": 3399, "s": 3392, "text": "Kotlin" }, { "code": "fun fileToString(file: File) : String {// readAllBytes throws TOException,// but we can omit catching itfileContent = Files.readAllBytes (file)return String (fileContent)}", "e": 3571, "s": 3399, "text": null }, { "code": null, "e": 3714, "s": 3571, "text": "As you can see, we don’t need to wrap things with try-catch if we don’t want to. In Java, we couldn’t proceed without handling this exception." }, { "code": null, "e": 3740, "s": 3714, "text": "Kotlin Exception-Handling" }, { "code": null, "e": 3747, "s": 3740, "text": "Kotlin" } ]
Centralized Clock Synchronization - GeeksforGeeks
31 Jul, 2020 Centralized Clock Synchronization is an internal clock synchronization approach where clocks of system are synchronized with one of clock of system. Clock synchronization is carried out to make all clocks in network agree on the same value. In centralized clock synchronization, one of clocks is appointed as master clock. Other clock of the system are called slaves and these clocks are kept is synchronization with master clock. Master Clock :It is one of clocks of system which is designated as master clock. All remaining clocks are synchronized with this clock. Master clock is also known as time server. It is single in number.Slave Clocks :Remaining clocks of systems after designated master clock are known as slave clocks. These clocks are synchronized with master clock of system. These are various in number in system. Master Clock :It is one of clocks of system which is designated as master clock. All remaining clocks are synchronized with this clock. Master clock is also known as time server. It is single in number. Slave Clocks :Remaining clocks of systems after designated master clock are known as slave clocks. These clocks are synchronized with master clock of system. These are various in number in system. Working :Master clock sends its time to all other clocks (slave clocks) for synchronization. Server broadcasts its time after each ‘t’ time interval. Slave clocks receive time from master clock and set their time accordingly. Time interval ‘t’ is chosen quite carefully. Case-I:If ‘t’ is very small then, master clock frequently sends its time to slave clocks and slave clocks are in propersynchronization with master clock but high communication overhead occurs. Case-II:If ‘t’ is very large then, clocks drift too much from each other. Relation between ‘t’ and ‘p’ :‘t’ represents time interval and ‘p’ represents drift rate between two clocks. When slave clocks are synchronized after every ‘t’ time then drift of slave clock from master clock is p x t.Hence, maximum drift between any two clocks is 2 x p x t. Example –Suppose drift rate between any two clocks is 5 micro second. A synchronized set of six distributed clocks are implemented using Centralized Clock Synchronization. Maximum drift between any two clocks is limited to 1 milli second. Find re-synchronization time interval ‘t’. Explanation : Drift rate (p) = 0.000005 sec. Maximum drift b/w two clocks (e) = 0.001 sec. As we know maximum drift e = 2 x p x t Hence, t = e / (2 x p) = 0.001 / (2 x 0.000005) = 100 sec. Therefore, it can be concluded that re-synchronization time interval should be less than 100 second. Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Memory Management in Operating System Logical and Physical Address in Operating System Program for Least Recently Used (LRU) Page Replacement algorithm Difference between Internal and External fragmentation File Allocation Methods Mutex lock for Linux Thread Synchronization States of a Process in Operating Systems Process Table and Process Control Block (PCB) Dining Philosopher Problem Using Semaphores Process Schedulers in Operating System
[ { "code": null, "e": 24492, "s": 24464, "text": "\n31 Jul, 2020" }, { "code": null, "e": 24641, "s": 24492, "text": "Centralized Clock Synchronization is an internal clock synchronization approach where clocks of system are synchronized with one of clock of system." }, { "code": null, "e": 24923, "s": 24641, "text": "Clock synchronization is carried out to make all clocks in network agree on the same value. In centralized clock synchronization, one of clocks is appointed as master clock. Other clock of the system are called slaves and these clocks are kept is synchronization with master clock." }, { "code": null, "e": 25322, "s": 24923, "text": "Master Clock :It is one of clocks of system which is designated as master clock. All remaining clocks are synchronized with this clock. Master clock is also known as time server. It is single in number.Slave Clocks :Remaining clocks of systems after designated master clock are known as slave clocks. These clocks are synchronized with master clock of system. These are various in number in system." }, { "code": null, "e": 25525, "s": 25322, "text": "Master Clock :It is one of clocks of system which is designated as master clock. All remaining clocks are synchronized with this clock. Master clock is also known as time server. It is single in number." }, { "code": null, "e": 25722, "s": 25525, "text": "Slave Clocks :Remaining clocks of systems after designated master clock are known as slave clocks. These clocks are synchronized with master clock of system. These are various in number in system." }, { "code": null, "e": 25993, "s": 25722, "text": "Working :Master clock sends its time to all other clocks (slave clocks) for synchronization. Server broadcasts its time after each ‘t’ time interval. Slave clocks receive time from master clock and set their time accordingly. Time interval ‘t’ is chosen quite carefully." }, { "code": null, "e": 26186, "s": 25993, "text": "Case-I:If ‘t’ is very small then, master clock frequently sends its time to slave clocks and slave clocks are in propersynchronization with master clock but high communication overhead occurs." }, { "code": null, "e": 26260, "s": 26186, "text": "Case-II:If ‘t’ is very large then, clocks drift too much from each other." }, { "code": null, "e": 26369, "s": 26260, "text": "Relation between ‘t’ and ‘p’ :‘t’ represents time interval and ‘p’ represents drift rate between two clocks." }, { "code": null, "e": 26536, "s": 26369, "text": "When slave clocks are synchronized after every ‘t’ time then drift of slave clock from master clock is p x t.Hence, maximum drift between any two clocks is 2 x p x t." }, { "code": null, "e": 26818, "s": 26536, "text": "Example –Suppose drift rate between any two clocks is 5 micro second. A synchronized set of six distributed clocks are implemented using Centralized Clock Synchronization. Maximum drift between any two clocks is limited to 1 milli second. Find re-synchronization time interval ‘t’." }, { "code": null, "e": 26832, "s": 26818, "text": "Explanation :" }, { "code": null, "e": 27016, "s": 26832, "text": "Drift rate (p) = 0.000005 sec.\n\nMaximum drift b/w two clocks (e) = 0.001 sec.\n\nAs we know maximum drift e = 2 x p x t\n\nHence, \nt = e / (2 x p)\n = 0.001 / (2 x 0.000005)\n = 100 sec.\n" }, { "code": null, "e": 27117, "s": 27016, "text": "Therefore, it can be concluded that re-synchronization time interval should be less than 100 second." }, { "code": null, "e": 27135, "s": 27117, "text": "Operating Systems" }, { "code": null, "e": 27153, "s": 27135, "text": "Operating Systems" }, { "code": null, "e": 27251, "s": 27153, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27260, "s": 27251, "text": "Comments" }, { "code": null, "e": 27273, "s": 27260, "text": "Old Comments" }, { "code": null, "e": 27311, "s": 27273, "text": "Memory Management in Operating System" }, { "code": null, "e": 27360, "s": 27311, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27425, "s": 27360, "text": "Program for Least Recently Used (LRU) Page Replacement algorithm" }, { "code": null, "e": 27480, "s": 27425, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27504, "s": 27480, "text": "File Allocation Methods" }, { "code": null, "e": 27548, "s": 27504, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 27589, "s": 27548, "text": "States of a Process in Operating Systems" }, { "code": null, "e": 27635, "s": 27589, "text": "Process Table and Process Control Block (PCB)" }, { "code": null, "e": 27679, "s": 27635, "text": "Dining Philosopher Problem Using Semaphores" } ]
JavaFX | CustomMenuItem - GeeksforGeeks
19 Apr, 2021 CustomMenuItem is a part of the JavaFX library. CustomMenuItem allows different types of nodes as its menu item. One of the useful property of the customMenuItem is hideOnClick. This property states whether the menu should be hidden when the user clicks the menuitem or not.Constructors of CustomMenuItem: CustomMenuItem(Node n): creates a menuitem with the node specifiedCustomMenuItem(Node n, boolean b): creates a menuitem with the node and hide on click property specified CustomMenuItem(Node n): creates a menuitem with the node specified CustomMenuItem(Node n, boolean b): creates a menuitem with the node and hide on click property specified Commonly used methods: Below programs will illustrate the use of CustomMenuItem: Program to Create a custom menu items and add it to the menu: This program creates a menubar indicated by the name menubar. A menu will be created by name m and 3 custom menuitems menuitem_1, menuitem_2, menuitem_3 will be added to the menu and the menu will be added to the menubar. The menubar will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide a title to the stage. Then a VBox is created, on which addChildren() method is called to attach the menubar inside the scene. Finally, the show() method is called to display the final results. The Custom MenuItems will contain a button, label, and a checkbox. Java // Program to create a custom menu items and add it to the menuimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*; public class CustomMenuItem_1 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle("creating CustomMenuItem "); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label("This is a CustomMenuItem example "); // Create a menu Menu menu = new Menu("Menu"); // Create menuitems CustomMenuItem menuitem_1 = new CustomMenuItem(new Button("MenuItem 1")); CustomMenuItem menuitem_2 = new CustomMenuItem(new Label("MenuItem 2")); CustomMenuItem menuitem_3 = new CustomMenuItem(new CheckBox("MenuItem 3")); // Add menu items to menu menu.getItems().add(menuitem_1); menu.getItems().add(menuitem_2); menu.getItems().add(menuitem_3); // Create a menubar MenuBar menubar = new MenuBar(); // Add menu to menubar menubar.getMenus().add(menu); // Create a VBox VBox vbox = new VBox(menubar); // Create a scene Scene scene = new Scene(vbox, 200, 200); // Set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }} Output: Program to create custom menu items and add it to the menu and use the property hide on click: This program creates a menubar indicated by the name menubar. A menu will be created by name m and 4 custom menuitems menuitem_1, menuitem_2, menuitem_3, menuitem_4 will be added to the menu and the menu will be added to the menubar. The menubar will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide a title to the stage. Then a VBox is created, on which addChildren() method is called to attach the menubar inside the scene. Finally, the show() method is called to display the final results. The CustonMenuItems will contain a button, a slider, a checkbox, and a choicebox. The hide on click property of custom menuitems_2 and menuitems_4 will be set to false and of menuitem_1 and menuitems_3 will be set to true. On Clicking on menuitem_2 and menuitem_4 will not disappear on clicking. Java // Program to create custom menu items and// Add it to the menu and use the property hide on click import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class CustomMenuItem_2 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle("creating CustomMenuItem "); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label("This is a CustomMenuItem example "); // Create a menu Menu menu = new Menu("Menu"); // Create menuitems CustomMenuItem menuitem_1 = new CustomMenuItem(new Button("MenuItem 1")); CustomMenuItem menuitem_2 = new CustomMenuItem(new Slider()); CustomMenuItem menuitem_3 = new CustomMenuItem(new CheckBox("MenuItem 3")); CustomMenuItem menuitem_4 = new CustomMenuItem(new ChoiceBox(FXCollections .observableArrayList("choice 1", "choice 2", "choice 3"))); // Cet hide on click property menuitem_2.setHideOnClick(false); menuitem_4.setHideOnClick(false); menuitem_1.setHideOnClick(true); menuitem_3.setHideOnClick(true); // Add menu items to menu menu.getItems().add(menuitem_1); menu.getItems().add(menuitem_2); menu.getItems().add(menuitem_3); menu.getItems().add(menuitem_4); // Create a menubar MenuBar menubar = new MenuBar(); // Add menu to menubar menubar.getMenus().add(menu); // Create a VBox VBox vbox = new VBox(menubar); // Create a scene Scene scene = new Scene(vbox, 200, 200); // Cet the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/control/CustomMenuItem.html nidhi_biet ManasChhabra2 sweetyty JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples PriorityQueue in Java Internal Working of HashMap in Java
[ { "code": null, "e": 25237, "s": 25209, "text": "\n19 Apr, 2021" }, { "code": null, "e": 25545, "s": 25237, "text": "CustomMenuItem is a part of the JavaFX library. CustomMenuItem allows different types of nodes as its menu item. One of the useful property of the customMenuItem is hideOnClick. This property states whether the menu should be hidden when the user clicks the menuitem or not.Constructors of CustomMenuItem: " }, { "code": null, "e": 25716, "s": 25545, "text": "CustomMenuItem(Node n): creates a menuitem with the node specifiedCustomMenuItem(Node n, boolean b): creates a menuitem with the node and hide on click property specified" }, { "code": null, "e": 25783, "s": 25716, "text": "CustomMenuItem(Node n): creates a menuitem with the node specified" }, { "code": null, "e": 25888, "s": 25783, "text": "CustomMenuItem(Node n, boolean b): creates a menuitem with the node and hide on click property specified" }, { "code": null, "e": 25912, "s": 25888, "text": "Commonly used methods: " }, { "code": null, "e": 25974, "s": 25914, "text": "Below programs will illustrate the use of CustomMenuItem: " }, { "code": null, "e": 26651, "s": 25974, "text": "Program to Create a custom menu items and add it to the menu: This program creates a menubar indicated by the name menubar. A menu will be created by name m and 3 custom menuitems menuitem_1, menuitem_2, menuitem_3 will be added to the menu and the menu will be added to the menubar. The menubar will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide a title to the stage. Then a VBox is created, on which addChildren() method is called to attach the menubar inside the scene. Finally, the show() method is called to display the final results. The Custom MenuItems will contain a button, label, and a checkbox. " }, { "code": null, "e": 26656, "s": 26651, "text": "Java" }, { "code": "// Program to create a custom menu items and add it to the menuimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*; public class CustomMenuItem_1 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle(\"creating CustomMenuItem \"); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label(\"This is a CustomMenuItem example \"); // Create a menu Menu menu = new Menu(\"Menu\"); // Create menuitems CustomMenuItem menuitem_1 = new CustomMenuItem(new Button(\"MenuItem 1\")); CustomMenuItem menuitem_2 = new CustomMenuItem(new Label(\"MenuItem 2\")); CustomMenuItem menuitem_3 = new CustomMenuItem(new CheckBox(\"MenuItem 3\")); // Add menu items to menu menu.getItems().add(menuitem_1); menu.getItems().add(menuitem_2); menu.getItems().add(menuitem_3); // Create a menubar MenuBar menubar = new MenuBar(); // Add menu to menubar menubar.getMenus().add(menu); // Create a VBox VBox vbox = new VBox(menubar); // Create a scene Scene scene = new Scene(vbox, 200, 200); // Set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }}", "e": 28455, "s": 26656, "text": null }, { "code": null, "e": 28465, "s": 28455, "text": "Output: " }, { "code": null, "e": 29417, "s": 28465, "text": "Program to create custom menu items and add it to the menu and use the property hide on click: This program creates a menubar indicated by the name menubar. A menu will be created by name m and 4 custom menuitems menuitem_1, menuitem_2, menuitem_3, menuitem_4 will be added to the menu and the menu will be added to the menubar. The menubar will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide a title to the stage. Then a VBox is created, on which addChildren() method is called to attach the menubar inside the scene. Finally, the show() method is called to display the final results. The CustonMenuItems will contain a button, a slider, a checkbox, and a choicebox. The hide on click property of custom menuitems_2 and menuitems_4 will be set to false and of menuitem_1 and menuitems_3 will be set to true. On Clicking on menuitem_2 and menuitem_4 will not disappear on clicking. " }, { "code": null, "e": 29422, "s": 29417, "text": "Java" }, { "code": "// Program to create custom menu items and// Add it to the menu and use the property hide on click import javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.collections.*;import javafx.stage.Stage;import javafx.scene.text.Text.*;import javafx.scene.paint.*;import javafx.scene.text.*;public class CustomMenuItem_2 extends Application { // Launch the application public void start(Stage stage) { // Set title for the stage stage.setTitle(\"creating CustomMenuItem \"); // Create a tile pane TilePane r = new TilePane(); // Create a label Label description_label = new Label(\"This is a CustomMenuItem example \"); // Create a menu Menu menu = new Menu(\"Menu\"); // Create menuitems CustomMenuItem menuitem_1 = new CustomMenuItem(new Button(\"MenuItem 1\")); CustomMenuItem menuitem_2 = new CustomMenuItem(new Slider()); CustomMenuItem menuitem_3 = new CustomMenuItem(new CheckBox(\"MenuItem 3\")); CustomMenuItem menuitem_4 = new CustomMenuItem(new ChoiceBox(FXCollections .observableArrayList(\"choice 1\", \"choice 2\", \"choice 3\"))); // Cet hide on click property menuitem_2.setHideOnClick(false); menuitem_4.setHideOnClick(false); menuitem_1.setHideOnClick(true); menuitem_3.setHideOnClick(true); // Add menu items to menu menu.getItems().add(menuitem_1); menu.getItems().add(menuitem_2); menu.getItems().add(menuitem_3); menu.getItems().add(menuitem_4); // Create a menubar MenuBar menubar = new MenuBar(); // Add menu to menubar menubar.getMenus().add(menu); // Create a VBox VBox vbox = new VBox(menubar); // Create a scene Scene scene = new Scene(vbox, 200, 200); // Cet the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // Launch the application launch(args); }}", "e": 31695, "s": 29422, "text": null }, { "code": null, "e": 31705, "s": 31695, "text": "Output: " }, { "code": null, "e": 31882, "s": 31705, "text": "Note: The above programs might not run in an online IDE please use an offline compiler.Reference: https://docs.oracle.com/javafx/2/api/javafx/scene/control/CustomMenuItem.html " }, { "code": null, "e": 31893, "s": 31882, "text": "nidhi_biet" }, { "code": null, "e": 31907, "s": 31893, "text": "ManasChhabra2" }, { "code": null, "e": 31916, "s": 31907, "text": "sweetyty" }, { "code": null, "e": 31923, "s": 31916, "text": "JavaFX" }, { "code": null, "e": 31928, "s": 31923, "text": "Java" }, { "code": null, "e": 31933, "s": 31928, "text": "Java" }, { "code": null, "e": 32031, "s": 31933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32046, "s": 32031, "text": "Stream In Java" }, { "code": null, "e": 32067, "s": 32046, "text": "Constructors in Java" }, { "code": null, "e": 32086, "s": 32067, "text": "Exceptions in Java" }, { "code": null, "e": 32116, "s": 32086, "text": "Functional Interfaces in Java" }, { "code": null, "e": 32162, "s": 32116, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 32179, "s": 32162, "text": "Generics in Java" }, { "code": null, "e": 32200, "s": 32179, "text": "Introduction to Java" }, { "code": null, "e": 32243, "s": 32200, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 32265, "s": 32243, "text": "PriorityQueue in Java" } ]
Node.js URL.port API - GeeksforGeeks
14 Oct, 2021 The url.port is an inbuilt application programming interface of class URL within url module which is used to get and set the port portion of the URL.the port value may be a number or a string containing a number in the range 0 to 65535 (inclusive). Setting the value to the default port of the URL objects given protocol will result in the port value becoming the empty string (”). The port value can be an empty string in which case the port depends on the protocol/scheme: Upon assigning a value to the port, the value will first be converted to a string using .toString(). If that string is invalid but it begins with a number, the leading number is assigned to the port. If the number lies outside the range denoted above, it is ignored. Syntax: const url.port Return value: It gets and sets the port portion of the URL. Below programs illustrate the use of url.port Method: Example 1: Javascript // node program to demonstrate the // url.port API as Setter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram'); // Display href and port// value of myURL before changeconsole.log("Before Change");console.log(myURL.href); // assigning port portion// using port APIconsole.log();myURL.port = '12345'; // Display href and password// value of myURL after changeconsole.log("After Change");console.log(myURL.href); Output: Example 2: If the port number is half numeric and half alphabetic Javascript // node program to demonstrate the // url.port API as Setter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram'); // Display href and port// value of myURL before changeconsole.log("Before Change");console.log(myURL.href); // assigning port portion// using port APIconsole.log();myURL.port = '2580abcd'; // Display href and password// value of myURL after changeconsole.log("After Change");console.log(myURL.href); Output: Example 3: Javascript // node program to demonstrate the // url.port API as Getter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram');myURL.port = '1234' // getting the port portion// using portconst port = myURL.port; // Display port value console.log("port is : " + port); //"https" default port is 443console.log("After Change");myURL.port = '443';console.log(myURL.port); Output: NOTE: The above program will compile and run by using the myapp.js command on Node. Reference: https://nodejs.org/api/url.html#url_url_port mridulmanochagfg sagartomar9927 Node-URL Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFileSync() Method How to update Node.js and NPM to next version ? Node.js fs.writeFile() Method How to update NPM ? Difference between promise and async await in Node.js Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 37354, "s": 37326, "text": "\n14 Oct, 2021" }, { "code": null, "e": 37829, "s": 37354, "text": "The url.port is an inbuilt application programming interface of class URL within url module which is used to get and set the port portion of the URL.the port value may be a number or a string containing a number in the range 0 to 65535 (inclusive). Setting the value to the default port of the URL objects given protocol will result in the port value becoming the empty string (”). The port value can be an empty string in which case the port depends on the protocol/scheme:" }, { "code": null, "e": 38096, "s": 37829, "text": "Upon assigning a value to the port, the value will first be converted to a string using .toString(). If that string is invalid but it begins with a number, the leading number is assigned to the port. If the number lies outside the range denoted above, it is ignored." }, { "code": null, "e": 38106, "s": 38096, "text": "Syntax: " }, { "code": null, "e": 38121, "s": 38106, "text": "const url.port" }, { "code": null, "e": 38181, "s": 38121, "text": "Return value: It gets and sets the port portion of the URL." }, { "code": null, "e": 38235, "s": 38181, "text": "Below programs illustrate the use of url.port Method:" }, { "code": null, "e": 38248, "s": 38235, "text": "Example 1: " }, { "code": null, "e": 38259, "s": 38248, "text": "Javascript" }, { "code": "// node program to demonstrate the // url.port API as Setter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram'); // Display href and port// value of myURL before changeconsole.log(\"Before Change\");console.log(myURL.href); // assigning port portion// using port APIconsole.log();myURL.port = '12345'; // Display href and password// value of myURL after changeconsole.log(\"After Change\");console.log(myURL.href);", "e": 38777, "s": 38259, "text": null }, { "code": null, "e": 38786, "s": 38777, "text": "Output: " }, { "code": null, "e": 38854, "s": 38786, "text": "Example 2: If the port number is half numeric and half alphabetic " }, { "code": null, "e": 38865, "s": 38854, "text": "Javascript" }, { "code": "// node program to demonstrate the // url.port API as Setter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.com:80/foo#ram'); // Display href and port// value of myURL before changeconsole.log(\"Before Change\");console.log(myURL.href); // assigning port portion// using port APIconsole.log();myURL.port = '2580abcd'; // Display href and password// value of myURL after changeconsole.log(\"After Change\");console.log(myURL.href);", "e": 39391, "s": 38865, "text": null }, { "code": null, "e": 39400, "s": 39391, "text": "Output: " }, { "code": null, "e": 39413, "s": 39400, "text": "Example 3: " }, { "code": null, "e": 39424, "s": 39413, "text": "Javascript" }, { "code": "// node program to demonstrate the // url.port API as Getter //importing the module 'url'const http = require('url'); // creating and initializing myURLconst myURL = new URL('https://example.org/foo#ram');myURL.port = '1234' // getting the port portion// using portconst port = myURL.port; // Display port value console.log(\"port is : \" + port); //\"https\" default port is 443console.log(\"After Change\");myURL.port = '443';console.log(myURL.port);", "e": 39877, "s": 39424, "text": null }, { "code": null, "e": 39886, "s": 39877, "text": "Output: " }, { "code": null, "e": 39971, "s": 39886, "text": "NOTE: The above program will compile and run by using the myapp.js command on Node. " }, { "code": null, "e": 40028, "s": 39971, "text": "Reference: https://nodejs.org/api/url.html#url_url_port " }, { "code": null, "e": 40045, "s": 40028, "text": "mridulmanochagfg" }, { "code": null, "e": 40060, "s": 40045, "text": "sagartomar9927" }, { "code": null, "e": 40069, "s": 40060, "text": "Node-URL" }, { "code": null, "e": 40077, "s": 40069, "text": "Node.js" }, { "code": null, "e": 40094, "s": 40077, "text": "Web Technologies" }, { "code": null, "e": 40192, "s": 40094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40225, "s": 40192, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 40273, "s": 40225, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40303, "s": 40273, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 40323, "s": 40303, "text": "How to update NPM ?" }, { "code": null, "e": 40377, "s": 40323, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 40417, "s": 40377, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40462, "s": 40417, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40505, "s": 40462, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 40555, "s": 40505, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Area of a leaf inside a square - GeeksforGeeks
06 Jun, 2021 Given an integer a as the side of the square ABCD. The task is to find the area of the leaf AECFA inside the square as shown below: Examples: Input: a = 7 Output: 28 Input: a = 21 Output: 252 Approach: To calculate the area of the leaf, first find the area of the half leaf AECA, which can be given as: Area of half leaf = Area of quadrant AECDA – Area of right triangle ACD. Thus, Area of half leaf = ( PI * a * a / 4 ) – a * a / 2 where PI = 22 / 7 and a is the side of the square. Hence, the area of full leaf will be ( PI * a * a / 2 ) – a * a On taking a * a common we get, Area of leaf = a * a ( PI / 2 – 1 ) Below is the implementation of the above approach: C Java Python3 C# PHP Javascript // C program to find the area of// leaf inside a square#include <stdio.h>#define PI 3.14159265 // Function to find area of// leaffloat area_leaf(float a){ return (a * a * (PI / 2 - 1));} // Driver codeint main(){ float a = 7; printf("%f", area_leaf(a)); return 0;} // Java code to find the area of// leaf inside a squareimport java.lang.*; class GFG { static double PI = 3.14159265; // Function to find the area of // leaf public static double area_leaf(double a) { return (a * a * (PI / 2 - 1)); } // Driver code public static void main(String[] args) { double a = 7; System.out.println(area_leaf(a)); }} # Python3 code to find the area of leaf# inside a squarePI = 3.14159265 # Function to find the area of# leafdef area_leaf( a ): return ( a * a * ( PI / 2 - 1 ) ) # Driver codea = 7print(area_leaf( a )) // C# code to find the area of// leaf// inside squareusing System; class GFG { static double PI = 3.14159265; // Function to find the area of // leaf public static double area_leaf(double a) { return (a * a * (PI / 2 - 1)); } // Driver code public static void Main() { double a = 7; Console.Write(area_leaf(a)); }} <?php// PHP program to find the// area of leaf// inside a square$PI = 3.14159265; // Function to find area of// leaffunction area_leaf( $a ){ global $PI; return ( $a * $a * ( $PI / 2 - 1 ) );} // Driver code$a = 7; echo(area_leaf( $a ));?> <script> // Javascript program to find the area of// leaf inside a squareconst PI = 3.14159265; // Function to find area of// leaffunction area_leaf(a){ return(a * a * (PI / 2 - 1));} // Driver codelet a = 7; document.write(Math.round(area_leaf(a))); // This code is contributed by souravmahato348 </script> 28 souravmahato348 Aptitude Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Puzzle | How much money did the man have before entering the bank? Order and Ranking Questions & Answers C | C Quiz - 113 | Question 1 Program to find Surface Area and Volume of Octagonal Prism Aptitude | Syllogism | Question 3 How to check if a given point lies inside or outside a polygon? Closest Pair of Points using Divide and Conquer algorithm Program for distance between two points on earth How to check if two given line segments intersect? Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)
[ { "code": null, "e": 26345, "s": 26317, "text": "\n06 Jun, 2021" }, { "code": null, "e": 26477, "s": 26345, "text": "Given an integer a as the side of the square ABCD. The task is to find the area of the leaf AECFA inside the square as shown below:" }, { "code": null, "e": 26488, "s": 26477, "text": "Examples: " }, { "code": null, "e": 26512, "s": 26488, "text": "Input: a = 7 Output: 28" }, { "code": null, "e": 26539, "s": 26512, "text": "Input: a = 21 Output: 252 " }, { "code": null, "e": 26652, "s": 26539, "text": "Approach: To calculate the area of the leaf, first find the area of the half leaf AECA, which can be given as: " }, { "code": null, "e": 26964, "s": 26652, "text": "Area of half leaf = Area of quadrant AECDA – Area of right triangle ACD. Thus, Area of half leaf = ( PI * a * a / 4 ) – a * a / 2 where PI = 22 / 7 and a is the side of the square. Hence, the area of full leaf will be ( PI * a * a / 2 ) – a * a On taking a * a common we get, Area of leaf = a * a ( PI / 2 – 1 )" }, { "code": null, "e": 27017, "s": 26964, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27019, "s": 27017, "text": "C" }, { "code": null, "e": 27024, "s": 27019, "text": "Java" }, { "code": null, "e": 27032, "s": 27024, "text": "Python3" }, { "code": null, "e": 27035, "s": 27032, "text": "C#" }, { "code": null, "e": 27039, "s": 27035, "text": "PHP" }, { "code": null, "e": 27050, "s": 27039, "text": "Javascript" }, { "code": "// C program to find the area of// leaf inside a square#include <stdio.h>#define PI 3.14159265 // Function to find area of// leaffloat area_leaf(float a){ return (a * a * (PI / 2 - 1));} // Driver codeint main(){ float a = 7; printf(\"%f\", area_leaf(a)); return 0;}", "e": 27337, "s": 27050, "text": null }, { "code": "// Java code to find the area of// leaf inside a squareimport java.lang.*; class GFG { static double PI = 3.14159265; // Function to find the area of // leaf public static double area_leaf(double a) { return (a * a * (PI / 2 - 1)); } // Driver code public static void main(String[] args) { double a = 7; System.out.println(area_leaf(a)); }}", "e": 27732, "s": 27337, "text": null }, { "code": "# Python3 code to find the area of leaf# inside a squarePI = 3.14159265 # Function to find the area of# leafdef area_leaf( a ): return ( a * a * ( PI / 2 - 1 ) ) # Driver codea = 7print(area_leaf( a ))", "e": 27945, "s": 27732, "text": null }, { "code": "// C# code to find the area of// leaf// inside squareusing System; class GFG { static double PI = 3.14159265; // Function to find the area of // leaf public static double area_leaf(double a) { return (a * a * (PI / 2 - 1)); } // Driver code public static void Main() { double a = 7; Console.Write(area_leaf(a)); }}", "e": 28313, "s": 27945, "text": null }, { "code": "<?php// PHP program to find the// area of leaf// inside a square$PI = 3.14159265; // Function to find area of// leaffunction area_leaf( $a ){ global $PI; return ( $a * $a * ( $PI / 2 - 1 ) );} // Driver code$a = 7; echo(area_leaf( $a ));?>", "e": 28559, "s": 28313, "text": null }, { "code": "<script> // Javascript program to find the area of// leaf inside a squareconst PI = 3.14159265; // Function to find area of// leaffunction area_leaf(a){ return(a * a * (PI / 2 - 1));} // Driver codelet a = 7; document.write(Math.round(area_leaf(a))); // This code is contributed by souravmahato348 </script>", "e": 28870, "s": 28559, "text": null }, { "code": null, "e": 28873, "s": 28870, "text": "28" }, { "code": null, "e": 28891, "s": 28875, "text": "souravmahato348" }, { "code": null, "e": 28900, "s": 28891, "text": "Aptitude" }, { "code": null, "e": 28910, "s": 28900, "text": "Geometric" }, { "code": null, "e": 28923, "s": 28910, "text": "Mathematical" }, { "code": null, "e": 28936, "s": 28923, "text": "Mathematical" }, { "code": null, "e": 28946, "s": 28936, "text": "Geometric" }, { "code": null, "e": 29044, "s": 28946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29111, "s": 29044, "text": "Puzzle | How much money did the man have before entering the bank?" }, { "code": null, "e": 29149, "s": 29111, "text": "Order and Ranking Questions & Answers" }, { "code": null, "e": 29179, "s": 29149, "text": "C | C Quiz - 113 | Question 1" }, { "code": null, "e": 29238, "s": 29179, "text": "Program to find Surface Area and Volume of Octagonal Prism" }, { "code": null, "e": 29272, "s": 29238, "text": "Aptitude | Syllogism | Question 3" }, { "code": null, "e": 29336, "s": 29272, "text": "How to check if a given point lies inside or outside a polygon?" }, { "code": null, "e": 29394, "s": 29336, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 29443, "s": 29394, "text": "Program for distance between two points on earth" }, { "code": null, "e": 29494, "s": 29443, "text": "How to check if two given line segments intersect?" } ]
Space Science with Python — The Solar System centre | by Thomas Albin | Towards Data Science
This is the 3rd part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy! ... we computed and visualised the movement of the Solar System Barycentre (SSB) with respect to the Sun. A 2-dimensional projection on the Ecliptic plane revealed an impressive behaviour of the SSB: The barycentre’s position leaves the Sun on a regular basis, although the Sun contains more than 99 % of the Solar System’s mass! One can understand that this movement is caused by the other celestial objects, like e.g., the planets, the asteroids and even the dust. But what are the main contributors and can we visualise it? In this tutorial, we will aim for this scientific question and make an analysis of the results from last time. For our analysis we will use the same time interval and methods as shown last time. We will use additionally another great library: pandas. pandas is commonly used among data scientists, data engineers and also scientists. One can create so called data-frames that contain data in a tabular form. Filtering, adding columns, applying functions or SQL-similar requests allow one to manipulate and analyse data that is stored in-memory. If you did not install pandas yet, do so by using the pip3 package manager in your virtual environment: pip3 install pandas If you are not familiar with pandas, I would recommend some tutorials, where you can learn the functionalities and advantages of this package. I will explain the shown functions, but I highly encourage you to deep dive into this data driven tool. Our first SPICE function is again furnsh that loads all requested SPICE kernel files that are listed in the SPICE meta file kernel_meta.txt. I already downloaded and added the according kernels for this article, so you can simply pull the recent update from GitHub. Later tutorials require large kernels that need to be downloaded manually. We will learn how to navigate through the official repository and how to choose the correct kernels in a separate tutorial. Again, we choose a time interval starting at the 1st January 2000 and add 10,000 days. We convert the UTC time strings to the Ephemeris time (ET) with the function utc2et and create a numpy array that contains all ET time steps. How should we proceed now with the analysis of the SSB’s movement? Well first of all, we need to compute the trajectory of the barycentre with respect to the Sun. Last time, we did this in a for-loop. From now on, we use the pandas data-frames to store all necessary results in one place. SPICE returns spatial information in km. Again, we want to scale it with the Sun’s radius. We extract this information from the kernel with the function bodvcd (Note: SPICE knows the content of each kernel, you do not need to specify the kernel’s name or location after loading it): The results will be stored in a data-frame called SOLAR_SYSTEM_DF that is defined empty in the beginning. Line 6 creates a column called ET and fills the data-frame with the corresponding ET values. .loc is used in pandas to allocate columns and is also used to filter the data-frame. In line 12+13 we compute the date-time objects of the ETs. The spiceypy function et2datetime is used for this purpose, however, it is not a part of the official SPICE toolkit. In SPICE, the function et2utc is used where one can set miscellaneous date-time formats; the output itself is a string. We add and compute now three new columns. First, POS_SSB_WRT_SUN is computed that contains the position vector of the SSB as seen from the Sun. For this computation we need the ET column and apply row-wise (with .apply) the SPICE function spkgps via a lambda function. spkgps requires the target NAIF ID (targ), the ET (et), the reference frame (ref; here it is the Ecliptic reference frame ECLIPJ2000) and the observer’s NAIF ID (obs). The ID for the SSB and Sun is 0 and 10, respectively. The computed position vectors are then scaled with the Sun’s radius (line 11 + 12). We apply row-wise a lambda function that divides the arrays by the radius. Finally, the distance between the Sun and the SSB is computed, using the SPICE function vnorm. The function computes the length (so-called norm) of a vector and is identical to the numpy function numpy.linalg.norm(). Whether it is data science, space science, astronomy or any other scientific field: visualising and describing data is the first step of a proper analysis. So let’s visualise the distance between the SSB and the Sun as a function of time. For this purpose we use the module matplotlib, as introduced last time. We use the data of the column SSB_WRT_SUN_SCALED_DIST and plot it against the UTC date-time. The following code creates a plot that is shown below. Let’s describe and understand the plot. We see the distance between the SSB and the Sun vs. the date-time given in UTC. The distance-axis is scaled between 0 and 2 Solar Radii and the time-axis starts at the year 2000 and ends right before 2028. We see that the distance varies in time, however, the variation appears to be modulated (different amplitudes; and also frequencies (?)). The distance between two local maxima (around the year 2009 and 2022) is approximately a decade! What do these slow temporal changes mean? The SSB’s position w.r.t. the Sun can be theoretically computed by the sum of all gravity forces (planets, asteroids, dust, etc.). The inner planets (Mercury to Mars) have an orbital period between 90 days and almost 2 years. If the masses of these planets would be significant for the computation of the SSB, we would see a lot of “spikes” and fast changing variations, but we do not. Compared to the inner planets, the outer gas giants (Jupiter, Saturn, Uranus and Neptune) have a larger mass and a larger orbital period (Jupiter revolves the Sun in around 12 years, Saturn needs almost 30 years). Although they are farer away (Jupiter around 5 AU, Saturn around 9.5 AU) it appears that they influence the SSB’s position severely. Can we simply see this effect in the data? Today (29th April 2020) we see the Moon in its waxing phase. With every second the illuminated area as seen from the Earth increases. In a few days the Moon is fully illuminated and its waning phase begins. During its revolutions around us, the Moon appears in different so called phase angles w.r.t. the Sun. Consider the following sketch: The phase angle is the angle between the directional vectors of the Sun and the Moon as seen from the Earth. Generally speaking: the phase angle is the angle that is enclosed by two directional vector as seen from an observer. Thus, the phase angle can be computed between any celestial objects and is defined between 0 and 180 degrees. How is this related to the SSB analysis? As mentioned before, we have the theory that the gas giants’ gravitational pull is the most relevant factor of the SSB’s movement. A large distance between the SSB and the Sun’s centre could mean that the outer planets “line up” to create a stronger gravitational pull from the same direction. To check this phase angle dependency, we add new columns to our data-frame that contain the angles for all gas giants. First, we set up a dictionary that contains an abbreviated name for the planets (barycentres) with the corresponding planet’s NAIF ID codes. A for loop iterates through the dictionary and creates dynamically 2 new columns for each planet (the substring %s is replaced by the planet’s abbreviation): POS_%s_WRT_SUN: Position vector of the planet as seen from the Sun. For this computation, we use again the .apply functionality on the ETs and use the SPICE function spkgps for this purpose. PHASE_ANGLE_SUN_%s2SSB: Phase angle between the planet and the SSB as seen from the Sun. .apply is applied on axis=1, since we need two columns for this computation, namely POS_%s_WRT_SUN and the SSB’s direction vector from the Sun POS_SSB_WRT_SUN. The angle between these two vectors is calculated with the SPICE function vsep. The result is given in rad, thus the numpy function numpy.degrees() is used to convert it to degrees. How is the angle (p) calculated between two vectors (a, b)? The dot product between two vectors is equal to the multiplication of the length of both vectors times the cosine of the enclosed angle. We rearrange the equation to the angle and get the following equation: Now, let’s verify the vsep results. We define a lambda function where we use numpy’s numpy.arccos(), .dot() and .linalg.norm() functions. We use the very first entry of our data-frame and compute the phase angle between the SSB and Jupiter as seen from the Sun. The pandas function .iloc[] allows one to access data via an integer index; here: 0. For both functions we get a result of around 14.9°. We have now a sophisticated data-frame that contains miscellaneous parameters. We got the time in UTC and ET, we have the distance between the Sun and the SSB as well as the phase angles for all gas giants. Now we want to plot the data to see a link between the SSB-Sun distance and the phase angles. How shall we plot the data? We have two different types of data we want to show. First: the distance SSB-Sun (as shown before) and the phase angle between the SSB and each planet as seen from the Sun. To see any link we need to plot them in one plot, resulting in two different y-axes (the x-axis is the time in UTC). We have the phase angles of 4 planets, resulting in 5 curves in one plot. The resulting plot would be too crowded and one could easily lose track of what is shown. So for each planet we create an individual sub-plot. The plots are aligned vertically, to share the date-time axis. Line 3 prepares the figure and creates 4 matplotlib axes. The for-loop iterates through all matplotlib axes and planet data, respectively. Let’s have a deep dive: Line 15: First we create a title for each sub-plot. The name is the planet’s name. Since each planet has its own plot we do not need to set a legend. Line 18–20: Here, we plot the SSB-Sun distance and choose a blue color to distinguish between the distance and phase angle curves. Line 24–30: Some plot formatting, where we add a y-label, axis limits, and colours. Line 33: This command tells matplotlib to create a twin plot in the same matplotlib axis. .twinx() indicates that the x axis (date-time in UTC) is copied. Line 36–39: Now we plot the phase angle between the planet and the SSB (Observer: the Sun). This curve is coloured in orange ... Line 42–49: ... as well as the corresponding y axis label and ticks (the numbers shown on the y axis). Line 52: For a better readability or eye guidance we add a vertical grid along the date-time. At the end we set a label for the time axis, reduce the space between the sub-plots and save the plot. All subplots are shown below. You can see the blue and orange curves representing the SSB-Sun distance and phase angle between the SSB and planet, respectively. The title shows the name of the planet and the right y axis is inverted. As you can see, the large distance between the SSB and the Sun correlates between the years 2020 and 2024 with the small phase angle to the planet Jupiter. However, this effect is less severe for the first local maximum between 2008 and 2012 and does not correlate at all with the minimum between 2012 and 2016. Let’s have a look at this particular minimum. You can see that the phase angles for Saturn, Uranus and Neptune are way larger and create a “counter gravity pull” to the other direction causing the SSB’s position to stay within the Sun. Between 2020 and 2024 the gas giants are more aligned to the same direction causing a maximum distance of almost 2 Solar Radii! Today we had a look at the causes of the SSB’s movement. The distance between the Sun and the barycentre varies slowly in time. The amplitudes change and the time interval between the maxima and minima indicates that the inner planets cannot be the main contributors of this gravitational pull (otherwise we would see more short time spikes and variations that correlate with shorter orbital periods). We analysed the distance between the Sun and the SSB using the phase angle between the SSB and the gas giants as seen from the Sun. It appears that Jupiter is a major factor (since it is the most massive planet and only 5 AU away). However, the other giants cannot be neglected, considering the minimum distance of 0.5 Solar Radii between the years 2012 and 2016. To get a deeper dive into this topic we would need to approach this problem with Newtonian mechanics and compute the SSB’s position w.r.t. the Sun using the gravitational force of each planet. However, we do not want to push this particular topic too hard. The next tutorial will be published on 2nd May 2020, where we will continue working with the phase angle on a complete different space topic. Creating plots in science is often challenging and time consuming. Are there other ways to visualise the data and analysis? Of course! Visualising data in a certain way is only one possible solution. If you would like to share your ideas or plot solutions, feel free to do it. Here or on GitHub. In the meantime, stay healthy and enjoy the night sky,
[ { "code": null, "e": 312, "s": 172, "text": "This is the 3rd part of my Python tutorial series “Space Science with Python”. All codes that are shown here are uploaded on GitHub. Enjoy!" }, { "code": null, "e": 950, "s": 312, "text": "... we computed and visualised the movement of the Solar System Barycentre (SSB) with respect to the Sun. A 2-dimensional projection on the Ecliptic plane revealed an impressive behaviour of the SSB: The barycentre’s position leaves the Sun on a regular basis, although the Sun contains more than 99 % of the Solar System’s mass! One can understand that this movement is caused by the other celestial objects, like e.g., the planets, the asteroids and even the dust. But what are the main contributors and can we visualise it? In this tutorial, we will aim for this scientific question and make an analysis of the results from last time." }, { "code": null, "e": 1488, "s": 950, "text": "For our analysis we will use the same time interval and methods as shown last time. We will use additionally another great library: pandas. pandas is commonly used among data scientists, data engineers and also scientists. One can create so called data-frames that contain data in a tabular form. Filtering, adding columns, applying functions or SQL-similar requests allow one to manipulate and analyse data that is stored in-memory. If you did not install pandas yet, do so by using the pip3 package manager in your virtual environment:" }, { "code": null, "e": 1508, "s": 1488, "text": "pip3 install pandas" }, { "code": null, "e": 1755, "s": 1508, "text": "If you are not familiar with pandas, I would recommend some tutorials, where you can learn the functionalities and advantages of this package. I will explain the shown functions, but I highly encourage you to deep dive into this data driven tool." }, { "code": null, "e": 2220, "s": 1755, "text": "Our first SPICE function is again furnsh that loads all requested SPICE kernel files that are listed in the SPICE meta file kernel_meta.txt. I already downloaded and added the according kernels for this article, so you can simply pull the recent update from GitHub. Later tutorials require large kernels that need to be downloaded manually. We will learn how to navigate through the official repository and how to choose the correct kernels in a separate tutorial." }, { "code": null, "e": 2449, "s": 2220, "text": "Again, we choose a time interval starting at the 1st January 2000 and add 10,000 days. We convert the UTC time strings to the Ephemeris time (ET) with the function utc2et and create a numpy array that contains all ET time steps." }, { "code": null, "e": 2738, "s": 2449, "text": "How should we proceed now with the analysis of the SSB’s movement? Well first of all, we need to compute the trajectory of the barycentre with respect to the Sun. Last time, we did this in a for-loop. From now on, we use the pandas data-frames to store all necessary results in one place." }, { "code": null, "e": 3021, "s": 2738, "text": "SPICE returns spatial information in km. Again, we want to scale it with the Sun’s radius. We extract this information from the kernel with the function bodvcd (Note: SPICE knows the content of each kernel, you do not need to specify the kernel’s name or location after loading it):" }, { "code": null, "e": 3602, "s": 3021, "text": "The results will be stored in a data-frame called SOLAR_SYSTEM_DF that is defined empty in the beginning. Line 6 creates a column called ET and fills the data-frame with the corresponding ET values. .loc is used in pandas to allocate columns and is also used to filter the data-frame. In line 12+13 we compute the date-time objects of the ETs. The spiceypy function et2datetime is used for this purpose, however, it is not a part of the official SPICE toolkit. In SPICE, the function et2utc is used where one can set miscellaneous date-time formats; the output itself is a string." }, { "code": null, "e": 4093, "s": 3602, "text": "We add and compute now three new columns. First, POS_SSB_WRT_SUN is computed that contains the position vector of the SSB as seen from the Sun. For this computation we need the ET column and apply row-wise (with .apply) the SPICE function spkgps via a lambda function. spkgps requires the target NAIF ID (targ), the ET (et), the reference frame (ref; here it is the Ecliptic reference frame ECLIPJ2000) and the observer’s NAIF ID (obs). The ID for the SSB and Sun is 0 and 10, respectively." }, { "code": null, "e": 4252, "s": 4093, "text": "The computed position vectors are then scaled with the Sun’s radius (line 11 + 12). We apply row-wise a lambda function that divides the arrays by the radius." }, { "code": null, "e": 4469, "s": 4252, "text": "Finally, the distance between the Sun and the SSB is computed, using the SPICE function vnorm. The function computes the length (so-called norm) of a vector and is identical to the numpy function numpy.linalg.norm()." }, { "code": null, "e": 4625, "s": 4469, "text": "Whether it is data science, space science, astronomy or any other scientific field: visualising and describing data is the first step of a proper analysis." }, { "code": null, "e": 4873, "s": 4625, "text": "So let’s visualise the distance between the SSB and the Sun as a function of time. For this purpose we use the module matplotlib, as introduced last time. We use the data of the column SSB_WRT_SUN_SCALED_DIST and plot it against the UTC date-time." }, { "code": null, "e": 4928, "s": 4873, "text": "The following code creates a plot that is shown below." }, { "code": null, "e": 5409, "s": 4928, "text": "Let’s describe and understand the plot. We see the distance between the SSB and the Sun vs. the date-time given in UTC. The distance-axis is scaled between 0 and 2 Solar Radii and the time-axis starts at the year 2000 and ends right before 2028. We see that the distance varies in time, however, the variation appears to be modulated (different amplitudes; and also frequencies (?)). The distance between two local maxima (around the year 2009 and 2022) is approximately a decade!" }, { "code": null, "e": 5837, "s": 5409, "text": "What do these slow temporal changes mean? The SSB’s position w.r.t. the Sun can be theoretically computed by the sum of all gravity forces (planets, asteroids, dust, etc.). The inner planets (Mercury to Mars) have an orbital period between 90 days and almost 2 years. If the masses of these planets would be significant for the computation of the SSB, we would see a lot of “spikes” and fast changing variations, but we do not." }, { "code": null, "e": 6184, "s": 5837, "text": "Compared to the inner planets, the outer gas giants (Jupiter, Saturn, Uranus and Neptune) have a larger mass and a larger orbital period (Jupiter revolves the Sun in around 12 years, Saturn needs almost 30 years). Although they are farer away (Jupiter around 5 AU, Saturn around 9.5 AU) it appears that they influence the SSB’s position severely." }, { "code": null, "e": 6227, "s": 6184, "text": "Can we simply see this effect in the data?" }, { "code": null, "e": 6568, "s": 6227, "text": "Today (29th April 2020) we see the Moon in its waxing phase. With every second the illuminated area as seen from the Earth increases. In a few days the Moon is fully illuminated and its waning phase begins. During its revolutions around us, the Moon appears in different so called phase angles w.r.t. the Sun. Consider the following sketch:" }, { "code": null, "e": 6905, "s": 6568, "text": "The phase angle is the angle between the directional vectors of the Sun and the Moon as seen from the Earth. Generally speaking: the phase angle is the angle that is enclosed by two directional vector as seen from an observer. Thus, the phase angle can be computed between any celestial objects and is defined between 0 and 180 degrees." }, { "code": null, "e": 7240, "s": 6905, "text": "How is this related to the SSB analysis? As mentioned before, we have the theory that the gas giants’ gravitational pull is the most relevant factor of the SSB’s movement. A large distance between the SSB and the Sun’s centre could mean that the outer planets “line up” to create a stronger gravitational pull from the same direction." }, { "code": null, "e": 7500, "s": 7240, "text": "To check this phase angle dependency, we add new columns to our data-frame that contain the angles for all gas giants. First, we set up a dictionary that contains an abbreviated name for the planets (barycentres) with the corresponding planet’s NAIF ID codes." }, { "code": null, "e": 7658, "s": 7500, "text": "A for loop iterates through the dictionary and creates dynamically 2 new columns for each planet (the substring %s is replaced by the planet’s abbreviation):" }, { "code": null, "e": 7849, "s": 7658, "text": "POS_%s_WRT_SUN: Position vector of the planet as seen from the Sun. For this computation, we use again the .apply functionality on the ETs and use the SPICE function spkgps for this purpose." }, { "code": null, "e": 8280, "s": 7849, "text": "PHASE_ANGLE_SUN_%s2SSB: Phase angle between the planet and the SSB as seen from the Sun. .apply is applied on axis=1, since we need two columns for this computation, namely POS_%s_WRT_SUN and the SSB’s direction vector from the Sun POS_SSB_WRT_SUN. The angle between these two vectors is calculated with the SPICE function vsep. The result is given in rad, thus the numpy function numpy.degrees() is used to convert it to degrees." }, { "code": null, "e": 8548, "s": 8280, "text": "How is the angle (p) calculated between two vectors (a, b)? The dot product between two vectors is equal to the multiplication of the length of both vectors times the cosine of the enclosed angle. We rearrange the equation to the angle and get the following equation:" }, { "code": null, "e": 8947, "s": 8548, "text": "Now, let’s verify the vsep results. We define a lambda function where we use numpy’s numpy.arccos(), .dot() and .linalg.norm() functions. We use the very first entry of our data-frame and compute the phase angle between the SSB and Jupiter as seen from the Sun. The pandas function .iloc[] allows one to access data via an integer index; here: 0. For both functions we get a result of around 14.9°." }, { "code": null, "e": 9248, "s": 8947, "text": "We have now a sophisticated data-frame that contains miscellaneous parameters. We got the time in UTC and ET, we have the distance between the Sun and the SSB as well as the phase angles for all gas giants. Now we want to plot the data to see a link between the SSB-Sun distance and the phase angles." }, { "code": null, "e": 9730, "s": 9248, "text": "How shall we plot the data? We have two different types of data we want to show. First: the distance SSB-Sun (as shown before) and the phase angle between the SSB and each planet as seen from the Sun. To see any link we need to plot them in one plot, resulting in two different y-axes (the x-axis is the time in UTC). We have the phase angles of 4 planets, resulting in 5 curves in one plot. The resulting plot would be too crowded and one could easily lose track of what is shown." }, { "code": null, "e": 9904, "s": 9730, "text": "So for each planet we create an individual sub-plot. The plots are aligned vertically, to share the date-time axis. Line 3 prepares the figure and creates 4 matplotlib axes." }, { "code": null, "e": 10009, "s": 9904, "text": "The for-loop iterates through all matplotlib axes and planet data, respectively. Let’s have a deep dive:" }, { "code": null, "e": 10159, "s": 10009, "text": "Line 15: First we create a title for each sub-plot. The name is the planet’s name. Since each planet has its own plot we do not need to set a legend." }, { "code": null, "e": 10290, "s": 10159, "text": "Line 18–20: Here, we plot the SSB-Sun distance and choose a blue color to distinguish between the distance and phase angle curves." }, { "code": null, "e": 10374, "s": 10290, "text": "Line 24–30: Some plot formatting, where we add a y-label, axis limits, and colours." }, { "code": null, "e": 10529, "s": 10374, "text": "Line 33: This command tells matplotlib to create a twin plot in the same matplotlib axis. .twinx() indicates that the x axis (date-time in UTC) is copied." }, { "code": null, "e": 10658, "s": 10529, "text": "Line 36–39: Now we plot the phase angle between the planet and the SSB (Observer: the Sun). This curve is coloured in orange ..." }, { "code": null, "e": 10761, "s": 10658, "text": "Line 42–49: ... as well as the corresponding y axis label and ticks (the numbers shown on the y axis)." }, { "code": null, "e": 10855, "s": 10761, "text": "Line 52: For a better readability or eye guidance we add a vertical grid along the date-time." }, { "code": null, "e": 10958, "s": 10855, "text": "At the end we set a label for the time axis, reduce the space between the sub-plots and save the plot." }, { "code": null, "e": 11868, "s": 10958, "text": "All subplots are shown below. You can see the blue and orange curves representing the SSB-Sun distance and phase angle between the SSB and planet, respectively. The title shows the name of the planet and the right y axis is inverted. As you can see, the large distance between the SSB and the Sun correlates between the years 2020 and 2024 with the small phase angle to the planet Jupiter. However, this effect is less severe for the first local maximum between 2008 and 2012 and does not correlate at all with the minimum between 2012 and 2016. Let’s have a look at this particular minimum. You can see that the phase angles for Saturn, Uranus and Neptune are way larger and create a “counter gravity pull” to the other direction causing the SSB’s position to stay within the Sun. Between 2020 and 2024 the gas giants are more aligned to the same direction causing a maximum distance of almost 2 Solar Radii!" }, { "code": null, "e": 12634, "s": 11868, "text": "Today we had a look at the causes of the SSB’s movement. The distance between the Sun and the barycentre varies slowly in time. The amplitudes change and the time interval between the maxima and minima indicates that the inner planets cannot be the main contributors of this gravitational pull (otherwise we would see more short time spikes and variations that correlate with shorter orbital periods). We analysed the distance between the Sun and the SSB using the phase angle between the SSB and the gas giants as seen from the Sun. It appears that Jupiter is a major factor (since it is the most massive planet and only 5 AU away). However, the other giants cannot be neglected, considering the minimum distance of 0.5 Solar Radii between the years 2012 and 2016." }, { "code": null, "e": 13033, "s": 12634, "text": "To get a deeper dive into this topic we would need to approach this problem with Newtonian mechanics and compute the SSB’s position w.r.t. the Sun using the gravitational force of each planet. However, we do not want to push this particular topic too hard. The next tutorial will be published on 2nd May 2020, where we will continue working with the phase angle on a complete different space topic." }, { "code": null, "e": 13329, "s": 13033, "text": "Creating plots in science is often challenging and time consuming. Are there other ways to visualise the data and analysis? Of course! Visualising data in a certain way is only one possible solution. If you would like to share your ideas or plot solutions, feel free to do it. Here or on GitHub." } ]
Penalty Shooters | Practice | GeeksforGeeks
Geek and Nerd are strikers playing football with their friend the Goalie. Their energies are denoted by X,Y and Z respectively. Strikers can only score a goal if the Goalie's energy is a factor of their energy. For every goal scored the energy of the respective player is decreased by 1. Each save decreses the Goalie's energy by 1. The game ends when the Goalie's energy is reduced to 1. The strikers can try to goal repeatedly in any order in order to optimise the total number of goals. Geek takes the lead whenever in doubt. Find the number of goals made by Geek and Nerd. Example 1: Input: X = 4, Y = 9, Z = 5 Output: 3 2 Explaination: 1st Kick: X=4, Y=9, Z=4 Z is not a factor of X or Y. So the Goalie will save the first kick and his energy will reduce by 1. 2nd Kick: X=3, Y=9, Z=4 Z is a factor of X. So Geek will take the goal and reduce X by 1. 3rd Kick: X=3, Y=9, Z=3. Goalie saves. 4th Kick: X=2, Y=9, Z=3. Z is a factor of both X and Y. When in doubt, Geek takes the lead. 5th Kick: X=2, Y=8, Z=3. Nerd goals. 6th Kick: X=2, Y=8, Z=2. Goalie saves. 7th Kick: X=1, Y=8, Z=2. Geek goals. 8th Kick: X=1, Y=7, Z=2. Nerd goals. 9th Kick: X=1, Y=7, Z=1. Goalie saves and ends the game. Example 2: Input: X = 13, Y = 10, Z = 7 Output: 0 3 Explaination: Since X is a prime number, Geek will never goal. Your Task: You do not need to read input or print anything. Your task is to complee the function goals() which takes X, Y and Z as input parameters and returns a list of integers containing two elements denoting the number of goals scored by Geek and Nerd respectively. Expected Time Complexity: O(Z) Expected Auxiliary Space: O(1) Constraints: 1 ≤ X, Y, Z ≤ 105 +1 imohdalam2 months ago Java | O(n) class Solution{ static List<Integer> goals(int X, int Y, int Z) { ArrayList<Integer> list = new ArrayList<Integer>(); int Geek = 0; int Nerd = 0; while(Z != 1){ if( X%Z == 0 && Y%Z == 0){ Geek++; X--; } // Goal by Geek else if(X%Z != 0 && Y%Z != 0){ Z--; } // Goal saved by Goalie else if(X%Z != 0 && Y%Z == 0){ Nerd++; Y--; } // Goal by Nerd else if(X%Z == 0 && Y%Z != 0){ Geek++; X--; } // Goal by Geek } list.add(Geek); list.add(Nerd); return list; } } +1 wsurajml0073 months ago vector<int> goals(int x, int y, int z){ int geek = 0, nerd = 0; while(z != 1){ if(x % z == 0){ geek++; x = x-1; }else if(y % z == 0){ nerd++; y = y-1; }else{ z = z-1; } } vector<int> v; v.push_back(geek); v.push_back(nerd); return v; } 0 vishwajeetofficial20223 months ago //JAVA SOLUTION class Solution{ static List<Integer> goals(int X, int Y, int Z) { // code here ArrayList<Integer> aL = new ArrayList<>(); int a = 0 , b = 0; while(Z > 1) { if(X % Z == 0) { ++a; --X; } else if(Y % Z == 0) { ++b; --Y; } else --Z; } aL.add(a); aL.add(b); return aL; } } 0 diptendunandi3 months ago vector<int> goals(int X, int Y, int Z){ // code here int Xi = X; int Yi = Y; int Zi = Z; while(Z > 1) { if(X%Z == 0){ X--; } else if(Y%Z == 0) { Y--; } else { Z--; } } return {Xi - X, Yi - Y}; } 0 jacksonbusch333 months ago //C++ Solution class Solution{public: vector<int> goals(int X, int Y, int Z){ int Xi = X; int Yi = Y; int Zi = Z; while(Z > 1) { if(X%Z == 0){ --X; } else if(Y%Z == 0) { --Y; } else { --Z; } } return {Xi - X, Yi - Y}; }}; 0 shivkantpandey704 months ago def goals(self, X, Y, Z): a=c=0 b=Z while(b>1): if(X%b==0): a+=1 X-=1 elif Y%b==0: c+=1 Y-=1 else: b-=1 return a,c 0 saivadamodalu4 months ago PLC-22809-13-74074 0 proakash2566 months ago static List<Integer> goals(int X, int Y, int Z) { // code here ArrayList<Integer> ar = new ArrayList<>(); int a = 0 , b = 0; while(Z > 1) { if((X % Z) == 0) { ++a; --X; } else if(Y % Z == 0) { ++b; --Y; } else --Z; } ar.add(a); ar.add(b); return ar; } -1 Rohit Vishwakarma8 months ago Rohit Vishwakarma can someone please tell me where I'm wrong here, its giving me segfault error class Solution{public: vector<int> goals(int x, int y, int z){ // code here if (z == 1) { return vector<int>{0, 0}; } int geek, nerd; geek = nerd = 0; if (x % z == 0) { geek++; x--; } else if (y % z == 0) { nerd++; y--; } else { z--; } vector<int> res = goals(x, y, z); int p=res[0],q=res[1]; res.clear(); return vector<int>{geek + p, nerd + q}; }}; -1 ANKIT SINHA9 months ago ANKIT SINHA https://uploads.disquscdn.c... 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": 806, "s": 226, "text": "Geek and Nerd are strikers playing football with their friend the Goalie. Their energies are denoted by X,Y and Z respectively. \nStrikers can only score a goal if the Goalie's energy is a factor of their energy. For every goal scored the energy of the respective player is decreased by 1. Each save decreses the Goalie's energy by 1. The game ends when the Goalie's energy is reduced to 1. The strikers can try to goal repeatedly in any order in order to optimise the total number of goals. Geek takes the lead whenever in doubt. \nFind the number of goals made by Geek and Nerd. " }, { "code": null, "e": 818, "s": 806, "text": "\nExample 1:" }, { "code": null, "e": 1441, "s": 818, "text": "Input: \nX = 4, Y = 9, Z = 5\n\nOutput: 3 2\n\nExplaination:\n1st Kick: X=4, Y=9, Z=4\nZ is not a factor of X or Y. So the Goalie \nwill save the first kick and his energy will \nreduce by 1. \n\n2nd Kick: X=3, Y=9, Z=4\nZ is a factor of X. So Geek will take the \ngoal and reduce X by 1. \n\n3rd Kick: X=3, Y=9, Z=3. Goalie saves. \n\n4th Kick: X=2, Y=9, Z=3. \nZ is a factor of both X and Y. \nWhen in doubt, Geek takes the lead. \n\n5th Kick: X=2, Y=8, Z=3. Nerd goals.\n6th Kick: X=2, Y=8, Z=2. Goalie saves.\n7th Kick: X=1, Y=8, Z=2. Geek goals.\n8th Kick: X=1, Y=7, Z=2. Nerd goals.\n9th Kick: X=1, Y=7, Z=1. \nGoalie saves and ends the game." }, { "code": null, "e": 1453, "s": 1441, "text": "\nExample 2:" }, { "code": null, "e": 1562, "s": 1453, "text": "Input: \nX = 13, Y = 10, Z = 7\n\nOutput: 0 3\n\nExplaination: Since X is a prime number, \nGeek will never goal. " }, { "code": null, "e": 1834, "s": 1562, "text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complee the function goals() which takes X, Y and Z as input parameters and returns a list of integers containing two elements denoting the number of goals scored by Geek and Nerd respectively. " }, { "code": null, "e": 1897, "s": 1834, "text": "\nExpected Time Complexity: O(Z)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 1929, "s": 1897, "text": "\nConstraints:\n1 ≤ X, Y, Z ≤ 105" }, { "code": null, "e": 1932, "s": 1929, "text": "+1" }, { "code": null, "e": 1954, "s": 1932, "text": "imohdalam2 months ago" }, { "code": null, "e": 1966, "s": 1954, "text": "Java | O(n)" }, { "code": null, "e": 2582, "s": 1966, "text": "class Solution{\n static List<Integer> goals(int X, int Y, int Z)\n {\n ArrayList<Integer> list = new ArrayList<Integer>();\n \n int Geek = 0;\n int Nerd = 0;\n \n while(Z != 1){\n if( X%Z == 0 && Y%Z == 0){ Geek++; X--; } // Goal by Geek\n else if(X%Z != 0 && Y%Z != 0){ Z--; } // Goal saved by Goalie\n else if(X%Z != 0 && Y%Z == 0){ Nerd++; Y--; } // Goal by Nerd\n else if(X%Z == 0 && Y%Z != 0){ Geek++; X--; } // Goal by Geek\n }\n \n list.add(Geek);\n list.add(Nerd);\n \n return list;\n }\n}" }, { "code": null, "e": 2585, "s": 2582, "text": "+1" }, { "code": null, "e": 2609, "s": 2585, "text": "wsurajml0073 months ago" }, { "code": null, "e": 3020, "s": 2609, "text": "vector<int> goals(int x, int y, int z){ int geek = 0, nerd = 0; while(z != 1){ if(x % z == 0){ geek++; x = x-1; }else if(y % z == 0){ nerd++; y = y-1; }else{ z = z-1; } } vector<int> v; v.push_back(geek); v.push_back(nerd); return v; }" }, { "code": null, "e": 3022, "s": 3020, "text": "0" }, { "code": null, "e": 3057, "s": 3022, "text": "vishwajeetofficial20223 months ago" }, { "code": null, "e": 3569, "s": 3057, "text": "//JAVA SOLUTION\n\nclass Solution{\n static List<Integer> goals(int X, int Y, int Z)\n {\n // code here\n ArrayList<Integer> aL = new ArrayList<>();\n int a = 0 , b = 0;\n while(Z > 1)\n {\n if(X % Z == 0)\n {\n ++a;\n --X;\n }\n else if(Y % Z == 0)\n {\n ++b;\n --Y;\n }\n else\n --Z;\n }\n aL.add(a);\n aL.add(b);\n return aL;\n }\n}" }, { "code": null, "e": 3571, "s": 3569, "text": "0" }, { "code": null, "e": 3597, "s": 3571, "text": "diptendunandi3 months ago" }, { "code": null, "e": 3974, "s": 3597, "text": "vector<int> goals(int X, int Y, int Z){\n // code here\n int Xi = X;\n int Yi = Y;\n int Zi = Z;\n \n while(Z > 1) {\n if(X%Z == 0){\n X--;\n }\n else if(Y%Z == 0) {\n Y--;\n }\n else {\n Z--;\n }\n }\n \n return {Xi - X, Yi - Y};\n }" }, { "code": null, "e": 3976, "s": 3974, "text": "0" }, { "code": null, "e": 4003, "s": 3976, "text": "jacksonbusch333 months ago" }, { "code": null, "e": 4018, "s": 4003, "text": "//C++ Solution" }, { "code": null, "e": 4381, "s": 4018, "text": "class Solution{public: vector<int> goals(int X, int Y, int Z){ int Xi = X; int Yi = Y; int Zi = Z; while(Z > 1) { if(X%Z == 0){ --X; } else if(Y%Z == 0) { --Y; } else { --Z; } } return {Xi - X, Yi - Y}; }};" }, { "code": null, "e": 4383, "s": 4381, "text": "0" }, { "code": null, "e": 4412, "s": 4383, "text": "shivkantpandey704 months ago" }, { "code": null, "e": 4652, "s": 4412, "text": "def goals(self, X, Y, Z): a=c=0 b=Z while(b>1): if(X%b==0): a+=1 X-=1 elif Y%b==0: c+=1 Y-=1 else: b-=1 return a,c " }, { "code": null, "e": 4654, "s": 4652, "text": "0" }, { "code": null, "e": 4680, "s": 4654, "text": "saivadamodalu4 months ago" }, { "code": null, "e": 4699, "s": 4680, "text": "PLC-22809-13-74074" }, { "code": null, "e": 4701, "s": 4699, "text": "0" }, { "code": null, "e": 4725, "s": 4701, "text": "proakash2566 months ago" }, { "code": null, "e": 5175, "s": 4725, "text": "static List<Integer> goals(int X, int Y, int Z) { // code here ArrayList<Integer> ar = new ArrayList<>(); int a = 0 , b = 0; while(Z > 1) { if((X % Z) == 0) { ++a; --X; } else if(Y % Z == 0) { ++b; --Y; } else --Z; } ar.add(a); ar.add(b); return ar; }" }, { "code": null, "e": 5178, "s": 5175, "text": "-1" }, { "code": null, "e": 5208, "s": 5178, "text": "Rohit Vishwakarma8 months ago" }, { "code": null, "e": 5226, "s": 5208, "text": "Rohit Vishwakarma" }, { "code": null, "e": 5304, "s": 5226, "text": "can someone please tell me where I'm wrong here, its giving me segfault error" }, { "code": null, "e": 5860, "s": 5304, "text": "class Solution{public: vector<int> goals(int x, int y, int z){ // code here if (z == 1) { return vector<int>{0, 0}; } int geek, nerd; geek = nerd = 0; if (x % z == 0) { geek++; x--; } else if (y % z == 0) { nerd++; y--; } else { z--; } vector<int> res = goals(x, y, z); int p=res[0],q=res[1]; res.clear(); return vector<int>{geek + p, nerd + q}; }};" }, { "code": null, "e": 5863, "s": 5860, "text": "-1" }, { "code": null, "e": 5887, "s": 5863, "text": "ANKIT SINHA9 months ago" }, { "code": null, "e": 5899, "s": 5887, "text": "ANKIT SINHA" }, { "code": null, "e": 5930, "s": 5899, "text": "https://uploads.disquscdn.c..." }, { "code": null, "e": 6076, "s": 5930, "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": 6112, "s": 6076, "text": " Login to access your submissions. " }, { "code": null, "e": 6122, "s": 6112, "text": "\nProblem\n" }, { "code": null, "e": 6132, "s": 6122, "text": "\nContest\n" }, { "code": null, "e": 6195, "s": 6132, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6343, "s": 6195, "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": 6551, "s": 6343, "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": 6657, "s": 6551, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to switch between different activities in android?
This example demonstrates how do I switch between different activities in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:text="MainActivity" android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="40dp"/> <Button android:id="@+id/btnOpenAct2" android:text="Open Second Activity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.btnOpenAct2); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(MainActivity.this, SecondActivity.class); startActivity(intent); } }); } } Step 4 − Create a new empty Activity and add the following code − activity_second.xml: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:text="Second Activity" android:textSize="24sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="40dp"/> <Button android:id="@+id/btnOpenMain" android:text="Go back to MainActivity" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true"/> </RelativeLayout> SecondActivity.java − import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class SecondActivity extends AppCompatActivity { Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); button = findViewById(R.id.btnOpenMain); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(SecondActivity.this, MainActivity.class); startActivity(i); } }); } } 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=".SecondActivity"></activity> <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": 1145, "s": 1062, "text": "This example demonstrates how do I switch between different activities in android." }, { "code": null, "e": 1274, "s": 1145, "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": 1339, "s": 1274, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2089, "s": 1339, "text": "<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns: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:text=\"MainActivity\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"40dp\"/>\n <Button\n android:id=\"@+id/btnOpenAct2\"\n android:text=\"Open Second Activity\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 2146, "s": 2089, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 2847, "s": 2146, "text": "import android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class MainActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n button = findViewById(R.id.btnOpenAct2);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent intent = new Intent(MainActivity.this, SecondActivity.class);\n startActivity(intent);\n }\n });\n }\n}" }, { "code": null, "e": 2913, "s": 2847, "text": "Step 4 − Create a new empty Activity and add the following code −" }, { "code": null, "e": 3732, "s": 2913, "text": "activity_second.xml:\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:text=\"Second Activity\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"40dp\"/>\n <Button\n android:id=\"@+id/btnOpenMain\"\n android:text=\"Go back to MainActivity\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"/>\n</RelativeLayout>" }, { "code": null, "e": 3754, "s": 3732, "text": "SecondActivity.java −" }, { "code": null, "e": 4449, "s": 3754, "text": "import android.content.Intent;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.Button;\npublic class SecondActivity extends AppCompatActivity {\n Button button;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_second);\n button = findViewById(R.id.btnOpenMain);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Intent i = new Intent(SecondActivity.this, MainActivity.class);\n startActivity(i);\n }\n });\n }\n}" }, { "code": null, "e": 4504, "s": 4449, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5233, "s": 4504, "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=\".SecondActivity\"></activity>\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": 5580, "s": 5233, "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": 5621, "s": 5580, "text": "Click here to download the project code." } ]
How to Find Closed and Maximal Frequent Itemsets from FP-Growth | by Andrewngai | Towards Data Science
Python Optimization on finding Closed and Maximal Frequent Itemsets In the last article, I have discussed in detail what is FP-growth, and how does it work to find frequent itemsets. Also, I demonstrated the python implementation from scratch. In this article, I would like to introduce two important concepts in Association Rule Mining, closed, and maximal frequent itemsets. In order to understand the concept, you need to have some basic knowledge of what is an FPtree and what is frequent itemsets. My last article covers all the basics. Understand and Build FP-Growth Algorithm in Python Here we quickly review the concept of frequent itemsets. An itemset is whose support is greater than or equal to a minsup(Minimum Support) threshold. Support is the frequency of occurrence of an itemset. For example, given a set of transactions T, we would like to find all itemsets that appear more than 2 times in all transactions. This can be viewed as finding all frequent itemsets with minsup ≥2. Then what are closed and maximal frequent itemsets? By definition, An itemset is maximal frequent if none of its immediate supersets is frequent. An itemset is closed if none of its immediate supersets has the same support as the itemset. Let’s use an example and diagram representation to better understand the concept. Here we have transactions T with 5 transactions, let’s present all the itemsets hierarchy using a tree-type diagram and write down the transactions the itemset appears on top in red. If we set the minsup to be 2, any itemsets that appear more than twice will be frequent itemsets. And among those frequent itemsets, we can find closed and maximal frequent itemsets by comparing their support(frequency of occurrence) to their supersets. We can see the maximal itemsets are a subset of closed itemsets. Also, the maximal itemset works as a boundary, anything below the maximal sets is not frequent itemsets(any superset of maximal itemsets are not frequent). There are many different approaches trying to efficiently find close and maximal frequent itemsets. And this is still a popular research problem in the data mining field. If you are interested, you can find many research articles on different algorithms to solve this problem. I will demonstrate a relatively simple approach to mine the closed and maximal frequent itemsets based on the frequent itemsets found by comparing each items’ support with their supersets. However, this approach can be quite time consuming, considering an O(n2) runtime complexity. To optimize the algorithm when dealing with large databases, we need to take advantage of a python dictionary. By storing all itemsets with the same support count into a dictionary, using support as the key, we can reduce the complexity to O(n). Because we do not need to compare every item since all supersets have ≤ support from their parents. And we only need to compare items with the same support count when finding closed itemsets. The same thing applies when finding maximal itemsets. For implementation, I used the MLXtend library and fpgrowth function to compute the frequent itemsets first, and write my own function to mine the closed and maximal frequent itemsets from the result of the first step. #Import all basic librayimport pandas as pdfrom mlxtend.preprocessing import TransactionEncoderimport timefrom mlxtend.frequent_patterns import fpgrowth#Task1 : Compute Frequent Item Set using mlxtend.frequent_patternste = TransactionEncoder()te_ary = te.fit(dataset).transform(dataset)df = pd.DataFrame(te_ary, columns=te.columns_)start_time = time.time()frequent = fpgrowth(df, min_support=0.001, use_colnames=True)print('Time to find frequent itemset')print("--- %s seconds ---" % (time.time() - start_time))# Task 2&3: Find closed/max frequent itemset using frequent itemset found in task1su = frequent.support.unique()#all unique support count#Dictionay storing itemset with same support count keyfredic = {}for i in range(len(su)): inset = list(frequent.loc[frequent.support ==su[i]]['itemsets']) fredic[su[i]] = inset#Dictionay storing itemset with support count <= keyfredic2 = {}for i in range(len(su)): inset2 = list(frequent.loc[frequent.support<=su[i]]['itemsets']) fredic2[su[i]] = inset2#Find Closed frequent itemsetstart_time = time.time()cl = []for index, row in frequent.iterrows(): isclose = True cli = row['itemsets'] cls = row['support'] checkset = fredic[cls] for i in checkset: if (cli!=i): if(frozenset.issubset(cli,i)): isclose = False break if(isclose): cl.append(row['itemsets'])print('Time to find Close frequent itemset')print("--- %s seconds ---" % (time.time() - start_time)) #Find Max frequent itemsetstart_time = time.time()ml = []for index, row in frequent.iterrows(): isclose = True cli = row['itemsets'] cls = row['support'] checkset = fredic2[cls] for i in checkset: if (cli!=i): if(frozenset.issubset(cli,i)): isclose = False break if(isclose): ml.append(row['itemsets'])print('Time to find Max frequent itemset')print("--- %s seconds ---" % (time.time() - start_time)) Thanks for reading and I am looking forward to hearing your questions and thoughts. If you want to learn more about Data Science and Cloud Computing, you can find me on Linkedin.
[ { "code": null, "e": 239, "s": 171, "text": "Python Optimization on finding Closed and Maximal Frequent Itemsets" }, { "code": null, "e": 713, "s": 239, "text": "In the last article, I have discussed in detail what is FP-growth, and how does it work to find frequent itemsets. Also, I demonstrated the python implementation from scratch. In this article, I would like to introduce two important concepts in Association Rule Mining, closed, and maximal frequent itemsets. In order to understand the concept, you need to have some basic knowledge of what is an FPtree and what is frequent itemsets. My last article covers all the basics." }, { "code": null, "e": 764, "s": 713, "text": "Understand and Build FP-Growth Algorithm in Python" }, { "code": null, "e": 1166, "s": 764, "text": "Here we quickly review the concept of frequent itemsets. An itemset is whose support is greater than or equal to a minsup(Minimum Support) threshold. Support is the frequency of occurrence of an itemset. For example, given a set of transactions T, we would like to find all itemsets that appear more than 2 times in all transactions. This can be viewed as finding all frequent itemsets with minsup ≥2." }, { "code": null, "e": 1218, "s": 1166, "text": "Then what are closed and maximal frequent itemsets?" }, { "code": null, "e": 1487, "s": 1218, "text": "By definition, An itemset is maximal frequent if none of its immediate supersets is frequent. An itemset is closed if none of its immediate supersets has the same support as the itemset. Let’s use an example and diagram representation to better understand the concept." }, { "code": null, "e": 1670, "s": 1487, "text": "Here we have transactions T with 5 transactions, let’s present all the itemsets hierarchy using a tree-type diagram and write down the transactions the itemset appears on top in red." }, { "code": null, "e": 1924, "s": 1670, "text": "If we set the minsup to be 2, any itemsets that appear more than twice will be frequent itemsets. And among those frequent itemsets, we can find closed and maximal frequent itemsets by comparing their support(frequency of occurrence) to their supersets." }, { "code": null, "e": 2145, "s": 1924, "text": "We can see the maximal itemsets are a subset of closed itemsets. Also, the maximal itemset works as a boundary, anything below the maximal sets is not frequent itemsets(any superset of maximal itemsets are not frequent)." }, { "code": null, "e": 3196, "s": 2145, "text": "There are many different approaches trying to efficiently find close and maximal frequent itemsets. And this is still a popular research problem in the data mining field. If you are interested, you can find many research articles on different algorithms to solve this problem. I will demonstrate a relatively simple approach to mine the closed and maximal frequent itemsets based on the frequent itemsets found by comparing each items’ support with their supersets. However, this approach can be quite time consuming, considering an O(n2) runtime complexity. To optimize the algorithm when dealing with large databases, we need to take advantage of a python dictionary. By storing all itemsets with the same support count into a dictionary, using support as the key, we can reduce the complexity to O(n). Because we do not need to compare every item since all supersets have ≤ support from their parents. And we only need to compare items with the same support count when finding closed itemsets. The same thing applies when finding maximal itemsets." }, { "code": null, "e": 3415, "s": 3196, "text": "For implementation, I used the MLXtend library and fpgrowth function to compute the frequent itemsets first, and write my own function to mine the closed and maximal frequent itemsets from the result of the first step." }, { "code": null, "e": 5395, "s": 3415, "text": "#Import all basic librayimport pandas as pdfrom mlxtend.preprocessing import TransactionEncoderimport timefrom mlxtend.frequent_patterns import fpgrowth#Task1 : Compute Frequent Item Set using mlxtend.frequent_patternste = TransactionEncoder()te_ary = te.fit(dataset).transform(dataset)df = pd.DataFrame(te_ary, columns=te.columns_)start_time = time.time()frequent = fpgrowth(df, min_support=0.001, use_colnames=True)print('Time to find frequent itemset')print(\"--- %s seconds ---\" % (time.time() - start_time))# Task 2&3: Find closed/max frequent itemset using frequent itemset found in task1su = frequent.support.unique()#all unique support count#Dictionay storing itemset with same support count keyfredic = {}for i in range(len(su)): inset = list(frequent.loc[frequent.support ==su[i]]['itemsets']) fredic[su[i]] = inset#Dictionay storing itemset with support count <= keyfredic2 = {}for i in range(len(su)): inset2 = list(frequent.loc[frequent.support<=su[i]]['itemsets']) fredic2[su[i]] = inset2#Find Closed frequent itemsetstart_time = time.time()cl = []for index, row in frequent.iterrows(): isclose = True cli = row['itemsets'] cls = row['support'] checkset = fredic[cls] for i in checkset: if (cli!=i): if(frozenset.issubset(cli,i)): isclose = False break if(isclose): cl.append(row['itemsets'])print('Time to find Close frequent itemset')print(\"--- %s seconds ---\" % (time.time() - start_time)) #Find Max frequent itemsetstart_time = time.time()ml = []for index, row in frequent.iterrows(): isclose = True cli = row['itemsets'] cls = row['support'] checkset = fredic2[cls] for i in checkset: if (cli!=i): if(frozenset.issubset(cli,i)): isclose = False break if(isclose): ml.append(row['itemsets'])print('Time to find Max frequent itemset')print(\"--- %s seconds ---\" % (time.time() - start_time))" } ]
How to convert columns of an R data frame into rows?
If the row values are incorrectly recorded into columns then we might want to convert the columns into rows. Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as.data.frame(t(df)). Live Demo set.seed(4) x1<-rnorm(5,10,2) x2<-letters[1:5] x3<-1:5 df1<-data.frame(x1,x2,x3) df1 x1 x2 x3 1 10.433510 a 1 2 8.915015 b 2 3 11.782289 c 3 4 11.191961 d 4 5 13.271236 e 5 Converting columns of df1 to rows − df1_new<-as.data.frame(t(df1)) df1_new V1 V2 V3 V4 V5 x1 10.433510 8.915015 11.782289 11.191961 13.271236 x2 a b c d e x3 1 2 3 4 5 Live Demo a<-sample(0:1,20,replace=TRUE) b<-sample(0:5,20,replace=TRUE) c<-sample(1:10,20,replace=TRUE) d<-sample(6:10,20,replace=TRUE) df2<-data.frame(a,b,c,d) df2 a b c d 1 0 3 5 10 2 1 4 9 10 3 1 4 2 9 4 1 5 10 7 5 1 4 4 6 6 1 0 8 6 7 1 5 10 9 8 0 2 2 6 9 1 5 10 9 10 0 4 6 9 11 0 3 10 9 12 0 0 6 10 13 0 3 1 10 14 0 5 4 7 15 1 2 2 10 16 1 4 4 10 17 0 3 3 8 18 0 3 1 7 19 1 5 7 9 20 1 5 7 7 Converting columns of df2 to rows − df2_new<-as.data.frame(t(df2)) df2_new V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 a 0 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 1 b 3 4 4 5 4 0 5 2 5 4 3 0 3 5 2 4 3 3 5 5 c 5 9 2 10 4 8 10 2 10 6 10 6 1 4 2 4 3 1 7 7 d 10 10 9 7 6 6 9 6 9 9 9 10 10 7 10 10 8 7 9 7 Live Demo y1<-LETTERS[1:20] y2<-letters[1:20] y3<-sample(LETTERS[1:4],20,replace=TRUE) df3<-data.frame(y1,y2,y3) df3 y1 y2 y3 1 A a A 2 B b A 3 C c D 4 D d C 5 E e C 6 F f B 7 G g A 8 H h C 9 I i B 10 J j A 11 K k A 12 L l C 13 M m C 14 N n A 15 O o A 16 P p C 17 Q q D 18 R r D 19 S s D 20 T t D Converting columns of df3 to rows − df3_new<-as.data.frame(t(df3)) df3_new V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 y1 A B C D E F G H I J K L M N O P Q R S T y2 a b c d e f g h i j k l m n o p q r s t y3 A A D C C B A C B A A C C A A C D D D D Live Demo z1<-rpois(20,10) z2<-rpois(20,5) z3<-rpois(20,8) z4<-rpois(20,4) df4<-data.frame(z1,z2,z3,z4) df4 z1 z2 z3 z4 1 10 11 13 2 2 8 3 9 2 3 6 4 10 3 4 16 6 10 4 5 9 7 5 8 6 4 5 5 3 7 7 4 3 2 8 8 2 9 3 9 12 6 9 4 10 15 7 9 3 11 8 5 10 2 12 20 4 6 4 13 5 4 10 8 14 10 2 8 1 15 20 5 9 3 16 5 5 8 5 17 13 5 8 6 18 7 1 14 3 19 12 2 9 6 20 9 8 11 2 Converting columns of df4 to rows − df4_new<-as.data.frame(t(df4)) df4_new V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20 z1 10 8 6 16 9 4 7 8 12 15 8 20 5 10 20 5 13 7 12 9 z2 11 3 4 6 7 5 4 2 6 7 5 4 4 2 5 5 5 1 2 8 z3 13 9 10 10 5 5 3 9 9 9 10 6 10 8 9 8 8 14 9 11 z4 2 2 3 4 8 3 2 3 4 3 2 4 8 1 3 5 6 3 6 2
[ { "code": null, "e": 1413, "s": 1062, "text": "If the row values are incorrectly recorded into columns then we might want to convert the columns into rows. Thus, to convert columns of an R data frame into rows we can use transpose function t. For example, if we have a data frame df with five columns and five rows then we can convert the columns of the df into rows by using as.data.frame(t(df))." }, { "code": null, "e": 1424, "s": 1413, "text": " Live Demo" }, { "code": null, "e": 1509, "s": 1424, "text": "set.seed(4)\nx1<-rnorm(5,10,2)\nx2<-letters[1:5]\nx3<-1:5\ndf1<-data.frame(x1,x2,x3)\ndf1" }, { "code": null, "e": 1612, "s": 1509, "text": " x1 x2 x3\n1 10.433510 a 1\n2 8.915015 b 2\n3 11.782289 c 3\n4 11.191961 d 4\n5 13.271236 e 5" }, { "code": null, "e": 1648, "s": 1612, "text": "Converting columns of df1 to rows −" }, { "code": null, "e": 1687, "s": 1648, "text": "df1_new<-as.data.frame(t(df1))\ndf1_new" }, { "code": null, "e": 1880, "s": 1687, "text": " V1 V2 V3 V4 V5\nx1 10.433510 8.915015 11.782289 11.191961 13.271236\nx2 a b c d e\nx3 1 2 3 4 5" }, { "code": null, "e": 1891, "s": 1880, "text": " Live Demo" }, { "code": null, "e": 2046, "s": 1891, "text": "a<-sample(0:1,20,replace=TRUE)\nb<-sample(0:5,20,replace=TRUE)\nc<-sample(1:10,20,replace=TRUE)\nd<-sample(6:10,20,replace=TRUE)\ndf2<-data.frame(a,b,c,d)\ndf2" }, { "code": null, "e": 2297, "s": 2046, "text": " a b c d\n1 0 3 5 10\n2 1 4 9 10\n3 1 4 2 9\n4 1 5 10 7\n5 1 4 4 6\n6 1 0 8 6\n7 1 5 10 9\n8 0 2 2 6\n9 1 5 10 9\n10 0 4 6 9\n11 0 3 10 9\n12 0 0 6 10\n13 0 3 1 10\n14 0 5 4 7\n15 1 2 2 10\n16 1 4 4 10\n17 0 3 3 8\n18 0 3 1 7\n19 1 5 7 9\n20 1 5 7 7" }, { "code": null, "e": 2333, "s": 2297, "text": "Converting columns of df2 to rows −" }, { "code": null, "e": 2372, "s": 2333, "text": "df2_new<-as.data.frame(t(df2))\ndf2_new" }, { "code": null, "e": 2729, "s": 2372, "text": " V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20\na 0 1 1 1 1 1 1 0 1 0 0 0 0 0 1 1 0 0 1 1\nb 3 4 4 5 4 0 5 2 5 4 3 0 3 5 2 4 3 3 5 5\nc 5 9 2 10 4 8 10 2 10 6 10 6 1 4 2 4 3 1 7 7\nd 10 10 9 7 6 6 9 6 9 9 9 10 10 7 10 10 8 7 9 7" }, { "code": null, "e": 2740, "s": 2729, "text": " Live Demo" }, { "code": null, "e": 2847, "s": 2740, "text": "y1<-LETTERS[1:20]\ny2<-letters[1:20]\ny3<-sample(LETTERS[1:4],20,replace=TRUE)\ndf3<-data.frame(y1,y2,y3)\ndf3" }, { "code": null, "e": 3037, "s": 2847, "text": " y1 y2 y3\n1 A a A\n2 B b A\n3 C c D\n4 D d C\n5 E e C\n6 F f B\n7 G g A\n8 H h C\n9 I i B\n10 J j A\n11 K k A\n12 L l C\n13 M m C\n14 N n A\n15 O o A\n16 P p C\n17 Q q D\n18 R r D\n19 S s D\n20 T t D" }, { "code": null, "e": 3073, "s": 3037, "text": "Converting columns of df3 to rows −" }, { "code": null, "e": 3112, "s": 3073, "text": "df3_new<-as.data.frame(t(df3))\ndf3_new" }, { "code": null, "e": 3401, "s": 3112, "text": " V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20\ny1 A B C D E F G H I J K L M N O P Q R S T\ny2 a b c d e f g h i j k l m n o p q r s t\ny3 A A D C C B A C B A A C C A A C D D D D" }, { "code": null, "e": 3412, "s": 3401, "text": " Live Demo" }, { "code": null, "e": 3510, "s": 3412, "text": "z1<-rpois(20,10)\nz2<-rpois(20,5)\nz3<-rpois(20,8)\nz4<-rpois(20,4)\ndf4<-data.frame(z1,z2,z3,z4)\ndf4" }, { "code": null, "e": 3806, "s": 3510, "text": " z1 z2 z3 z4\n1 10 11 13 2\n2 8 3 9 2\n3 6 4 10 3\n4 16 6 10 4\n5 9 7 5 8\n6 4 5 5 3\n7 7 4 3 2\n8 8 2 9 3\n9 12 6 9 4\n10 15 7 9 3\n11 8 5 10 2\n12 20 4 6 4\n13 5 4 10 8\n14 10 2 8 1\n15 20 5 9 3\n16 5 5 8 5\n17 13 5 8 6\n18 7 1 14 3\n19 12 2 9 6\n20 9 8 11 2" }, { "code": null, "e": 3842, "s": 3806, "text": "Converting columns of df4 to rows −" }, { "code": null, "e": 3881, "s": 3842, "text": "df4_new<-as.data.frame(t(df4))\ndf4_new" }, { "code": null, "e": 4249, "s": 3881, "text": " V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15 V16 V17 V18 V19 V20\nz1 10 8 6 16 9 4 7 8 12 15 8 20 5 10 20 5 13 7 12 9\nz2 11 3 4 6 7 5 4 2 6 7 5 4 4 2 5 5 5 1 2 8\nz3 13 9 10 10 5 5 3 9 9 9 10 6 10 8 9 8 8 14 9 11\nz4 2 2 3 4 8 3 2 3 4 3 2 4 8 1 3 5 6 3 6 2" } ]
What is strncmp() Function in C language?
The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2. An array of characters is called a string. The syntax for declaring an array is as follows − char stringname [size]; For example − char string[50]; string of length 50 characters Using single character constant − char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’} Using string constants − char string[10] = "Hello":; Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’. This function is used for comparing first ‘n’ characters of 2 strings. The syntax for strncmp() function is as follows − strncmp ( string1, string2, n) char a[10] = "the"; char b[10] = "there" strncmp (a,b,3); The output would be that the Both strings are equal. Given below is a C program to compare a specific character between two strings using strncmp library function − Live Demo #include<stdio.h> #include<string.h> void main(){ //Declaring two strings// char string1[25],string2[25]; int value; //Reading string 1 and String 2// printf("Enter String 1: "); gets(string1); printf("Enter String 2: "); gets(string2); //Comparing using library function// value = strncmp(string1,string2,4); //If conditions// if(value==0){ printf("%s is same as %s",string1,string2); } else if(value>0){ printf("%s is greater than %s",string1,string2); } else { printf("%s is less than %s",string1,string2); } } When the above program is executed, it produces the following result − Run1: Enter String 1: Welcome Enter String 2: TO my World Welcome is greater than TO my World Run 2: Enter String 1: welcome Enter String 2: welcome welcome is same as welcome
[ { "code": null, "e": 1196, "s": 1062, "text": "The C library function int strncmp(const char *str1, const char *str2, size_t n) compares at most the first n bytes of str1 and str2." }, { "code": null, "e": 1239, "s": 1196, "text": "An array of characters is called a string." }, { "code": null, "e": 1289, "s": 1239, "text": "The syntax for declaring an array is as follows −" }, { "code": null, "e": 1313, "s": 1289, "text": "char stringname [size];" }, { "code": null, "e": 1375, "s": 1313, "text": "For example − char string[50]; string of length 50 characters" }, { "code": null, "e": 1409, "s": 1375, "text": "Using single character constant −" }, { "code": null, "e": 1460, "s": 1409, "text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}" }, { "code": null, "e": 1485, "s": 1460, "text": "Using string constants −" }, { "code": null, "e": 1513, "s": 1485, "text": "char string[10] = \"Hello\":;" }, { "code": null, "e": 1611, "s": 1513, "text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’." }, { "code": null, "e": 1682, "s": 1611, "text": "This function is used for comparing first ‘n’ characters of 2 strings." }, { "code": null, "e": 1732, "s": 1682, "text": "The syntax for strncmp() function is as follows −" }, { "code": null, "e": 1763, "s": 1732, "text": "strncmp ( string1, string2, n)" }, { "code": null, "e": 1821, "s": 1763, "text": "char a[10] = \"the\";\nchar b[10] = \"there\"\nstrncmp (a,b,3);" }, { "code": null, "e": 1874, "s": 1821, "text": "The output would be that the Both strings are equal." }, { "code": null, "e": 1986, "s": 1874, "text": "Given below is a C program to compare a specific character between two strings using strncmp library function −" }, { "code": null, "e": 1997, "s": 1986, "text": " Live Demo" }, { "code": null, "e": 2577, "s": 1997, "text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring two strings//\n char string1[25],string2[25];\n int value;\n //Reading string 1 and String 2//\n printf(\"Enter String 1: \");\n gets(string1);\n printf(\"Enter String 2: \");\n gets(string2);\n //Comparing using library function//\n value = strncmp(string1,string2,4);\n //If conditions//\n if(value==0){\n printf(\"%s is same as %s\",string1,string2);\n }\n else if(value>0){\n printf(\"%s is greater than %s\",string1,string2);\n } else {\n printf(\"%s is less than %s\",string1,string2);\n }\n}" }, { "code": null, "e": 2648, "s": 2577, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2824, "s": 2648, "text": "Run1:\nEnter String 1: Welcome\nEnter String 2: TO my World\nWelcome is greater than TO my World\nRun 2:\nEnter String 1: welcome\nEnter String 2: welcome\nwelcome is same as welcome" } ]
Upgrading a Docker Installation of MySQL
Before upgrading the docker installation of MySQL, ensure that the below mentioned steps have been followed − Download a MySQL server docker image. Download a MySQL server docker image. Start a MySQL server instance. Start a MySQL server instance. Connect to MySQL server instance from within the container. Connect to MySQL server instance from within the container. Following are the steps to upgrade a Docker installation of MySQL 5.7 to 8.0 − Stop the MySQL 5.6 server using the below command. Here mysql56 is the name of the container. Stop the MySQL 5.6 server using the below command. Here mysql56 is the name of the container. docker stop mysql56 Download the MySQL 5.7 Server Docker image. Download the MySQL 5.7 Server Docker image. Start a new MySQL 5.7 Docker container with the help of the old server data and configuration. Start a new MySQL 5.7 Docker container with the help of the old server data and configuration. Perform modifications if required. Perform modifications if required. If MySQL community server is present, run the below command − If MySQL community server is present, run the below command − docker run --name=mysql57 \ --mount type=bind,src=/path-on-host-machine/my.cnf,dst=/etc/my.cnf \ --mount type=bind,src=/path-on-host-machine/datadir,dst=/var/lib/mysql \ -d mysql/mysql-server:5.7 If required, adjust mysql/mysql-server to the correct repository name. If required, adjust mysql/mysql-server to the correct repository name. Wait for the server to finish the startup operations. Wait for the server to finish the startup operations. The status of the server can be checked for using the ‘docker ps’ command. The status of the server can be checked for using the ‘docker ps’ command. Run the mysql_upgrade utility in the MySQL 5.7 Server container using the below command − Run the mysql_upgrade utility in the MySQL 5.7 Server container using the below command − docker exec -it mysql57 mysql_upgrade -uroot -p When it prompts, enter the root password for the old MySQL 5.6 Server. When it prompts, enter the root password for the old MySQL 5.6 Server. Finish the upgrade by restarting the MySQL 5.7 Server container using the below command − Finish the upgrade by restarting the MySQL 5.7 Server container using the below command − docker restart mysql57
[ { "code": null, "e": 1172, "s": 1062, "text": "Before upgrading the docker installation of MySQL, ensure that the below mentioned steps have been followed −" }, { "code": null, "e": 1210, "s": 1172, "text": "Download a MySQL server docker image." }, { "code": null, "e": 1248, "s": 1210, "text": "Download a MySQL server docker image." }, { "code": null, "e": 1279, "s": 1248, "text": "Start a MySQL server instance." }, { "code": null, "e": 1310, "s": 1279, "text": "Start a MySQL server instance." }, { "code": null, "e": 1370, "s": 1310, "text": "Connect to MySQL server instance from within the container." }, { "code": null, "e": 1430, "s": 1370, "text": "Connect to MySQL server instance from within the container." }, { "code": null, "e": 1509, "s": 1430, "text": "Following are the steps to upgrade a Docker installation of MySQL 5.7 to 8.0 −" }, { "code": null, "e": 1603, "s": 1509, "text": "Stop the MySQL 5.6 server using the below command. Here mysql56 is the name of the container." }, { "code": null, "e": 1697, "s": 1603, "text": "Stop the MySQL 5.6 server using the below command. Here mysql56 is the name of the container." }, { "code": null, "e": 1717, "s": 1697, "text": "docker stop mysql56" }, { "code": null, "e": 1761, "s": 1717, "text": "Download the MySQL 5.7 Server Docker image." }, { "code": null, "e": 1805, "s": 1761, "text": "Download the MySQL 5.7 Server Docker image." }, { "code": null, "e": 1900, "s": 1805, "text": "Start a new MySQL 5.7 Docker container with the help of the old server data and\nconfiguration." }, { "code": null, "e": 1995, "s": 1900, "text": "Start a new MySQL 5.7 Docker container with the help of the old server data and\nconfiguration." }, { "code": null, "e": 2030, "s": 1995, "text": "Perform modifications if required." }, { "code": null, "e": 2065, "s": 2030, "text": "Perform modifications if required." }, { "code": null, "e": 2127, "s": 2065, "text": "If MySQL community server is present, run the below command −" }, { "code": null, "e": 2189, "s": 2127, "text": "If MySQL community server is present, run the below command −" }, { "code": null, "e": 2385, "s": 2189, "text": "docker run --name=mysql57 \\\n--mount type=bind,src=/path-on-host-machine/my.cnf,dst=/etc/my.cnf \\\n--mount type=bind,src=/path-on-host-machine/datadir,dst=/var/lib/mysql \\\n-d mysql/mysql-server:5.7" }, { "code": null, "e": 2456, "s": 2385, "text": "If required, adjust mysql/mysql-server to the correct repository name." }, { "code": null, "e": 2527, "s": 2456, "text": "If required, adjust mysql/mysql-server to the correct repository name." }, { "code": null, "e": 2581, "s": 2527, "text": "Wait for the server to finish the startup operations." }, { "code": null, "e": 2635, "s": 2581, "text": "Wait for the server to finish the startup operations." }, { "code": null, "e": 2710, "s": 2635, "text": "The status of the server can be checked for using the ‘docker ps’ command." }, { "code": null, "e": 2785, "s": 2710, "text": "The status of the server can be checked for using the ‘docker ps’ command." }, { "code": null, "e": 2875, "s": 2785, "text": "Run the mysql_upgrade utility in the MySQL 5.7 Server container using the below command −" }, { "code": null, "e": 2965, "s": 2875, "text": "Run the mysql_upgrade utility in the MySQL 5.7 Server container using the below command −" }, { "code": null, "e": 3013, "s": 2965, "text": "docker exec -it mysql57 mysql_upgrade -uroot -p" }, { "code": null, "e": 3084, "s": 3013, "text": "When it prompts, enter the root password for the old MySQL 5.6 Server." }, { "code": null, "e": 3155, "s": 3084, "text": "When it prompts, enter the root password for the old MySQL 5.6 Server." }, { "code": null, "e": 3245, "s": 3155, "text": "Finish the upgrade by restarting the MySQL 5.7 Server container using the below command −" }, { "code": null, "e": 3335, "s": 3245, "text": "Finish the upgrade by restarting the MySQL 5.7 Server container using the below command −" }, { "code": null, "e": 3358, "s": 3335, "text": "docker restart mysql57" } ]
- Unix, Linux Command
If the -key option is not used it will generate a new RSA private key using information specified in the configuration file. /DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe If -multi-rdn is not used then the UID value is 123456+CN=John Doe. More precisely the Attributes in a PKCS#10 certificate request are defined as a SET OF Attribute. They are not OPTIONAL so if no attributes are present then they should be encoded as an empty SET OF. The invalid form does not include the empty SET OF whereas the correct form does. It should be noted that very few CAs still require the use of this option. The options available are described in detail below. It can be set to several values default which is also the default option uses PrintableStrings, T61Strings and BMPStrings if the pkix value is used then only PrintableStrings and BMPStrings will be used. This follows the PKIX recommendation in RFC2459. If the utf8only option is used then only UTF8Strings will be used: this is the PKIX recommendation in RFC2459 after 2003. Finally the nombstr option just uses PrintableStrings and T61Strings: certain software has problems with BMPStrings and UTF8Strings: in particular Netscape. CN=My Name OU=My Organization emailAddress=someone@somewhere.org This allows external programs (e.g. GUI based) to generate a template file with all the field names and values and just pass it to req. An example of this kind of configuration file is contained in the EXAMPLES section. Alternatively if the prompt option is absent or not set to no then the file contains field prompting information. It consists of lines of the form: fieldName="prompt" fieldName_default="default field value" fieldName_min= 2 fieldName_max= 4 fieldName is the field name being used, for example commonName (or CN). The prompt string is used to ask the user to enter the relevant details. If the user enters nothing then the default value is used if no default value is present then the field is omitted. A field can still be omitted if a default value is present if the user just enters the ’.’ character. The number of characters entered must be between the fieldName_min and fieldName_max limits: there may be additional restrictions based on the field being used (for example countryName can only ever be two characters long and must fit in a PrintableString). Some fields (such as organizationName) can be used more than once in a DN. This presents a problem because configuration files will not recognize the same name occurring twice. To avoid this problem if the fieldName contains some characters followed by a full stop they will be ignored. So for example a second organizationName can be input by calling it 1.organizationName. The actual permitted field names are any object identifier short or long names. These are compiled into OpenSSL and include the usual values such as commonName, countryName, localityName, organizationName, organizationUnitName, stateOrProvinceName. Additionally emailAddress is include as well as name, surname, givenName initials and dnQualifier. Additional object identifiers can be defined with the oid_file or oid_section options in the configuration file. Any additional fields will be treated as though they were a DirectoryString. openssl req -in req.pem -text -verify -noout Create a private key and then generate a certificate request from it: openssl genrsa -out key.pem 1024 openssl req -new -key key.pem -out req.pem The same but just using req: openssl req -newkey rsa:1024 -keyout key.pem -out req.pem Generate a self signed root certificate: openssl req -x509 -newkey rsa:1024 -keyout key.pem -out req.pem Example of a file pointed to by the oid_file option: 1.2.3.4 shortName A longer Name 1.2.3.6 otherName Other longer Name Example of a section pointed to by oid_section making use of variable expansion: testoid1=1.2.3.5 testoid2=${testoid1}.6 Sample configuration file prompting for field values: [ req ] default_bits = 1024 default_keyfile = privkey.pem distinguished_name = req_distinguished_name attributes = req_attributes x509_extensions = v3_ca dirstring_type = nobmp [ req_distinguished_name ] countryName = Country Name (2 letter code) countryName_default = AU countryName_min = 2 countryName_max = 2 localityName = Locality Name (eg, city) organizationalUnitName = Organizational Unit Name (eg, section) commonName = Common Name (eg, YOUR name) commonName_max = 64 emailAddress = Email Address emailAddress_max = 40 [ req_attributes ] challengePassword = A challenge password challengePassword_min = 4 challengePassword_max = 20 [ v3_ca ] subjectKeyIdentifier=hash authorityKeyIdentifier=keyid:always,issuer:always basicConstraints = CA:true Sample configuration containing all field values: RANDFILE = $ENV::HOME/.rnd [ req ] default_bits = 1024 default_keyfile = keyfile.pem distinguished_name = req_distinguished_name attributes = req_attributes prompt = no output_password = mypass [ req_distinguished_name ] C = GB ST = Test State or Province L = Test Locality O = Organization Name OU = Organizational Unit Name CN = Common Name emailAddress = test@email.address [ req_attributes ] challengePassword = A challenge password -----BEGIN CERTIFICATE REQUEST----- -----END CERTIFICATE REQUEST----- some software (some versions of Netscape certificate server) instead needs: -----BEGIN NEW CERTIFICATE REQUEST----- -----END NEW CERTIFICATE REQUEST----- which is produced with the -newhdr option but is otherwise compatible. Either form is accepted transparently on input. The certificate requests generated by Xenroll with MSIE have extensions added. It includes the keyUsage extension which determines the type of key (signature only or general purpose) and any additional OIDs entered by the script in an extendedKeyUsage extension. Using configuration from /some/path/openssl.cnf Unable to load config info This is followed some time later by... unable to find ’distinguished_name’ in config problems making Certificate Request The first error message is the clue: it can’t find the configuration file! Certain operations (like examining a certificate request) don’t need a configuration file so its use isn’t enforced. Generation of certificates or requests however does need a configuration file. This could be regarded as a bug. Another puzzling message is this: Attributes: a0:00 this is displayed when no attributes are present and the request includes the correct empty SET OF structure (the DER encoding of which is 0xa0 0x00). If you just see: Attributes: then the SET OF is missing and the encoding is technically invalid (but it is tolerated). See the description of the command line option -asn1-kludge for more information. As a consequence of the T61String handling the only correct way to represent accented characters in OpenSSL is to use a BMPString: unfortunately Netscape currently chokes on these. If you have to use accented characters with Netscape and MSIE then you currently need to use the invalid T61String form. The current prompting is not very friendly. It doesn’t allow you to confirm what you’ve just entered. Other things like extensions in certificate requests are statically defined in the configuration file. Some of these: like an email address in subjectAltName should be input by the user. Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 10705, "s": 10577, "text": "\n\nIf the -key option is not used it will generate a new RSA private\nkey using information specified in the configuration file.\n" }, { "code": null, "e": 10759, "s": 10705, "text": "\n\n/DC=org/DC=OpenSSL/DC=users/UID=123456+CN=John Doe\n" }, { "code": null, "e": 10830, "s": 10759, "text": "\n\nIf -multi-rdn is not used then the UID value is 123456+CN=John Doe.\n" }, { "code": null, "e": 11115, "s": 10830, "text": "\n\nMore precisely the Attributes in a PKCS#10 certificate request\nare defined as a SET OF Attribute. They are not OPTIONAL so\nif no attributes are present then they should be encoded as an\nempty SET OF. The invalid form does not include the empty\nSET OF whereas the correct form does.\n" }, { "code": null, "e": 11193, "s": 11115, "text": "\n\nIt should be noted that very few CAs still require the use of this option.\n" }, { "code": null, "e": 11248, "s": 11193, "text": "\nThe options available are described in detail below.\n" }, { "code": null, "e": 11783, "s": 11248, "text": "\n\nIt can be set to several values default which is also the default\noption uses PrintableStrings, T61Strings and BMPStrings if the\npkix value is used then only PrintableStrings and BMPStrings will\nbe used. This follows the PKIX recommendation in RFC2459. If the\nutf8only option is used then only UTF8Strings will be used: this\nis the PKIX recommendation in RFC2459 after 2003. Finally the nombstr\noption just uses PrintableStrings and T61Strings: certain software has\nproblems with BMPStrings and UTF8Strings: in particular Netscape.\n" }, { "code": null, "e": 11855, "s": 11785, "text": "\n CN=My Name\n OU=My Organization\n emailAddress=someone@somewhere.org\n" }, { "code": null, "e": 12077, "s": 11855, "text": "\nThis allows external programs (e.g. GUI based) to generate a template file\nwith all the field names and values and just pass it to req. An example\nof this kind of configuration file is contained in the EXAMPLES section.\n" }, { "code": null, "e": 12227, "s": 12077, "text": "\nAlternatively if the prompt option is absent or not set to no then the\nfile contains field prompting information. It consists of lines of the form:\n" }, { "code": null, "e": 12328, "s": 12229, "text": "\n fieldName=\"prompt\"\n fieldName_default=\"default field value\"\n fieldName_min= 2\n fieldName_max= 4\n" }, { "code": null, "e": 12693, "s": 12328, "text": "\nfieldName is the field name being used, for example commonName (or CN).\nThe prompt string is used to ask the user to enter the relevant\ndetails. If the user enters nothing then the default value is used if no\ndefault value is present then the field is omitted. A field can\nstill be omitted if a default value is present if the user just\nenters the ’.’ character.\n" }, { "code": null, "e": 12953, "s": 12693, "text": "\nThe number of characters entered must be between the fieldName_min and\nfieldName_max limits: there may be additional restrictions based\non the field being used (for example countryName can only ever be\ntwo characters long and must fit in a PrintableString).\n" }, { "code": null, "e": 13330, "s": 12953, "text": "\nSome fields (such as organizationName) can be used more than once\nin a DN. This presents a problem because configuration files will\nnot recognize the same name occurring twice. To avoid this problem\nif the fieldName contains some characters followed by a full stop\nthey will be ignored. So for example a second organizationName can\nbe input by calling it 1.organizationName.\n" }, { "code": null, "e": 13680, "s": 13330, "text": "\nThe actual permitted field names are any object identifier short or\nlong names. These are compiled into OpenSSL and include the usual\nvalues such as commonName, countryName, localityName, organizationName,\norganizationUnitName, stateOrProvinceName. Additionally emailAddress\nis include as well as name, surname, givenName initials and dnQualifier.\n" }, { "code": null, "e": 13872, "s": 13680, "text": "\nAdditional object identifiers can be defined with the oid_file or\noid_section options in the configuration file. Any additional fields\nwill be treated as though they were a DirectoryString.\n" }, { "code": null, "e": 13922, "s": 13874, "text": "\n openssl req -in req.pem -text -verify -noout\n" }, { "code": null, "e": 13994, "s": 13922, "text": "\nCreate a private key and then generate a certificate request from it:\n" }, { "code": null, "e": 14076, "s": 13996, "text": "\n openssl genrsa -out key.pem 1024\n openssl req -new -key key.pem -out req.pem\n" }, { "code": null, "e": 14107, "s": 14076, "text": "\nThe same but just using req:\n" }, { "code": null, "e": 14170, "s": 14109, "text": "\n openssl req -newkey rsa:1024 -keyout key.pem -out req.pem\n" }, { "code": null, "e": 14213, "s": 14170, "text": "\nGenerate a self signed root certificate:\n" }, { "code": null, "e": 14282, "s": 14215, "text": "\n openssl req -x509 -newkey rsa:1024 -keyout key.pem -out req.pem\n" }, { "code": null, "e": 14337, "s": 14282, "text": "\nExample of a file pointed to by the oid_file option:\n" }, { "code": null, "e": 14437, "s": 14339, "text": "\n 1.2.3.4 shortName A longer Name\n 1.2.3.6 otherName Other longer Name\n" }, { "code": null, "e": 14520, "s": 14437, "text": "\nExample of a section pointed to by oid_section making use of variable\nexpansion:\n" }, { "code": null, "e": 14566, "s": 14522, "text": "\n testoid1=1.2.3.5\n testoid2=${testoid1}.6\n" }, { "code": null, "e": 14622, "s": 14566, "text": "\nSample configuration file prompting for field values:\n" }, { "code": null, "e": 14826, "s": 14624, "text": "\n [ req ]\n default_bits = 1024\n default_keyfile = privkey.pem\n distinguished_name = req_distinguished_name\n attributes = req_attributes\n x509_extensions = v3_ca\n" }, { "code": null, "e": 14854, "s": 14828, "text": "\n dirstring_type = nobmp\n" }, { "code": null, "e": 15058, "s": 14856, "text": "\n [ req_distinguished_name ]\n countryName = Country Name (2 letter code)\n countryName_default = AU\n countryName_min = 2\n countryName_max = 2\n" }, { "code": null, "e": 15121, "s": 15060, "text": "\n localityName = Locality Name (eg, city)\n" }, { "code": null, "e": 15198, "s": 15123, "text": "\n organizationalUnitName = Organizational Unit Name (eg, section)\n" }, { "code": null, "e": 15301, "s": 15200, "text": "\n commonName = Common Name (eg, YOUR name)\n commonName_max = 64\n" }, { "code": null, "e": 15390, "s": 15303, "text": "\n emailAddress = Email Address\n emailAddress_max = 40\n" }, { "code": null, "e": 15542, "s": 15392, "text": "\n [ req_attributes ]\n challengePassword = A challenge password\n challengePassword_min = 4\n challengePassword_max = 20\n" }, { "code": null, "e": 15557, "s": 15544, "text": "\n [ v3_ca ]\n" }, { "code": null, "e": 15667, "s": 15559, "text": "\n subjectKeyIdentifier=hash\n authorityKeyIdentifier=keyid:always,issuer:always\n basicConstraints = CA:true\n" }, { "code": null, "e": 15719, "s": 15667, "text": "\nSample configuration containing all field values:\n" }, { "code": null, "e": 15765, "s": 15721, "text": "\n RANDFILE = $ENV::HOME/.rnd\n" }, { "code": null, "e": 15999, "s": 15767, "text": "\n [ req ]\n default_bits = 1024\n default_keyfile = keyfile.pem\n distinguished_name = req_distinguished_name\n attributes = req_attributes\n prompt = no\n output_password = mypass\n" }, { "code": null, "e": 16327, "s": 16001, "text": "\n [ req_distinguished_name ]\n C = GB\n ST = Test State or Province\n L = Test Locality\n O = Organization Name\n OU = Organizational Unit Name\n CN = Common Name\n emailAddress = test@email.address\n" }, { "code": null, "e": 16406, "s": 16329, "text": "\n [ req_attributes ]\n challengePassword = A challenge password\n" }, { "code": null, "e": 16482, "s": 16408, "text": "\n -----BEGIN CERTIFICATE REQUEST-----\n -----END CERTIFICATE REQUEST-----\n" }, { "code": null, "e": 16560, "s": 16482, "text": "\nsome software (some versions of Netscape certificate server) instead needs:\n" }, { "code": null, "e": 16644, "s": 16562, "text": "\n -----BEGIN NEW CERTIFICATE REQUEST-----\n -----END NEW CERTIFICATE REQUEST-----\n" }, { "code": null, "e": 16765, "s": 16644, "text": "\nwhich is produced with the -newhdr option but is otherwise compatible.\nEither form is accepted transparently on input.\n" }, { "code": null, "e": 17030, "s": 16765, "text": "\nThe certificate requests generated by Xenroll with MSIE have extensions\nadded. It includes the keyUsage extension which determines the type of\nkey (signature only or general purpose) and any additional OIDs entered\nby the script in an extendedKeyUsage extension.\n" }, { "code": null, "e": 17125, "s": 17032, "text": "\n Using configuration from /some/path/openssl.cnf\n Unable to load config info\n" }, { "code": null, "e": 17166, "s": 17125, "text": "\nThis is followed some time later by...\n" }, { "code": null, "e": 17268, "s": 17168, "text": "\n unable to find ’distinguished_name’ in config\n problems making Certificate Request\n" }, { "code": null, "e": 17574, "s": 17268, "text": "\nThe first error message is the clue: it can’t find the configuration\nfile! Certain operations (like examining a certificate request) don’t\nneed a configuration file so its use isn’t enforced. Generation of\ncertificates or requests however does need a configuration file. This\ncould be regarded as a bug.\n" }, { "code": null, "e": 17610, "s": 17574, "text": "\nAnother puzzling message is this:\n" }, { "code": null, "e": 17652, "s": 17612, "text": "\n Attributes:\n a0:00\n" }, { "code": null, "e": 17822, "s": 17652, "text": "\nthis is displayed when no attributes are present and the request includes\nthe correct empty SET OF structure (the DER encoding of which is 0xa0\n0x00). If you just see:\n" }, { "code": null, "e": 17846, "s": 17824, "text": "\n Attributes:\n" }, { "code": null, "e": 18020, "s": 17846, "text": "\nthen the SET OF is missing and the encoding is technically invalid (but\nit is tolerated). See the description of the command line option -asn1-kludge\nfor more information.\n" }, { "code": null, "e": 18324, "s": 18020, "text": "\nAs a consequence of the T61String handling the only correct way to represent\naccented characters in OpenSSL is to use a BMPString: unfortunately Netscape\ncurrently chokes on these. If you have to use accented characters with Netscape\nand MSIE then you currently need to use the invalid T61String form.\n" }, { "code": null, "e": 18615, "s": 18324, "text": "\nThe current prompting is not very friendly. It doesn’t allow you to confirm what\nyou’ve just entered. Other things like extensions in certificate requests are\nstatically defined in the configuration file. Some of these: like an email\naddress in subjectAltName should be input by the user.\n" }, { "code": null, "e": 18632, "s": 18615, "text": "\nAdvertisements\n" }, { "code": null, "e": 18667, "s": 18632, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 18695, "s": 18667, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 18729, "s": 18695, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 18746, "s": 18729, "text": " Frahaan Hussain" }, { "code": null, "e": 18779, "s": 18746, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 18790, "s": 18779, "text": " Pradeep D" }, { "code": null, "e": 18825, "s": 18790, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 18841, "s": 18825, "text": " Musab Zayadneh" }, { "code": null, "e": 18874, "s": 18841, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 18886, "s": 18874, "text": " GUHARAJANM" }, { "code": null, "e": 18918, "s": 18886, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 18926, "s": 18918, "text": " Uplatz" }, { "code": null, "e": 18933, "s": 18926, "text": " Print" }, { "code": null, "e": 18944, "s": 18933, "text": " Add Notes" } ]
Are you still using Pandas for big data? | by Roman Orac | Towards Data Science
Pandas is one of the best tools when it comes to Exploratory Data Analysis. But this doesn't mean that it is the best tool available for every task — like big data processing. I’ve spent so much time waiting for pandas to read a bunch of files or to aggregate them and calculate features. Recently, I took the time and found a better tool, which made me update my data processing pipeline. I use this tool for heavy data processing — like reading multiple files with 10 gigs of data, apply filters to them and do aggregations. When I am done with heavy processing I save the result to a smaller “pandas friendly” CSV file and continue with Exploratory Data Analysis in pandas. Here are few links that might interest you: - Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course] Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything. Dask provides advanced parallelism for analytics, enabling performance at scale for the tools you love. This includes numpy, pandas and sklearn. It is open-source and freely available. It uses existing Python APIs and data structures to make it easy to switch between Dask-powered equivalents. Dask makes simple things easy and complex things possible I could go on and on describing Dask, because it has so many features, but instead, let's look at a practical example. In my work, I usually get a bunch of files that I need to analyze. Let’s simulate my workday and create 10 files with 100K entries (each file has 196 MB). from sklearn.datasets import make_classificationimport pandas as pdfor i in range(1, 11): print('Generating trainset %d' % i) x, y = make_classification(n_samples=100_000, n_features=100) df = pd.DataFrame(data=x) df['y'] = y df.to_csv('trainset_%d.csv' % i, index=False) Now, let’s read those files with pandas and measure time. Pandas doesn’t have native glob support so we need to read files in a loop. %%timeimport globdf_list = []for filename in glob.glob('trainset_*.csv'): df_ = pd.read_csv(filename) df_list.append(df_)df = pd.concat(df_list)df.shape It took pandas 16 seconds to read files. CPU times: user 14.6 s, sys: 1.29 s, total: 15.9 sWall time: 16 s Now, imagine if those files would be 100 times bigger — you couldn’t even read them with pandas. Dask can process data that doesn’t fit into memory by breaking it into blocks and specifying task chains. Let’s measure how long Dask needs to load those files. import dask.dataframe as dd%%timedf = dd.read_csv('trainset_*.csv')CPU times: user 154 ms, sys: 58.6 ms, total: 212 msWall time: 212 ms Dask needed 154 ms! How is that even possible? Well, it is not. Dask has delayed execution paradigm. It only calculates things when it needs them. We define the execution graph so Dask can then optimize the execution of the tasks. Let’s repeat the experiment — also notice that Dask’s read_csv function takes glob natively. %%timedf = dd.read_csv('trainset_*.csv').compute()CPU times: user 39.5 s, sys: 5.3 s, total: 44.8 sWall time: 8.21 s The compute function forces Dask to return the result. Dask read files twice as fast than pandas. Dask natively scales Python Does Dask use all of the cores you paid for? Let’s compare CPU usage between pandas and Dask when reading files — the code is the same as above. In the screen recordings above the difference in multiprocessing is obvious with pandas and Dask when reading files. Dask’s DataFrame is composed of multiple pandas DataFrames, which are split by index. When we execute read_csv with Dask, multiple processes read a single file. We can even visualize the execution graph. exec_graph = dd.read_csv('trainset_*.csv')exec_graph.visualize() You might be thinking if Dask is so great, why not ditch pandas all together. Well, it is not that simple. Only certain functions from pandas are ported to Dask. Some of them are hard to parallelize, like sorting values and setting indexes on unsorted columns. Dask is not a silver bullet — usage of Dask is recommended only for datasets that don’t fit in the main memory. As Dask is built on top of pandas, operations that were slow in pandas, stay slow in Dask. Like I mentioned before, Dask is a useful tool in the data pipeline process, but it doesn’t replace other libraries. Dask is recommended only for datasets that don’t fit in the main memory To install Dask simply run: python -m pip install "dask[complete]" This will install the whole Dask library. I’ve only touched the surface of Dask library in this blog post. If you would like to dive deeper check amazing Dask tutorials and Dask’s DataFrame documentation. Interested in which DataFrame functions are supported in Dask? Check DataFrame API. Download the Jupyter Notebook to follow examples. Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.
[ { "code": null, "e": 461, "s": 172, "text": "Pandas is one of the best tools when it comes to Exploratory Data Analysis. But this doesn't mean that it is the best tool available for every task — like big data processing. I’ve spent so much time waiting for pandas to read a bunch of files or to aggregate them and calculate features." }, { "code": null, "e": 849, "s": 461, "text": "Recently, I took the time and found a better tool, which made me update my data processing pipeline. I use this tool for heavy data processing — like reading multiple files with 10 gigs of data, apply filters to them and do aggregations. When I am done with heavy processing I save the result to a smaller “pandas friendly” CSV file and continue with Exploratory Data Analysis in pandas." }, { "code": null, "e": 893, "s": 849, "text": "Here are few links that might interest you:" }, { "code": null, "e": 1071, "s": 893, "text": "- Complete your Python analyses 10x faster with Mito [Product]- Free skill tests for Data Scientists & ML Engineers [Test]- All New Self-Driving Car Engineer Nanodegree [Course]" }, { "code": null, "e": 1242, "s": 1071, "text": "Would you like to read more such articles? If so, you can support me by clicking on any links above. Some of them are affiliate links, but you don’t need to buy anything." }, { "code": null, "e": 1536, "s": 1242, "text": "Dask provides advanced parallelism for analytics, enabling performance at scale for the tools you love. This includes numpy, pandas and sklearn. It is open-source and freely available. It uses existing Python APIs and data structures to make it easy to switch between Dask-powered equivalents." }, { "code": null, "e": 1594, "s": 1536, "text": "Dask makes simple things easy and complex things possible" }, { "code": null, "e": 1868, "s": 1594, "text": "I could go on and on describing Dask, because it has so many features, but instead, let's look at a practical example. In my work, I usually get a bunch of files that I need to analyze. Let’s simulate my workday and create 10 files with 100K entries (each file has 196 MB)." }, { "code": null, "e": 2155, "s": 1868, "text": "from sklearn.datasets import make_classificationimport pandas as pdfor i in range(1, 11): print('Generating trainset %d' % i) x, y = make_classification(n_samples=100_000, n_features=100) df = pd.DataFrame(data=x) df['y'] = y df.to_csv('trainset_%d.csv' % i, index=False)" }, { "code": null, "e": 2289, "s": 2155, "text": "Now, let’s read those files with pandas and measure time. Pandas doesn’t have native glob support so we need to read files in a loop." }, { "code": null, "e": 2448, "s": 2289, "text": "%%timeimport globdf_list = []for filename in glob.glob('trainset_*.csv'): df_ = pd.read_csv(filename) df_list.append(df_)df = pd.concat(df_list)df.shape" }, { "code": null, "e": 2489, "s": 2448, "text": "It took pandas 16 seconds to read files." }, { "code": null, "e": 2555, "s": 2489, "text": "CPU times: user 14.6 s, sys: 1.29 s, total: 15.9 sWall time: 16 s" }, { "code": null, "e": 2652, "s": 2555, "text": "Now, imagine if those files would be 100 times bigger — you couldn’t even read them with pandas." }, { "code": null, "e": 2813, "s": 2652, "text": "Dask can process data that doesn’t fit into memory by breaking it into blocks and specifying task chains. Let’s measure how long Dask needs to load those files." }, { "code": null, "e": 2949, "s": 2813, "text": "import dask.dataframe as dd%%timedf = dd.read_csv('trainset_*.csv')CPU times: user 154 ms, sys: 58.6 ms, total: 212 msWall time: 212 ms" }, { "code": null, "e": 3273, "s": 2949, "text": "Dask needed 154 ms! How is that even possible? Well, it is not. Dask has delayed execution paradigm. It only calculates things when it needs them. We define the execution graph so Dask can then optimize the execution of the tasks. Let’s repeat the experiment — also notice that Dask’s read_csv function takes glob natively." }, { "code": null, "e": 3390, "s": 3273, "text": "%%timedf = dd.read_csv('trainset_*.csv').compute()CPU times: user 39.5 s, sys: 5.3 s, total: 44.8 sWall time: 8.21 s" }, { "code": null, "e": 3488, "s": 3390, "text": "The compute function forces Dask to return the result. Dask read files twice as fast than pandas." }, { "code": null, "e": 3516, "s": 3488, "text": "Dask natively scales Python" }, { "code": null, "e": 3661, "s": 3516, "text": "Does Dask use all of the cores you paid for? Let’s compare CPU usage between pandas and Dask when reading files — the code is the same as above." }, { "code": null, "e": 3778, "s": 3661, "text": "In the screen recordings above the difference in multiprocessing is obvious with pandas and Dask when reading files." }, { "code": null, "e": 3939, "s": 3778, "text": "Dask’s DataFrame is composed of multiple pandas DataFrames, which are split by index. When we execute read_csv with Dask, multiple processes read a single file." }, { "code": null, "e": 3982, "s": 3939, "text": "We can even visualize the execution graph." }, { "code": null, "e": 4047, "s": 3982, "text": "exec_graph = dd.read_csv('trainset_*.csv')exec_graph.visualize()" }, { "code": null, "e": 4628, "s": 4047, "text": "You might be thinking if Dask is so great, why not ditch pandas all together. Well, it is not that simple. Only certain functions from pandas are ported to Dask. Some of them are hard to parallelize, like sorting values and setting indexes on unsorted columns. Dask is not a silver bullet — usage of Dask is recommended only for datasets that don’t fit in the main memory. As Dask is built on top of pandas, operations that were slow in pandas, stay slow in Dask. Like I mentioned before, Dask is a useful tool in the data pipeline process, but it doesn’t replace other libraries." }, { "code": null, "e": 4700, "s": 4628, "text": "Dask is recommended only for datasets that don’t fit in the main memory" }, { "code": null, "e": 4728, "s": 4700, "text": "To install Dask simply run:" }, { "code": null, "e": 4767, "s": 4728, "text": "python -m pip install \"dask[complete]\"" }, { "code": null, "e": 4809, "s": 4767, "text": "This will install the whole Dask library." }, { "code": null, "e": 5056, "s": 4809, "text": "I’ve only touched the surface of Dask library in this blog post. If you would like to dive deeper check amazing Dask tutorials and Dask’s DataFrame documentation. Interested in which DataFrame functions are supported in Dask? Check DataFrame API." }, { "code": null, "e": 5106, "s": 5056, "text": "Download the Jupyter Notebook to follow examples." } ]
What is Default access level in Java?
The default access level is available when no access level is specified. All the classes, data members, methods etc. which have the default access level can only be accessed inside the same package. A program that demonstrates the default access level in Java is given as follows: Live Demo class Employee { int empno; String name; void insert(int e, String n) { empno = e; name = n; } void display() { System.out.println("Employee Number: " + empno); System.out.println("Name: " + name); } } public class Demo { public static void main(String[] args) { Employee emp = new Employee(); emp.insert(105, "James Nortan"); emp.display(); } } Employee Number: 105 Name: James Nortan Now let us understand the above program. The Employee class is created with data members empno, name and member functions insert() and display(). The Employee class and the data members empno, name have the default access control. A code snippet which demonstrates this is as follows: class Employee { int empno; String name; void insert(int e, String n) { empno = e; name = n; } void display() { System.out.println("Employee Number: " + empno); System.out.println("Name: " + name); } } In the main() method, an object emp of class Employee is created. Then insert() method is called with parameters 105 and “James Norton”. Finally the display() method is called. A code snippet which demonstrates this is as follows: public class Demo { public static void main(String[] args) { Employee emp = new Employee(); emp.insert(105, "James Nortan"); emp.display(); } }
[ { "code": null, "e": 1261, "s": 1062, "text": "The default access level is available when no access level is specified. All the classes, data members, methods etc. which have the default access level can only be accessed inside the same package." }, { "code": null, "e": 1343, "s": 1261, "text": "A program that demonstrates the default access level in Java is given as follows:" }, { "code": null, "e": 1354, "s": 1343, "text": " Live Demo" }, { "code": null, "e": 1766, "s": 1354, "text": "class Employee {\n int empno;\n String name;\n void insert(int e, String n) {\n empno = e;\n name = n;\n }\n void display() {\n System.out.println(\"Employee Number: \" + empno);\n System.out.println(\"Name: \" + name);\n }\n}\npublic class Demo {\n public static void main(String[] args) {\n Employee emp = new Employee();\n emp.insert(105, \"James Nortan\");\n emp.display();\n }\n}" }, { "code": null, "e": 1806, "s": 1766, "text": "Employee Number: 105\nName: James Nortan" }, { "code": null, "e": 1847, "s": 1806, "text": "Now let us understand the above program." }, { "code": null, "e": 2091, "s": 1847, "text": "The Employee class is created with data members empno, name and member functions insert() and display(). The Employee class and the data members empno, name have the default access control. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2335, "s": 2091, "text": "class Employee {\n int empno;\n String name;\n void insert(int e, String n) {\n empno = e;\n name = n;\n }\n void display() {\n System.out.println(\"Employee Number: \" + empno);\n System.out.println(\"Name: \" + name);\n }\n}" }, { "code": null, "e": 2566, "s": 2335, "text": "In the main() method, an object emp of class Employee is created. Then insert() method is called with parameters 105 and “James Norton”. Finally the display() method is called. A code snippet which demonstrates this is as follows:" }, { "code": null, "e": 2734, "s": 2566, "text": "public class Demo {\n public static void main(String[] args) {\n Employee emp = new Employee();\n emp.insert(105, \"James Nortan\");\n emp.display();\n }\n}" } ]
EasyUI React Droppable Component - GeeksforGeeks
30 Sep, 2021 In this article, we will learn how to design a draggable widget using jQuery EasyUI. EasyUI is an HTML5 framework for using user interface components based on jQuery, React, Angular, and Vue technologies. It helps in building features for interactive web and mobile applications saving a lot of time for developers. The component creates a droppable area from the markup or selector where we can drop the draggable elements. Droppable Props: scope: This prop is used for dropping scopes. disabled: This prop is used to stop resizing the droppable area. Droppable Events: onDragEnter: The assigned event fires when the draggable object is dragged enter. onDragOver: The assigned event fires when the draggable object is dragged over. onDragLeave: The assigned event fires when the draggable object is dragged leave. onDrop: The assigned event fires when the draggable object is dropped over. Creating React Application and Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, import the EasyUI modules using the following syntax. import { Droppable } from "rc-easyui"; Project Structure: It will look like this. App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react';import { Draggable, Droppable } from 'rc-easyui'; class App extends React.Component { render() { return ( <div> <h2>EasyUI React Draggable Component</h2> <Draggable> <div style={{ width: '100px', height: '25', border: '2px solid #ccc', background: 'green' }}> <p style={{ textAlign: 'center', fontsize: '24px' }}> Geeksforgeeks </p> </div> </Draggable> <Droppable onDragEnter={() => this.setState({ isover: true })} onDragLeave={() => this.setState({ isover: false })} onDrop={() => this.setState({ dropped: true })} > <div> <p style={{ textAlign: 'center' }}>Drop here</p> </div> </Droppable> </div> ); }} export default App; Step to run the application: Run the application using the following command. npm start Output: EasyUI ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments ReactJS useNavigate() Hook How to set background images in ReactJS ? How to navigate on path by button click in react router ? How to create a table in ReactJS ? How to parse JSON Data into React Table Component ? Installation of Node.js on Linux Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24708, "s": 24680, "text": "\n30 Sep, 2021" }, { "code": null, "e": 25133, "s": 24708, "text": "In this article, we will learn how to design a draggable widget using jQuery EasyUI. EasyUI is an HTML5 framework for using user interface components based on jQuery, React, Angular, and Vue technologies. It helps in building features for interactive web and mobile applications saving a lot of time for developers. The component creates a droppable area from the markup or selector where we can drop the draggable elements." }, { "code": null, "e": 25150, "s": 25133, "text": "Droppable Props:" }, { "code": null, "e": 25196, "s": 25150, "text": "scope: This prop is used for dropping scopes." }, { "code": null, "e": 25261, "s": 25196, "text": "disabled: This prop is used to stop resizing the droppable area." }, { "code": null, "e": 25279, "s": 25261, "text": "Droppable Events:" }, { "code": null, "e": 25361, "s": 25279, "text": "onDragEnter: The assigned event fires when the draggable object is dragged enter." }, { "code": null, "e": 25441, "s": 25361, "text": "onDragOver: The assigned event fires when the draggable object is dragged over." }, { "code": null, "e": 25523, "s": 25441, "text": "onDragLeave: The assigned event fires when the draggable object is dragged leave." }, { "code": null, "e": 25599, "s": 25523, "text": "onDrop: The assigned event fires when the draggable object is dropped over." }, { "code": null, "e": 25649, "s": 25599, "text": "Creating React Application and Installing Module:" }, { "code": null, "e": 25713, "s": 25649, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 25745, "s": 25713, "text": "npx create-react-app foldername" }, { "code": null, "e": 25845, "s": 25745, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 25859, "s": 25845, "text": "cd foldername" }, { "code": null, "e": 25961, "s": 25859, "text": "Step 3: After creating the ReactJS application, import the EasyUI modules using the following syntax." }, { "code": null, "e": 26000, "s": 25961, "text": "import { Droppable } from \"rc-easyui\";" }, { "code": null, "e": 26043, "s": 26000, "text": "Project Structure: It will look like this." }, { "code": null, "e": 26172, "s": 26043, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26183, "s": 26172, "text": "Javascript" }, { "code": "import React from 'react';import { Draggable, Droppable } from 'rc-easyui'; class App extends React.Component { render() { return ( <div> <h2>EasyUI React Draggable Component</h2> <Draggable> <div style={{ width: '100px', height: '25', border: '2px solid #ccc', background: 'green' }}> <p style={{ textAlign: 'center', fontsize: '24px' }}> Geeksforgeeks </p> </div> </Draggable> <Droppable onDragEnter={() => this.setState({ isover: true })} onDragLeave={() => this.setState({ isover: false })} onDrop={() => this.setState({ dropped: true })} > <div> <p style={{ textAlign: 'center' }}>Drop here</p> </div> </Droppable> </div> ); }} export default App;", "e": 27127, "s": 26183, "text": null }, { "code": null, "e": 27205, "s": 27127, "text": "Step to run the application: Run the application using the following command." }, { "code": null, "e": 27215, "s": 27205, "text": "npm start" }, { "code": null, "e": 27223, "s": 27215, "text": "Output:" }, { "code": null, "e": 27230, "s": 27223, "text": "EasyUI" }, { "code": null, "e": 27238, "s": 27230, "text": "ReactJS" }, { "code": null, "e": 27255, "s": 27238, "text": "Web Technologies" }, { "code": null, "e": 27353, "s": 27255, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27362, "s": 27353, "text": "Comments" }, { "code": null, "e": 27375, "s": 27362, "text": "Old Comments" }, { "code": null, "e": 27402, "s": 27375, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 27444, "s": 27402, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 27502, "s": 27444, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 27537, "s": 27502, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 27589, "s": 27537, "text": "How to parse JSON Data into React Table Component ?" }, { "code": null, "e": 27622, "s": 27589, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27664, "s": 27622, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27726, "s": 27664, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27776, "s": 27726, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
An Overview of Python’s Datatable package | by Parul Pandey | Towards Data Science
“There were 5 Exabytes of information created between the dawn of civilization through 2003, but that much information is now created every 2 days”:Eric Schmidt If you are an R user, chances are that you have already been using the data.table package. Data.table is an extension of the data.frame package in R. It’s also the go-to package for R users when it comes to the fast aggregation of large data (including 100GB in RAM). The R’s data.table package is a very versatile and a high-performance package due to its ease of use, convenience and programming speed. It is a fairly famous package in the R community with over 400k downloads per month and almost 650 CRAN and Bioconductor packages using it(source). So, what is in it for the Python users? Well, the good news is that there also exists a Python counterpart to thedata.table package called datatable which has a clear focus on big data support, high performance, both in-memory and out-of-memory datasets, and multi-threaded algorithms. In a way, it can be called as data.table’s younger sibling. Modern machine learning applications need to process a humongous amount of data and generate multiple features. This is necessary in order to build models with greater accuracy. Python’s datatable module was created to address this issue. It is a toolkit for performing big data (up to 100GB) operations on a single-node machine, at the maximum possible speed. The development of datatable is sponsored by H2O.ai and the first user of datatable was Driverless.ai. This toolkit resembles pandas very closely but is more focussed on speed and big data support. Python’s datatable also strives to achieve good user experience, helpful error messages, and a powerful API. In this article, we shall see how we can use datatable and how it scores over pandas when it comes to large datasets. On MacOS, datatable can be easily installed with pip: pip install datatable On Linux, installation is achieved with a binary distribution as follows: # If you have Python 3.5pip install https://s3.amazonaws.com/h2o-release/datatable/stable/datatable-0.8.0/datatable-0.8.0-cp35-cp35m-linux_x86_64.whl# If you have Python 3.6pip install https://s3.amazonaws.com/h2o-release/datatable/stable/datatable-0.8.0/datatable-0.8.0-cp36-cp36m-linux_x86_64.whl Currently, datatable does not work on Windows but work is being done to add support for Windows also. For more information see Build instructions. The code for this article can be accessed from the associated Github Repository or can be viewed on my binder by clicking the image below. The dataset being used has been taken from Kaggle and belongs to the Lending Club Loan Data Dataset. The dataset consists of complete loan data for all loans issued through the 2007–2015, including the current loan status (Current, Late, Fully Paid, etc.) and latest payment information. The file consists of 2.26 Million rows and 145 columns. The data size is ideal to demonstrate the capabilities of the datatable library. # Importing necessary Librariesimport numpy as npimport pandas as pdimport datatable as dt Let’s load in the data into the Frame object. The fundamental unit of analysis in datatable is a Frame. It is the same notion as a pandas DataFrame or SQL table: data arranged in a two-dimensional array with rows and columns. With datatable %%timedatatable_df = dt.fread("data.csv")____________________________________________________________________CPU times: user 30 s, sys: 3.39 s, total: 33.4 s Wall time: 23.6 s The fread() function above is both powerful and extremely fast. It can automatically detect and parse parameters for the majority of text files, load data from .zip archives or URLs, read Excel files, and much more. Additionally, the datatable parser : Can automatically detect separators, headers, column types, quoting rules, etc. Can read data from multiple sources including file, URL, shell, raw text, archives and glob. Provides multi-threaded file reading for maximum speed Includes a progress indicator when reading large files Can read both RFC4180-compliant and non-compliant files. With pandas Now, let us calculate the time taken by pandas to read the same file. %%timepandas_df= pd.read_csv("data.csv")___________________________________________________________CPU times: user 47.5 s, sys: 12.1 s, total: 59.6 sWall time: 1min 4s The results show that datatable clearly outperforms pandas when reading large datasets. Whereas pandas take more than a minute, datatable only takes seconds for the same. The existing Frame can also be converted into a numpy or pandas dataframe as follows: numpy_df = datatable_df.to_numpy()pandas_df = datatable_df.to_pandas() Let’s convert our existing frame into a pandas dataframe object and compare the time taken. %%timedatatable_pandas = datatable_df.to_pandas()___________________________________________________________________CPU times: user 17.1 s, sys: 4 s, total: 21.1 sWall time: 21.4 s It appears that reading a file as a datatable frame and then converting it to pandas dataframe takes less time than reading through pandas dataframe. Thus, it might be a good idea to import a large data file through datatable and then convert it to pandas dataframe. type(datatable_pandas)___________________________________________________________________pandas.core.frame.DataFrame Let’s look at some of the basic properties of a datatable frame which are similar to the pandas’ properties: print(datatable_df.shape) # (nrows, ncols)print(datatable_df.names[:5]) # top 5 column namesprint(datatable_df.stypes[:5]) # column types(top 5)______________________________________________________________(2260668, 145)('id', 'member_id', 'loan_amnt', 'funded_amnt', 'funded_amnt_inv')(stype.bool8, stype.bool8, stype.int32, stype.int32, stype.float64) We can also use the head command to output the top ‘n’ rows. datatable_df.head(10) The colour signifies the datatype where red denotes string, green denotes int and blue stands for float. Calculating the summary stats in pandas is a memory consuming process but not anymore with datatable. We can compute the following per-column summary stats using datatable: datatable_df.sum() datatable_df.nunique()datatable_df.sd() datatable_df.max()datatable_df.mode() datatable_df.min()datatable_df.nmodal() datatable_df.mean() Let’s calculate the mean of the columns using both datatable and pandas to measure the time difference. With datatable %%timedatatable_df.mean()_______________________________________________________________CPU times: user 5.11 s, sys: 51.8 ms, total: 5.16 sWall time: 1.43 s With pandas pandas_df.mean()__________________________________________________________________Throws memory error. The above command cannot be completed in pandas as it starts throwing memory error. Data Tables like dataframes are columnar data structures. In datatable, the primary vehicle for all these operations is the square-bracket notation inspired by traditional matrix indexing but with more functionalities. The same DT[i, j] notation is used in mathematics when indexing matrices, in C/C++, in R, in pandas, in numpy, etc. Let’s see how we can perform common data manipulation activities using datatable: The following code selects all rows and the funded_amnt column from the dataset. datatable_df[:,'funded_amnt'] Here is how we can select the first 5 rows and 3 columns datatable_df[:5,:3] With datatable Sorting the frame by a particular column can be accomplished by datatable as follows: %%timedatatable_df.sort('funded_amnt_inv')_________________________________________________________________CPU times: user 534 ms, sys: 67.9 ms, total: 602 msWall time: 179 ms With pandas: %%timepandas_df.sort_values(by = 'funded_amnt_inv')___________________________________________________________________CPU times: user 8.76 s, sys: 2.87 s, total: 11.6 sWall time: 12.4 s Notice the substantial time difference between datable and pandas. Here is how we can delete the column named member_id: del datatable_df[:, 'member_id'] Just like in pandas, datatable also has the groupby functionalities. Let’s see how we can get the mean of funded_amount column grouped by the grade column. With datatable %%timefor i in range(100): datatable_df[:, dt.sum(dt.f.funded_amnt), dt.by(dt.f.grade)]____________________________________________________________________CPU times: user 6.41 s, sys: 1.34 s, total: 7.76 sWall time: 2.42 s With pandas %%timefor i in range(100): pandas_df.groupby("grade")["funded_amnt"].sum()____________________________________________________________________CPU times: user 12.9 s, sys: 859 ms, total: 13.7 sWall time: 13.9 s What does .f stand for? f stands for frame proxy, and provides a simple way to refer to the Frame that we are currently operating upon. In the case of our example, dt.f simply stands for dt_df. The syntax for filtering rows is pretty similar to that of GroupBy. Let us filter those rows of loan_amntfor which the values of loan_amnt are greater than funded_amnt. datatable_df[dt.f.loan_amnt>dt.f.funded_amnt,"loan_amnt"] It is also possible to write the Frame’s content into a csv file so that it can be used in future. datatable_df.to_csv('output.csv') For more data manipulation functions, refer to the documentation page. The datatable module definitely speeds up the execution as compared to the default pandas and this definitely is a boon when working on large datasets. However, datatable lags behind pandas in terms of functionalities. But since datatable is still undergoing active development, we might see some major additions to the library in the future. R’s data.table Datatable documentation Getting started with Python datatable: A wonderful Kaggle Kernel on the usage of datatable DatatableTon — 100 datatable exercises over different sections structured as a course or tutorials to teach and learn for beginners, intermediates as well as experts.
[ { "code": null, "e": 332, "s": 171, "text": "“There were 5 Exabytes of information created between the dawn of civilization through 2003, but that much information is now created every 2 days”:Eric Schmidt" }, { "code": null, "e": 600, "s": 332, "text": "If you are an R user, chances are that you have already been using the data.table package. Data.table is an extension of the data.frame package in R. It’s also the go-to package for R users when it comes to the fast aggregation of large data (including 100GB in RAM)." }, { "code": null, "e": 885, "s": 600, "text": "The R’s data.table package is a very versatile and a high-performance package due to its ease of use, convenience and programming speed. It is a fairly famous package in the R community with over 400k downloads per month and almost 650 CRAN and Bioconductor packages using it(source)." }, { "code": null, "e": 1231, "s": 885, "text": "So, what is in it for the Python users? Well, the good news is that there also exists a Python counterpart to thedata.table package called datatable which has a clear focus on big data support, high performance, both in-memory and out-of-memory datasets, and multi-threaded algorithms. In a way, it can be called as data.table’s younger sibling." }, { "code": null, "e": 1695, "s": 1231, "text": "Modern machine learning applications need to process a humongous amount of data and generate multiple features. This is necessary in order to build models with greater accuracy. Python’s datatable module was created to address this issue. It is a toolkit for performing big data (up to 100GB) operations on a single-node machine, at the maximum possible speed. The development of datatable is sponsored by H2O.ai and the first user of datatable was Driverless.ai." }, { "code": null, "e": 2017, "s": 1695, "text": "This toolkit resembles pandas very closely but is more focussed on speed and big data support. Python’s datatable also strives to achieve good user experience, helpful error messages, and a powerful API. In this article, we shall see how we can use datatable and how it scores over pandas when it comes to large datasets." }, { "code": null, "e": 2071, "s": 2017, "text": "On MacOS, datatable can be easily installed with pip:" }, { "code": null, "e": 2093, "s": 2071, "text": "pip install datatable" }, { "code": null, "e": 2167, "s": 2093, "text": "On Linux, installation is achieved with a binary distribution as follows:" }, { "code": null, "e": 2466, "s": 2167, "text": "# If you have Python 3.5pip install https://s3.amazonaws.com/h2o-release/datatable/stable/datatable-0.8.0/datatable-0.8.0-cp35-cp35m-linux_x86_64.whl# If you have Python 3.6pip install https://s3.amazonaws.com/h2o-release/datatable/stable/datatable-0.8.0/datatable-0.8.0-cp36-cp36m-linux_x86_64.whl" }, { "code": null, "e": 2568, "s": 2466, "text": "Currently, datatable does not work on Windows but work is being done to add support for Windows also." }, { "code": null, "e": 2613, "s": 2568, "text": "For more information see Build instructions." }, { "code": null, "e": 2752, "s": 2613, "text": "The code for this article can be accessed from the associated Github Repository or can be viewed on my binder by clicking the image below." }, { "code": null, "e": 3177, "s": 2752, "text": "The dataset being used has been taken from Kaggle and belongs to the Lending Club Loan Data Dataset. The dataset consists of complete loan data for all loans issued through the 2007–2015, including the current loan status (Current, Late, Fully Paid, etc.) and latest payment information. The file consists of 2.26 Million rows and 145 columns. The data size is ideal to demonstrate the capabilities of the datatable library." }, { "code": null, "e": 3268, "s": 3177, "text": "# Importing necessary Librariesimport numpy as npimport pandas as pdimport datatable as dt" }, { "code": null, "e": 3494, "s": 3268, "text": "Let’s load in the data into the Frame object. The fundamental unit of analysis in datatable is a Frame. It is the same notion as a pandas DataFrame or SQL table: data arranged in a two-dimensional array with rows and columns." }, { "code": null, "e": 3509, "s": 3494, "text": "With datatable" }, { "code": null, "e": 3716, "s": 3509, "text": "%%timedatatable_df = dt.fread(\"data.csv\")____________________________________________________________________CPU times: user 30 s, sys: 3.39 s, total: 33.4 s Wall time: 23.6 s" }, { "code": null, "e": 3932, "s": 3716, "text": "The fread() function above is both powerful and extremely fast. It can automatically detect and parse parameters for the majority of text files, load data from .zip archives or URLs, read Excel files, and much more." }, { "code": null, "e": 3969, "s": 3932, "text": "Additionally, the datatable parser :" }, { "code": null, "e": 4049, "s": 3969, "text": "Can automatically detect separators, headers, column types, quoting rules, etc." }, { "code": null, "e": 4142, "s": 4049, "text": "Can read data from multiple sources including file, URL, shell, raw text, archives and glob." }, { "code": null, "e": 4197, "s": 4142, "text": "Provides multi-threaded file reading for maximum speed" }, { "code": null, "e": 4252, "s": 4197, "text": "Includes a progress indicator when reading large files" }, { "code": null, "e": 4309, "s": 4252, "text": "Can read both RFC4180-compliant and non-compliant files." }, { "code": null, "e": 4321, "s": 4309, "text": "With pandas" }, { "code": null, "e": 4391, "s": 4321, "text": "Now, let us calculate the time taken by pandas to read the same file." }, { "code": null, "e": 4559, "s": 4391, "text": "%%timepandas_df= pd.read_csv(\"data.csv\")___________________________________________________________CPU times: user 47.5 s, sys: 12.1 s, total: 59.6 sWall time: 1min 4s" }, { "code": null, "e": 4730, "s": 4559, "text": "The results show that datatable clearly outperforms pandas when reading large datasets. Whereas pandas take more than a minute, datatable only takes seconds for the same." }, { "code": null, "e": 4816, "s": 4730, "text": "The existing Frame can also be converted into a numpy or pandas dataframe as follows:" }, { "code": null, "e": 4887, "s": 4816, "text": "numpy_df = datatable_df.to_numpy()pandas_df = datatable_df.to_pandas()" }, { "code": null, "e": 4979, "s": 4887, "text": "Let’s convert our existing frame into a pandas dataframe object and compare the time taken." }, { "code": null, "e": 5160, "s": 4979, "text": "%%timedatatable_pandas = datatable_df.to_pandas()___________________________________________________________________CPU times: user 17.1 s, sys: 4 s, total: 21.1 sWall time: 21.4 s" }, { "code": null, "e": 5427, "s": 5160, "text": "It appears that reading a file as a datatable frame and then converting it to pandas dataframe takes less time than reading through pandas dataframe. Thus, it might be a good idea to import a large data file through datatable and then convert it to pandas dataframe." }, { "code": null, "e": 5544, "s": 5427, "text": "type(datatable_pandas)___________________________________________________________________pandas.core.frame.DataFrame" }, { "code": null, "e": 5653, "s": 5544, "text": "Let’s look at some of the basic properties of a datatable frame which are similar to the pandas’ properties:" }, { "code": null, "e": 6016, "s": 5653, "text": "print(datatable_df.shape) # (nrows, ncols)print(datatable_df.names[:5]) # top 5 column namesprint(datatable_df.stypes[:5]) # column types(top 5)______________________________________________________________(2260668, 145)('id', 'member_id', 'loan_amnt', 'funded_amnt', 'funded_amnt_inv')(stype.bool8, stype.bool8, stype.int32, stype.int32, stype.float64)" }, { "code": null, "e": 6077, "s": 6016, "text": "We can also use the head command to output the top ‘n’ rows." }, { "code": null, "e": 6099, "s": 6077, "text": "datatable_df.head(10)" }, { "code": null, "e": 6204, "s": 6099, "text": "The colour signifies the datatype where red denotes string, green denotes int and blue stands for float." }, { "code": null, "e": 6377, "s": 6204, "text": "Calculating the summary stats in pandas is a memory consuming process but not anymore with datatable. We can compute the following per-column summary stats using datatable:" }, { "code": null, "e": 6551, "s": 6377, "text": "datatable_df.sum() datatable_df.nunique()datatable_df.sd() datatable_df.max()datatable_df.mode() datatable_df.min()datatable_df.nmodal() datatable_df.mean()" }, { "code": null, "e": 6655, "s": 6551, "text": "Let’s calculate the mean of the columns using both datatable and pandas to measure the time difference." }, { "code": null, "e": 6670, "s": 6655, "text": "With datatable" }, { "code": null, "e": 6827, "s": 6670, "text": "%%timedatatable_df.mean()_______________________________________________________________CPU times: user 5.11 s, sys: 51.8 ms, total: 5.16 sWall time: 1.43 s" }, { "code": null, "e": 6839, "s": 6827, "text": "With pandas" }, { "code": null, "e": 6942, "s": 6839, "text": "pandas_df.mean()__________________________________________________________________Throws memory error." }, { "code": null, "e": 7026, "s": 6942, "text": "The above command cannot be completed in pandas as it starts throwing memory error." }, { "code": null, "e": 7245, "s": 7026, "text": "Data Tables like dataframes are columnar data structures. In datatable, the primary vehicle for all these operations is the square-bracket notation inspired by traditional matrix indexing but with more functionalities." }, { "code": null, "e": 7443, "s": 7245, "text": "The same DT[i, j] notation is used in mathematics when indexing matrices, in C/C++, in R, in pandas, in numpy, etc. Let’s see how we can perform common data manipulation activities using datatable:" }, { "code": null, "e": 7524, "s": 7443, "text": "The following code selects all rows and the funded_amnt column from the dataset." }, { "code": null, "e": 7554, "s": 7524, "text": "datatable_df[:,'funded_amnt']" }, { "code": null, "e": 7611, "s": 7554, "text": "Here is how we can select the first 5 rows and 3 columns" }, { "code": null, "e": 7631, "s": 7611, "text": "datatable_df[:5,:3]" }, { "code": null, "e": 7646, "s": 7631, "text": "With datatable" }, { "code": null, "e": 7732, "s": 7646, "text": "Sorting the frame by a particular column can be accomplished by datatable as follows:" }, { "code": null, "e": 7908, "s": 7732, "text": "%%timedatatable_df.sort('funded_amnt_inv')_________________________________________________________________CPU times: user 534 ms, sys: 67.9 ms, total: 602 msWall time: 179 ms" }, { "code": null, "e": 7921, "s": 7908, "text": "With pandas:" }, { "code": null, "e": 8107, "s": 7921, "text": "%%timepandas_df.sort_values(by = 'funded_amnt_inv')___________________________________________________________________CPU times: user 8.76 s, sys: 2.87 s, total: 11.6 sWall time: 12.4 s" }, { "code": null, "e": 8174, "s": 8107, "text": "Notice the substantial time difference between datable and pandas." }, { "code": null, "e": 8228, "s": 8174, "text": "Here is how we can delete the column named member_id:" }, { "code": null, "e": 8261, "s": 8228, "text": "del datatable_df[:, 'member_id']" }, { "code": null, "e": 8417, "s": 8261, "text": "Just like in pandas, datatable also has the groupby functionalities. Let’s see how we can get the mean of funded_amount column grouped by the grade column." }, { "code": null, "e": 8432, "s": 8417, "text": "With datatable" }, { "code": null, "e": 8658, "s": 8432, "text": "%%timefor i in range(100): datatable_df[:, dt.sum(dt.f.funded_amnt), dt.by(dt.f.grade)]____________________________________________________________________CPU times: user 6.41 s, sys: 1.34 s, total: 7.76 sWall time: 2.42 s" }, { "code": null, "e": 8670, "s": 8658, "text": "With pandas" }, { "code": null, "e": 8883, "s": 8670, "text": "%%timefor i in range(100): pandas_df.groupby(\"grade\")[\"funded_amnt\"].sum()____________________________________________________________________CPU times: user 12.9 s, sys: 859 ms, total: 13.7 sWall time: 13.9 s" }, { "code": null, "e": 8907, "s": 8883, "text": "What does .f stand for?" }, { "code": null, "e": 9077, "s": 8907, "text": "f stands for frame proxy, and provides a simple way to refer to the Frame that we are currently operating upon. In the case of our example, dt.f simply stands for dt_df." }, { "code": null, "e": 9246, "s": 9077, "text": "The syntax for filtering rows is pretty similar to that of GroupBy. Let us filter those rows of loan_amntfor which the values of loan_amnt are greater than funded_amnt." }, { "code": null, "e": 9304, "s": 9246, "text": "datatable_df[dt.f.loan_amnt>dt.f.funded_amnt,\"loan_amnt\"]" }, { "code": null, "e": 9403, "s": 9304, "text": "It is also possible to write the Frame’s content into a csv file so that it can be used in future." }, { "code": null, "e": 9437, "s": 9403, "text": "datatable_df.to_csv('output.csv')" }, { "code": null, "e": 9508, "s": 9437, "text": "For more data manipulation functions, refer to the documentation page." }, { "code": null, "e": 9851, "s": 9508, "text": "The datatable module definitely speeds up the execution as compared to the default pandas and this definitely is a boon when working on large datasets. However, datatable lags behind pandas in terms of functionalities. But since datatable is still undergoing active development, we might see some major additions to the library in the future." }, { "code": null, "e": 9866, "s": 9851, "text": "R’s data.table" }, { "code": null, "e": 9890, "s": 9866, "text": "Datatable documentation" }, { "code": null, "e": 9981, "s": 9890, "text": "Getting started with Python datatable: A wonderful Kaggle Kernel on the usage of datatable" } ]
React Native - TouchableOpacity
In this chapter we will show you button example using TouchableOpacity component. First we need to create src/components/home/TouchableOpacity.js file. This is just a simple container component with no additional functionality. src/components/home/HomeContainer.js import React, { Component } from 'react' import TouchableOpacityExample from './TouchableOpacityExample' export default class HomeContainer extends Component { constructor() { super(); } render() { return ( <TouchableOpacityExample buttonPressed = {this.buttonPressed}/> ); } } Presentational component is a simple button with some styling. src/components/home/TouchableOpacityExample.js import React, { Component } from 'react' import { View, TouchableOpacity, Text, StyleSheet } from 'react-native' export default TouchableOpacityExample = (props) => { return ( <View style = {styles.container}> <TouchableOpacity> <Text style = {styles.button}> Button </Text> </TouchableOpacity> </View> ) } const styles = StyleSheet.create ({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, button: { borderWidth: 1, padding: 25, borderColor: 'black' } }) When we press the button, opacity will change. 20 Lectures 1.5 hours Anadi Sharma 61 Lectures 6.5 hours A To Z Mentor 40 Lectures 4.5 hours Eduonix Learning Solutions 56 Lectures 12.5 hours Eduonix Learning Solutions 62 Lectures 4.5 hours Senol Atac 67 Lectures 4.5 hours Senol Atac Print Add Notes Bookmark this page
[ { "code": null, "e": 2426, "s": 2344, "text": "In this chapter we will show you button example using TouchableOpacity component." }, { "code": null, "e": 2496, "s": 2426, "text": "First we need to create src/components/home/TouchableOpacity.js file." }, { "code": null, "e": 2572, "s": 2496, "text": "This is just a simple container component with no additional functionality." }, { "code": null, "e": 2609, "s": 2572, "text": "src/components/home/HomeContainer.js" }, { "code": null, "e": 2928, "s": 2609, "text": "import React, { Component } from 'react'\nimport TouchableOpacityExample from './TouchableOpacityExample'\n\nexport default class HomeContainer extends Component {\n\n constructor() {\n super();\n }\n render() {\n return (\n <TouchableOpacityExample buttonPressed = {this.buttonPressed}/>\n );\n }\n}" }, { "code": null, "e": 2991, "s": 2928, "text": "Presentational component is a simple button with some styling." }, { "code": null, "e": 3038, "s": 2991, "text": "src/components/home/TouchableOpacityExample.js" }, { "code": null, "e": 3656, "s": 3038, "text": "import React, { Component } from 'react'\nimport {\n View,\n TouchableOpacity,\n Text,\n StyleSheet\n} from 'react-native'\n\nexport default TouchableOpacityExample = (props) => {\n return (\n <View style = {styles.container}>\n <TouchableOpacity>\n <Text style = {styles.button}>\n Button\n </Text>\n </TouchableOpacity>\n </View>\n )\n}\n\nconst styles = StyleSheet.create ({\n container: {\n flex: 1,\n justifyContent: 'center',\n alignItems: 'center',\n },\n button: {\n borderWidth: 1,\n padding: 25,\n borderColor: 'black'\n }\n})" }, { "code": null, "e": 3703, "s": 3656, "text": "When we press the button, opacity will change." }, { "code": null, "e": 3738, "s": 3703, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3752, "s": 3738, "text": " Anadi Sharma" }, { "code": null, "e": 3787, "s": 3752, "text": "\n 61 Lectures \n 6.5 hours \n" }, { "code": null, "e": 3802, "s": 3787, "text": " A To Z Mentor" }, { "code": null, "e": 3837, "s": 3802, "text": "\n 40 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3865, "s": 3837, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3901, "s": 3865, "text": "\n 56 Lectures \n 12.5 hours \n" }, { "code": null, "e": 3929, "s": 3901, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3964, "s": 3929, "text": "\n 62 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3976, "s": 3964, "text": " Senol Atac" }, { "code": null, "e": 4011, "s": 3976, "text": "\n 67 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4023, "s": 4011, "text": " Senol Atac" }, { "code": null, "e": 4030, "s": 4023, "text": " Print" }, { "code": null, "e": 4041, "s": 4030, "text": " Add Notes" } ]
Check if original Array is retained after performing XOR with M exactly K times - GeeksforGeeks
24 Nov, 2021 Given an array A and two integers M and K, the task is to check and print “Yes“, if the original array can be retained by performing exactly ‘K‘ number of bitwise XOR operations of the array elements with ‘M‘. Else print “No“.Note: XOR operation can be performed, on any element of the array, for 0 or more times. Examples: Input: A[] = {1, 2, 3, 4}, M = 5, K = 6 Output: Yes Explanation: If the XOR is performed on 1st element, A[0], for 6 times, we get A[0] back. Therefore, the original array is retained.Input: A[] = {5, 9, 3, 4, 5}, M = 5, K = 3 Output: No Explanation: The original array cant be retained after performing odd number of XOR operations. Approach: This problem can be solved using the XOR property A XOR B = C and C XOR B = A It can be seen that: if even number of XOR operations are performed for any positive number, then the original number can be retained.However, 0 is an exception. If both odd or even number of XOR operations are performed for 0, then the original number can be retained.Therefore, if K is even and M is 0, then the answer will always be Yes.If K is odd and 0 is not present in the array, then the answer will always be No.If K is odd and the count of 0 is at least 1 in the array then, the answer will be Yes. if even number of XOR operations are performed for any positive number, then the original number can be retained. However, 0 is an exception. If both odd or even number of XOR operations are performed for 0, then the original number can be retained. Therefore, if K is even and M is 0, then the answer will always be Yes. If K is odd and 0 is not present in the array, then the answer will always be No. If K is odd and the count of 0 is at least 1 in the array then, the answer will be Yes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation for the// above mentioned problem #include <bits/stdc++.h>using namespace std; // Function to check if original Array// can be retained by performing XOR// with M exactly K timesstring check(int Arr[], int n, int M, int K){ int flag = 0; // Check if O is present or not for (int i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return "No"; // Else it will be Yes else return "Yes";} // Driver Codeint main(){ int Arr[] = { 1, 1, 2, 4, 7, 8 }; int M = 5; int K = 6; int n = sizeof(Arr) / sizeof(Arr[0]); cout << check(Arr, n, M, K); return 0;} import java.util.*; class GFG{ // Function to check if original Array// can be retained by performing XOR// with M exactly K timesstatic String check(int []Arr, int n, int M, int K){ int flag = 0; // Check if O is present or not for (int i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return "No"; // Else it will be Yes else return "Yes";} // Driver Codepublic static void main(String args[]){ int []Arr = { 1, 1, 2, 4, 7, 8 }; int M = 5; int K = 6; int n = Arr.length; System.out.println(check(Arr, n, M, K));}} // This code is contributed by Surendra_Gangwar # Python3 implementation for the# above mentioned problem # Function to check if original Array# can be retained by performing XOR# with M exactly K timesdef check(Arr, n, M, K): flag = 0 # Check if O is present or not for i in range(n): if (Arr[i] == 0): flag = 1 # If K is odd and 0 is not present # then the answer will always be No. if (K % 2 != 0 and flag == 0): return "No" # Else it will be Yes else: return "Yes"; # Driver Codeif __name__=='__main__': Arr = [ 1, 1, 2, 4, 7, 8 ] M = 5; K = 6; n = len(Arr); print(check(Arr, n, M, K)) # This article contributed by Princi Singh // C# implementation for the// above mentioned problemusing System; class GFG{ // Function to check if original Array// can be retained by performing XOR// with M exactly K timesstatic String check(int []Arr, int n,int M, int K){ int flag = 0; // Check if O is present or not for (int i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return "No"; // Else it will be Yes else return "Yes";} // Driver codepublic static void Main(String[] args){ int []Arr = { 1, 1, 2, 4, 7, 8 }; int M = 5; int K = 6; int n = Arr.Length; Console.Write(check(Arr, n, M, K));}} // This code is contributed by shivanisinghss2110 <script>// Javascript implementation for the// above mentioned problem // Function to check if original Array// can be retained by performing XOR// with M exactly K timesfunction check(Arr, n, M, K){ let flag = 0; // Check if O is present or not for (let i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return "No"; // Else it will be Yes else return "Yes";} // Driver Code let Arr = [ 1, 1, 2, 4, 7, 8 ]; let M = 5; let K = 6; let n = Arr.length; document.write(check(Arr, n, M, K)); </script> Yes Time Complexity: O(N) Auxiliary Space: O(1) princi singh SURENDRA_GANGWAR shivanisinghss2110 rishavmahato348 subham348 Bitwise-XOR Maths Arrays Bit Magic Competitive Programming Mathematical Arrays Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find sum of elements in a given array Trapping Rain Water Reversal algorithm for array rotation Move all negative numbers to beginning and positive to end with constant extra space Window Sliding Technique Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Cyclic Redundancy Check and Modulo-2 Division Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer
[ { "code": null, "e": 24405, "s": 24377, "text": "\n24 Nov, 2021" }, { "code": null, "e": 24731, "s": 24405, "text": "Given an array A and two integers M and K, the task is to check and print “Yes“, if the original array can be retained by performing exactly ‘K‘ number of bitwise XOR operations of the array elements with ‘M‘. Else print “No“.Note: XOR operation can be performed, on any element of the array, for 0 or more times. Examples: " }, { "code": null, "e": 25067, "s": 24731, "text": "Input: A[] = {1, 2, 3, 4}, M = 5, K = 6 Output: Yes Explanation: If the XOR is performed on 1st element, A[0], for 6 times, we get A[0] back. Therefore, the original array is retained.Input: A[] = {5, 9, 3, 4, 5}, M = 5, K = 3 Output: No Explanation: The original array cant be retained after performing odd number of XOR operations. " }, { "code": null, "e": 25131, "s": 25069, "text": "Approach: This problem can be solved using the XOR property " }, { "code": null, "e": 25161, "s": 25131, "text": "A XOR B = C and C XOR B = A " }, { "code": null, "e": 25184, "s": 25161, "text": "It can be seen that: " }, { "code": null, "e": 25672, "s": 25184, "text": "if even number of XOR operations are performed for any positive number, then the original number can be retained.However, 0 is an exception. If both odd or even number of XOR operations are performed for 0, then the original number can be retained.Therefore, if K is even and M is 0, then the answer will always be Yes.If K is odd and 0 is not present in the array, then the answer will always be No.If K is odd and the count of 0 is at least 1 in the array then, the answer will be Yes." }, { "code": null, "e": 25786, "s": 25672, "text": "if even number of XOR operations are performed for any positive number, then the original number can be retained." }, { "code": null, "e": 25922, "s": 25786, "text": "However, 0 is an exception. If both odd or even number of XOR operations are performed for 0, then the original number can be retained." }, { "code": null, "e": 25994, "s": 25922, "text": "Therefore, if K is even and M is 0, then the answer will always be Yes." }, { "code": null, "e": 26076, "s": 25994, "text": "If K is odd and 0 is not present in the array, then the answer will always be No." }, { "code": null, "e": 26164, "s": 26076, "text": "If K is odd and the count of 0 is at least 1 in the array then, the answer will be Yes." }, { "code": null, "e": 26216, "s": 26164, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26220, "s": 26216, "text": "C++" }, { "code": null, "e": 26225, "s": 26220, "text": "Java" }, { "code": null, "e": 26233, "s": 26225, "text": "Python3" }, { "code": null, "e": 26236, "s": 26233, "text": "C#" }, { "code": null, "e": 26247, "s": 26236, "text": "Javascript" }, { "code": "// C++ implementation for the// above mentioned problem #include <bits/stdc++.h>using namespace std; // Function to check if original Array// can be retained by performing XOR// with M exactly K timesstring check(int Arr[], int n, int M, int K){ int flag = 0; // Check if O is present or not for (int i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return \"No\"; // Else it will be Yes else return \"Yes\";} // Driver Codeint main(){ int Arr[] = { 1, 1, 2, 4, 7, 8 }; int M = 5; int K = 6; int n = sizeof(Arr) / sizeof(Arr[0]); cout << check(Arr, n, M, K); return 0;}", "e": 27018, "s": 26247, "text": null }, { "code": "import java.util.*; class GFG{ // Function to check if original Array// can be retained by performing XOR// with M exactly K timesstatic String check(int []Arr, int n, int M, int K){ int flag = 0; // Check if O is present or not for (int i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return \"No\"; // Else it will be Yes else return \"Yes\";} // Driver Codepublic static void main(String args[]){ int []Arr = { 1, 1, 2, 4, 7, 8 }; int M = 5; int K = 6; int n = Arr.length; System.out.println(check(Arr, n, M, K));}} // This code is contributed by Surendra_Gangwar", "e": 27783, "s": 27018, "text": null }, { "code": "# Python3 implementation for the# above mentioned problem # Function to check if original Array# can be retained by performing XOR# with M exactly K timesdef check(Arr, n, M, K): flag = 0 # Check if O is present or not for i in range(n): if (Arr[i] == 0): flag = 1 # If K is odd and 0 is not present # then the answer will always be No. if (K % 2 != 0 and flag == 0): return \"No\" # Else it will be Yes else: return \"Yes\"; # Driver Codeif __name__=='__main__': Arr = [ 1, 1, 2, 4, 7, 8 ] M = 5; K = 6; n = len(Arr); print(check(Arr, n, M, K)) # This article contributed by Princi Singh", "e": 28455, "s": 27783, "text": null }, { "code": "// C# implementation for the// above mentioned problemusing System; class GFG{ // Function to check if original Array// can be retained by performing XOR// with M exactly K timesstatic String check(int []Arr, int n,int M, int K){ int flag = 0; // Check if O is present or not for (int i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return \"No\"; // Else it will be Yes else return \"Yes\";} // Driver codepublic static void Main(String[] args){ int []Arr = { 1, 1, 2, 4, 7, 8 }; int M = 5; int K = 6; int n = Arr.Length; Console.Write(check(Arr, n, M, K));}} // This code is contributed by shivanisinghss2110", "e": 29258, "s": 28455, "text": null }, { "code": "<script>// Javascript implementation for the// above mentioned problem // Function to check if original Array// can be retained by performing XOR// with M exactly K timesfunction check(Arr, n, M, K){ let flag = 0; // Check if O is present or not for (let i = 0; i < n; i++) { if (Arr[i] == 0) flag = 1; } // If K is odd and 0 is not present // then the answer will always be No. if (K % 2 != 0 && flag == 0) return \"No\"; // Else it will be Yes else return \"Yes\";} // Driver Code let Arr = [ 1, 1, 2, 4, 7, 8 ]; let M = 5; let K = 6; let n = Arr.length; document.write(check(Arr, n, M, K)); </script>", "e": 29944, "s": 29258, "text": null }, { "code": null, "e": 29948, "s": 29944, "text": "Yes" }, { "code": null, "e": 29972, "s": 29950, "text": "Time Complexity: O(N)" }, { "code": null, "e": 29994, "s": 29972, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30007, "s": 29994, "text": "princi singh" }, { "code": null, "e": 30024, "s": 30007, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 30043, "s": 30024, "text": "shivanisinghss2110" }, { "code": null, "e": 30059, "s": 30043, "text": "rishavmahato348" }, { "code": null, "e": 30069, "s": 30059, "text": "subham348" }, { "code": null, "e": 30081, "s": 30069, "text": "Bitwise-XOR" }, { "code": null, "e": 30087, "s": 30081, "text": "Maths" }, { "code": null, "e": 30094, "s": 30087, "text": "Arrays" }, { "code": null, "e": 30104, "s": 30094, "text": "Bit Magic" }, { "code": null, "e": 30128, "s": 30104, "text": "Competitive Programming" }, { "code": null, "e": 30141, "s": 30128, "text": "Mathematical" }, { "code": null, "e": 30148, "s": 30141, "text": "Arrays" }, { "code": null, "e": 30161, "s": 30148, "text": "Mathematical" }, { "code": null, "e": 30171, "s": 30161, "text": "Bit Magic" }, { "code": null, "e": 30269, "s": 30171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30278, "s": 30269, "text": "Comments" }, { "code": null, "e": 30291, "s": 30278, "text": "Old Comments" }, { "code": null, "e": 30340, "s": 30291, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 30360, "s": 30340, "text": "Trapping Rain Water" }, { "code": null, "e": 30398, "s": 30360, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30483, "s": 30398, "text": "Move all negative numbers to beginning and positive to end with constant extra space" }, { "code": null, "e": 30508, "s": 30483, "text": "Window Sliding Technique" }, { "code": null, "e": 30535, "s": 30508, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 30581, "s": 30535, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 30627, "s": 30581, "text": "Cyclic Redundancy Check and Modulo-2 Division" }, { "code": null, "e": 30695, "s": 30627, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" } ]
CLOSINGBALANCEYEAR function
Evaluates the expression at the last date of the year in the current context. CLOSINGBALANCEYEAR (<expression>, <dates>, [<filter>], [<year_end_date>]) expression An expression that returns a scalar value. dates A column that contains dates. filter Optional. An expression that specifies a filter to apply to the current context. year_end_date Optional. A literal string with a date that defines the year end date. The default is December 31. A scalar value. The dates parameter can be any of the following − A reference to a date/time column. A reference to a date/time column. A table expression that returns a single column of date/time values. A table expression that returns a single column of date/time values. A Boolean expression that defines a single-column table of date/time values. A Boolean expression that defines a single-column table of date/time values. Constraints on Boolean expressions − The expression cannot reference a calculated field. The expression cannot reference a calculated field. The expression cannot use CALCULATE function. The expression cannot use CALCULATE function. The expression cannot use any function that scans a table or returns a table, including aggregation functions. The expression cannot use any function that scans a table or returns a table, including aggregation functions. However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value. The filter parameter can be a Boolean expression or a table expression that defines a filter. The year_end_date parameter is a string literal of a date, in the locale where the workbook was created. The year portion of the date is ignored. Year End Inventory Value:= CLOSINGBALANCEYEAR ( SUMX (ProductInventory, [UnitsBalance]*[UnitCost]),ProductInventory[InventoryDate] ) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2079, "s": 2001, "text": "Evaluates the expression at the last date of the year in the current context." }, { "code": null, "e": 2154, "s": 2079, "text": "CLOSINGBALANCEYEAR (<expression>, <dates>, [<filter>], [<year_end_date>])\n" }, { "code": null, "e": 2165, "s": 2154, "text": "expression" }, { "code": null, "e": 2208, "s": 2165, "text": "An expression that returns a scalar value." }, { "code": null, "e": 2214, "s": 2208, "text": "dates" }, { "code": null, "e": 2244, "s": 2214, "text": "A column that contains dates." }, { "code": null, "e": 2251, "s": 2244, "text": "filter" }, { "code": null, "e": 2261, "s": 2251, "text": "Optional." }, { "code": null, "e": 2332, "s": 2261, "text": "An expression that specifies a filter to apply to the current context." }, { "code": null, "e": 2346, "s": 2332, "text": "year_end_date" }, { "code": null, "e": 2356, "s": 2346, "text": "Optional." }, { "code": null, "e": 2445, "s": 2356, "text": "A literal string with a date that defines the year end date. The default is December 31." }, { "code": null, "e": 2461, "s": 2445, "text": "A scalar value." }, { "code": null, "e": 2511, "s": 2461, "text": "The dates parameter can be any of the following −" }, { "code": null, "e": 2546, "s": 2511, "text": "A reference to a date/time column." }, { "code": null, "e": 2581, "s": 2546, "text": "A reference to a date/time column." }, { "code": null, "e": 2650, "s": 2581, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2719, "s": 2650, "text": "A table expression that returns a single column of date/time values." }, { "code": null, "e": 2796, "s": 2719, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2873, "s": 2796, "text": "A Boolean expression that defines a single-column table of date/time values." }, { "code": null, "e": 2910, "s": 2873, "text": "Constraints on Boolean expressions −" }, { "code": null, "e": 2962, "s": 2910, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3014, "s": 2962, "text": "The expression cannot reference a calculated field." }, { "code": null, "e": 3060, "s": 3014, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3106, "s": 3060, "text": "The expression cannot use CALCULATE function." }, { "code": null, "e": 3217, "s": 3106, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3328, "s": 3217, "text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions." }, { "code": null, "e": 3444, "s": 3328, "text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value." }, { "code": null, "e": 3538, "s": 3444, "text": "The filter parameter can be a Boolean expression or a table expression that defines a filter." }, { "code": null, "e": 3684, "s": 3538, "text": "The year_end_date parameter is a string literal of a date, in the locale where the workbook was created. The year portion of the date is ignored." }, { "code": null, "e": 3822, "s": 3684, "text": "Year End Inventory Value:= CLOSINGBALANCEYEAR ( \n SUMX (ProductInventory, [UnitsBalance]*[UnitCost]),ProductInventory[InventoryDate]\n) " }, { "code": null, "e": 3857, "s": 3822, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3871, "s": 3857, "text": " Abhay Gadiya" }, { "code": null, "e": 3904, "s": 3871, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3918, "s": 3904, "text": " Randy Minder" }, { "code": null, "e": 3953, "s": 3918, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3967, "s": 3953, "text": " Randy Minder" }, { "code": null, "e": 3974, "s": 3967, "text": " Print" }, { "code": null, "e": 3985, "s": 3974, "text": " Add Notes" } ]
Basic Blocks in Compiler Design - GeeksforGeeks
16 Feb, 2022 Basic Block is a straight line code sequence that has no branches in and out branches except to the entry and at the end respectively. Basic Block is a set of statements that always executes one after other, in a sequence. The first task is to partition a sequence of three-address code into basic blocks. A new basic block is begun with the first instruction and instructions are added until a jump or a label is met. In the absence of a jump, control moves further consecutively from one instruction to another. The idea is standardized in the algorithm below: Algorithm: Partitioning three-address code into basic blocks. Input: A sequence of three address instructions. Process: Instructions from intermediate code which are leaders are determined. Following are the rules used for finding a leader: The first three-address instruction of the intermediate code is a leader. Instructions that are targets of unconditional or conditional jump/goto statements are leaders. Instructions that immediately follow unconditional or conditional jump/goto statements are considered leaders. The first three-address instruction of the intermediate code is a leader. Instructions that are targets of unconditional or conditional jump/goto statements are leaders. Instructions that immediately follow unconditional or conditional jump/goto statements are considered leaders. For each leader thus determined its basic block contains itself and all instructions up to excluding the next leader. Example: Intermediate code to set a 10*10 matrix to an identity matrix: 1) i=1 //Leader 1 (First statement) 2) j=1 //Leader 2 (Target of 11th statement) 3) t1 = 10 * i //Leader 3 (Target of 9th statement) 4) t2 = t1 + j 5) t3 = 8 * t2 6) t4 = t3 - 88 7) a[t4] = 0.0 8) j = j + 1 9) if j <= goto (3) 10) i = i + 1 //Leader 4 (Immediately following Conditional goto statement) 11) if i <= 10 goto (2) 12) i = 1 //Leader 5 (Immediately following Conditional goto statement) 13) t5 = i - 1 //Leader 6 (Target of 17th statement) 14) t6 = 88 * t5 15) a[t6] = 1.0 16) i = i + 1 17) if i <= 10 goto (13) The given algorithm is used to convert a matrix into identity matrix i.e. a matrix with all diagonal elements 1 and all other elements as 0. Steps (3)-(6) are used to make elements 0, step (14) is used to make an element 1. These steps are used recursively by goto statements. There are 6 Basic Blocks in the above code : B1) Statement 1 B2) Statement 2 B3) Statement 3-9 B4) Statement 10-11 B5) Statement 12 B6) Statement 13-17 jatin7599 rajkumaar23 singhdrishti1001 mohansaitejat Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Directed Acyclic graph in Compiler Design (with examples) Difference between Top down parsing and Bottom up parsing Loop Optimization in Compiler Design S - attributed and L - attributed SDTs in Syntax directed translation Compiler construction tools Layers of OSI Model ACID Properties in DBMS TCP/IP Model Page Replacement Algorithms in Operating Systems Types of Operating Systems
[ { "code": null, "e": 24444, "s": 24416, "text": "\n16 Feb, 2022" }, { "code": null, "e": 24668, "s": 24444, "text": "Basic Block is a straight line code sequence that has no branches in and out branches except to the entry and at the end respectively. Basic Block is a set of statements that always executes one after other, in a sequence. " }, { "code": null, "e": 25009, "s": 24668, "text": "The first task is to partition a sequence of three-address code into basic blocks. A new basic block is begun with the first instruction and instructions are added until a jump or a label is met. In the absence of a jump, control moves further consecutively from one instruction to another. The idea is standardized in the algorithm below: " }, { "code": null, "e": 25072, "s": 25009, "text": "Algorithm: Partitioning three-address code into basic blocks. " }, { "code": null, "e": 25122, "s": 25072, "text": "Input: A sequence of three address instructions. " }, { "code": null, "e": 25254, "s": 25122, "text": "Process: Instructions from intermediate code which are leaders are determined. Following are the rules used for finding a leader: " }, { "code": null, "e": 25539, "s": 25254, "text": "The first three-address instruction of the intermediate code is a leader. Instructions that are targets of unconditional or conditional jump/goto statements are leaders. Instructions that immediately follow unconditional or conditional jump/goto statements are considered leaders. " }, { "code": null, "e": 25615, "s": 25539, "text": "The first three-address instruction of the intermediate code is a leader. " }, { "code": null, "e": 25713, "s": 25615, "text": "Instructions that are targets of unconditional or conditional jump/goto statements are leaders. " }, { "code": null, "e": 25826, "s": 25713, "text": "Instructions that immediately follow unconditional or conditional jump/goto statements are considered leaders. " }, { "code": null, "e": 25945, "s": 25826, "text": "For each leader thus determined its basic block contains itself and all instructions up to excluding the next leader. " }, { "code": null, "e": 26018, "s": 25945, "text": "Example: Intermediate code to set a 10*10 matrix to an identity matrix: " }, { "code": null, "e": 26646, "s": 26020, "text": "1) i=1 //Leader 1 (First statement)\n2) j=1 //Leader 2 (Target of 11th statement)\n3) t1 = 10 * i //Leader 3 (Target of 9th statement) \n4) t2 = t1 + j\n5) t3 = 8 * t2\n6) t4 = t3 - 88\n7) a[t4] = 0.0\n8) j = j + 1\n9) if j <= goto (3) \n10) i = i + 1 //Leader 4 (Immediately following Conditional goto statement)\n11) if i <= 10 goto (2)\n12) i = 1 //Leader 5 (Immediately following Conditional goto statement)\n13) t5 = i - 1 //Leader 6 (Target of 17th statement) \n14) t6 = 88 * t5\n15) a[t6] = 1.0\n16) i = i + 1\n17) if i <= 10 goto (13) " }, { "code": null, "e": 26788, "s": 26646, "text": "The given algorithm is used to convert a matrix into identity matrix i.e. a matrix with all diagonal elements 1 and all other elements as 0. " }, { "code": null, "e": 26925, "s": 26788, "text": "Steps (3)-(6) are used to make elements 0, step (14) is used to make an element 1. These steps are used recursively by goto statements. " }, { "code": null, "e": 27078, "s": 26925, "text": "There are 6 Basic Blocks in the above code : B1) Statement 1 B2) Statement 2 B3) Statement 3-9 B4) Statement 10-11 B5) Statement 12 B6) Statement 13-17 " }, { "code": null, "e": 27088, "s": 27078, "text": "jatin7599" }, { "code": null, "e": 27100, "s": 27088, "text": "rajkumaar23" }, { "code": null, "e": 27117, "s": 27100, "text": "singhdrishti1001" }, { "code": null, "e": 27131, "s": 27117, "text": "mohansaitejat" }, { "code": null, "e": 27147, "s": 27131, "text": "Compiler Design" }, { "code": null, "e": 27155, "s": 27147, "text": "GATE CS" }, { "code": null, "e": 27253, "s": 27155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27311, "s": 27253, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 27369, "s": 27311, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 27406, "s": 27369, "text": "Loop Optimization in Compiler Design" }, { "code": null, "e": 27476, "s": 27406, "text": "S - attributed and L - attributed SDTs in Syntax directed translation" }, { "code": null, "e": 27504, "s": 27476, "text": "Compiler construction tools" }, { "code": null, "e": 27524, "s": 27504, "text": "Layers of OSI Model" }, { "code": null, "e": 27548, "s": 27524, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27561, "s": 27548, "text": "TCP/IP Model" }, { "code": null, "e": 27610, "s": 27561, "text": "Page Replacement Algorithms in Operating Systems" } ]
Java Swing | Internal Frame with examples - GeeksforGeeks
14 Apr, 2021 JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Constructors for JInternalFrame JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with no titleJInternalFrame(String t) :creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with a title specifiedJInternalFrame(String t, boolean resizable) :creates a new non- closable, non- iconifiable, non- maximizable JInternalFrame with a title and resizability specifiedJInternalFrame(String t, boolean resizable, boolean closable) : creates a new non- iconifiable, non- maximizable JInternalFrame with a title, closability and resizability specifiedJInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable) :creates a new non- iconifiable JInternalFrame with a title, closability, maximizability and resizability specified JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) : creates a new JInternalFrame with a title, closability, maximizability, iconifiability and resizability specified JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with no title JInternalFrame(String t) :creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with a title specified JInternalFrame(String t, boolean resizable) :creates a new non- closable, non- iconifiable, non- maximizable JInternalFrame with a title and resizability specified JInternalFrame(String t, boolean resizable, boolean closable) : creates a new non- iconifiable, non- maximizable JInternalFrame with a title, closability and resizability specified JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable) :creates a new non- iconifiable JInternalFrame with a title, closability, maximizability and resizability specified JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) : creates a new JInternalFrame with a title, closability, maximizability, iconifiability and resizability specified Commonly used methods setFrameIcon(Icon icon) : sets the icon for the frame to the specified imagesetLayout(LayoutManager manager) : sets the layout of the frame to specified layout managersetTitle(String t): set the title of the frame to specified titlegetTitle() : get the title of the framereshape(int x, int y, int width, int height) : resize the frame to specified width and height and a specified locationadd(Component c) : adds the specified component to the container.addImpl(Component c, Object co, int i) : adds the specified component.addInternalFrameListener(InternalFrameListener l) : adds the specified InternalFrameListener to the list.createRootPane() : called by the constructor to set up the JRootPane.dispose() : makes this internal frame invisible, unselected, and closed.fireInternalFrameEvent(int id) : fires an internal frame event.getAccessibleContext() : gets the AccessibleContext associated with this JInternalFrame.getContentPane() : returns the content pane for this internal frame.getDefaultCloseOperation() : returns the default operation that occurs when the user initiates a “close” on this internal frame.getDesktopIcon() : returns the JDesktopIcon used when this JInternalFrame is iconified.getDesktopPane() : convenience method that searches the ancestor hierarchy for a JDesktop instance.getFocusOwner() : If this JInternalFrame is active, returns the child that has focus.getFrameIcon() : returns the image displayed in the title bar of this internal framegetGlassPane() : returns the glass pane for this internal frame.getInternalFrameListeners() : Returns an array of all the InternalFrameListeners added to this JInternalFrame with addInternalFrameListenergetJMenuBar() : returns the current JMenuBar for this JInternalFramegetLastCursor() : returns the last Cursor that was set by the setCursor methodgetLayer() : convenience method for getting the layer attribute of this component.getLayeredPane() : returns the layered pane for this internal frame.getMostRecentFocusOwner() : returns the child component of this JInternalFrame that will receive the focus when this JInternalFrame is selected.getNormalBounds() : If the JInternalFrame is not in maximized state, returns getBounds(); otherwise, returns the bounds that the JInternalFrame would be restored to.getRootPane(): returns the rootPane object for this internal frame.getUI() : returns the look-and-feel object that renders this component.getWarningString() : gets the warning string that is displayed with this internal frame.isClosable() : returns whether this JInternalFrame can be closed by some user action.isClosed() : Returns whether this JInternalFrame is currently closed.isIcon() : returns whether the JInternalFrame is currently iconified.isMaximizable() : gets the value of the maximizable property.isMaximum() : returns whether the JInternalFrame is currently maximized.isResizable() : returns whether the JInternalFrame can be resized or not.isSelected() : returns whether the JInternalFrame is the currently active frame or not.pack() : causes components of this JInternalFrame to be laid out at their preferred size.paintComponent(Graphics g) : Overridden to allow optimized painting when the internal frame is being dragged.paramString() : Returns a string representation of this JInternalFrame.remove(Component c) : removes the specified component from the container.removeInternalFrameListener(InternalFrameListener l) : removes the specified internal frame listener.setClosable(boolean b) : sets whether this JInternalFrame can be closed by some user action.setContentPane(Container c) : sets this JInternalFrame’s contentPane property.setCursor(Cursor c) : sets the cursor image to the specified cursor.setDefaultCloseOperation(int o): sets the operation that will happen by default when the user initiates a “close” on this internal frame.setDesktopIcon(JInternalFrame.JDesktopIcon d) : sets the JDesktopIcon associated with this JInternalFrame.setGlassPane(Component g) : sets this JInternalFrame’s glassPane property.setIcon(boolean b) : Iconifies or de-iconifies this internal frame.setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame.setIconifiable(boolean b) : sets the iconable property, which must be true for the user to be able to make the JInternalFrame an icon.setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame.setLayer(int l) : convenience method for setting the layer attribute of this component.setLayer(Integer l) : convenience method for setting the layer attribute of this component.setLayeredPane(JLayeredPane l) : sets this JInternalFrame’s layeredPane property.setMaximizable(boolean b) : sets the maximizable property, which determines whether the JInternalFrame can be maximized by some user action.setMaximum(boolean b) : Maximizes and restores this internal frame.setNormalBounds(Rectangle r) : sets the normal bounds for this internal frame.setResizable(boolean b) :sets whether the JInternalFrame can be resized by some user action.setRootPane(JRootPane r) : sets the rootPane property for this JInternalFrame.setRootPaneCheckingEnabled(boolean e) : sets whether calls to add and setLayout are forwarded to the contentPane.setSelected(boolean s) : selects or deselects the internal frame if it’s showing.setUI(InternalFrameUI ui) : sets the UI delegate for this JInternalFrame.show() : makes the internal frame visible.toBack(): sends this internal frame to the back.toFront() : Brings this internal frame to the front.updateUI() : notification from the UIManager that the look and feel has changed. setFrameIcon(Icon icon) : sets the icon for the frame to the specified image setLayout(LayoutManager manager) : sets the layout of the frame to specified layout manager setTitle(String t): set the title of the frame to specified title getTitle() : get the title of the frame reshape(int x, int y, int width, int height) : resize the frame to specified width and height and a specified location add(Component c) : adds the specified component to the container. addImpl(Component c, Object co, int i) : adds the specified component. addInternalFrameListener(InternalFrameListener l) : adds the specified InternalFrameListener to the list. createRootPane() : called by the constructor to set up the JRootPane. dispose() : makes this internal frame invisible, unselected, and closed. fireInternalFrameEvent(int id) : fires an internal frame event. getAccessibleContext() : gets the AccessibleContext associated with this JInternalFrame. getContentPane() : returns the content pane for this internal frame. getDefaultCloseOperation() : returns the default operation that occurs when the user initiates a “close” on this internal frame. getDesktopIcon() : returns the JDesktopIcon used when this JInternalFrame is iconified. getDesktopPane() : convenience method that searches the ancestor hierarchy for a JDesktop instance. getFocusOwner() : If this JInternalFrame is active, returns the child that has focus. getFrameIcon() : returns the image displayed in the title bar of this internal frame getGlassPane() : returns the glass pane for this internal frame. getInternalFrameListeners() : Returns an array of all the InternalFrameListeners added to this JInternalFrame with addInternalFrameListener getJMenuBar() : returns the current JMenuBar for this JInternalFrame getLastCursor() : returns the last Cursor that was set by the setCursor method getLayer() : convenience method for getting the layer attribute of this component. getLayeredPane() : returns the layered pane for this internal frame. getMostRecentFocusOwner() : returns the child component of this JInternalFrame that will receive the focus when this JInternalFrame is selected. getNormalBounds() : If the JInternalFrame is not in maximized state, returns getBounds(); otherwise, returns the bounds that the JInternalFrame would be restored to. getRootPane(): returns the rootPane object for this internal frame. getUI() : returns the look-and-feel object that renders this component. getWarningString() : gets the warning string that is displayed with this internal frame. isClosable() : returns whether this JInternalFrame can be closed by some user action. isClosed() : Returns whether this JInternalFrame is currently closed. isIcon() : returns whether the JInternalFrame is currently iconified. isMaximizable() : gets the value of the maximizable property. isMaximum() : returns whether the JInternalFrame is currently maximized. isResizable() : returns whether the JInternalFrame can be resized or not. isSelected() : returns whether the JInternalFrame is the currently active frame or not. pack() : causes components of this JInternalFrame to be laid out at their preferred size. paintComponent(Graphics g) : Overridden to allow optimized painting when the internal frame is being dragged. paramString() : Returns a string representation of this JInternalFrame. remove(Component c) : removes the specified component from the container. removeInternalFrameListener(InternalFrameListener l) : removes the specified internal frame listener. setClosable(boolean b) : sets whether this JInternalFrame can be closed by some user action. setContentPane(Container c) : sets this JInternalFrame’s contentPane property. setCursor(Cursor c) : sets the cursor image to the specified cursor. setDefaultCloseOperation(int o): sets the operation that will happen by default when the user initiates a “close” on this internal frame. setDesktopIcon(JInternalFrame.JDesktopIcon d) : sets the JDesktopIcon associated with this JInternalFrame. setGlassPane(Component g) : sets this JInternalFrame’s glassPane property. setIcon(boolean b) : Iconifies or de-iconifies this internal frame. setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame. setIconifiable(boolean b) : sets the iconable property, which must be true for the user to be able to make the JInternalFrame an icon. setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame. setLayer(int l) : convenience method for setting the layer attribute of this component. setLayer(Integer l) : convenience method for setting the layer attribute of this component. setLayeredPane(JLayeredPane l) : sets this JInternalFrame’s layeredPane property. setMaximizable(boolean b) : sets the maximizable property, which determines whether the JInternalFrame can be maximized by some user action. setMaximum(boolean b) : Maximizes and restores this internal frame. setNormalBounds(Rectangle r) : sets the normal bounds for this internal frame. setResizable(boolean b) :sets whether the JInternalFrame can be resized by some user action. setRootPane(JRootPane r) : sets the rootPane property for this JInternalFrame. setRootPaneCheckingEnabled(boolean e) : sets whether calls to add and setLayout are forwarded to the contentPane. setSelected(boolean s) : selects or deselects the internal frame if it’s showing. setUI(InternalFrameUI ui) : sets the UI delegate for this JInternalFrame. show() : makes the internal frame visible. toBack(): sends this internal frame to the back. toFront() : Brings this internal frame to the front. updateUI() : notification from the UIManager that the look and feel has changed. 1. Program to create a simple JInternalFrame : Java // java Program to create a simple JInternalFrameimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solution extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // main class public static void main(String[] args) { // create a new frame to f = new JFrame("frame"); // create a internal frame JInternalFrame in = new JInternalFrame(); // set the title of the frame in.setTitle("InternalFrame"); // create a Button JButton b = new JButton("button"); // create a label to display text l = new JLabel("This is a JInternal Frame "); // create a panel JPanel p = new JPanel(); // add label and button to panel p.add(l); p.add(b); // set visibility internal frame in.setVisible(true); // add panel to internal frame in.add(p); // add internal frame to frame f.add(in); // set the size of frame f.setSize(300, 300); f.show(); }} Output : 2. program to create multiple internal frames Java // java Program to create multiple internal framesimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solution extends JFrame { // frame static JFrame f; // label to display text static JLabel l, l1; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // set layout of frame f.setLayout(new FlowLayout()); // create a internal frame JInternalFrame in = new JInternalFrame("frame 1", true, true, true, true); // create a internal frame JInternalFrame in1 = new JInternalFrame("frame 2", true, true, true, true); // create a Button JButton b = new JButton("button"); JButton b1 = new JButton("button1"); // create a label to display text l = new JLabel("This is a JInternal Frame no 1 "); l1 = new JLabel("This is a JInternal Frame no 2 "); // create a panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // add label and button to panel p.add(l); p.add(b); p1.add(l1); p1.add(b1); // set visibility internal frame in.setVisible(true); in1.setVisible(true); // add panel to internal frame in.add(p); in1.add(p1); // add internal frame to frame f.add(in); f.add(in1); // set the size of frame f.setSize(300, 300); f.show(); }} Output : 3 . Program to create multiple frame and set icon to the frame Java // java Program to create multiple frame and set icon to the frameimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solution extends JFrame { // frame static JFrame f; // label to display text static JLabel l, l1; // main class public static void main(String[] args) { // create a new frame f = new JFrame("frame"); // set layout of frame f.setLayout(new FlowLayout()); // create a internal frame JInternalFrame in = new JInternalFrame("frame 1", true, true, true, true); // create a internal frame JInternalFrame in1 = new JInternalFrame("frame 2", true, true, true, true); // set icon for internal frames in.setFrameIcon(new ImageIcon("f:/gfg.jpg")); in1.setFrameIcon(new ImageIcon("f:/gfg.jpg")); // create a Button JButton b = new JButton("button"); JButton b1 = new JButton("button1"); // create a label to display text l = new JLabel("This is a JInternal Frame no 1 "); l1 = new JLabel("This is a JInternal Frame no 2 "); // create a panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // add label and button to panel p.add(l); p.add(b); p1.add(l1); p1.add(b1); // set visibility internal frame in.setVisible(true); in1.setVisible(true); // add panel to internal frame in.add(p); in1.add(p1); // add internal frame to frame f.add(in); f.add(in1); // set the size of frame f.setSize(300, 300); f.show(); }} Output : Note : the above program might not run in an online compiler please use an offline IDE Akanksha_Rai sweetyty java-swing Java Java 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 Generics in Java Exceptions in Java Functional Interfaces in Java Comparator Interface in Java with Examples HashMap get() Method in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23948, "s": 23920, "text": "\n14 Apr, 2021" }, { "code": null, "e": 24180, "s": 23948, "text": "JInternalFrame is a part of Java Swing . JInternalFrame is a container that provides many features of a frame which includes displaying title, opening, closing, resizing, support for menu bar, etc. Constructors for JInternalFrame " }, { "code": null, "e": 25213, "s": 24180, "text": "JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with no titleJInternalFrame(String t) :creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with a title specifiedJInternalFrame(String t, boolean resizable) :creates a new non- closable, non- iconifiable, non- maximizable JInternalFrame with a title and resizability specifiedJInternalFrame(String t, boolean resizable, boolean closable) : creates a new non- iconifiable, non- maximizable JInternalFrame with a title, closability and resizability specifiedJInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable) :creates a new non- iconifiable JInternalFrame with a title, closability, maximizability and resizability specified JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) : creates a new JInternalFrame with a title, closability, maximizability, iconifiability and resizability specified" }, { "code": null, "e": 25341, "s": 25213, "text": "JInternalFrame() : creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with no title" }, { "code": null, "e": 25485, "s": 25341, "text": "JInternalFrame(String t) :creates a new non- closable, non- resizable, non- iconifiable, non- maximizable JInternalFrame with a title specified" }, { "code": null, "e": 25649, "s": 25485, "text": "JInternalFrame(String t, boolean resizable) :creates a new non- closable, non- iconifiable, non- maximizable JInternalFrame with a title and resizability specified" }, { "code": null, "e": 25830, "s": 25649, "text": "JInternalFrame(String t, boolean resizable, boolean closable) : creates a new non- iconifiable, non- maximizable JInternalFrame with a title, closability and resizability specified" }, { "code": null, "e": 26031, "s": 25830, "text": "JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable) :creates a new non- iconifiable JInternalFrame with a title, closability, maximizability and resizability specified " }, { "code": null, "e": 26251, "s": 26031, "text": "JInternalFrame(String t, boolean resizable, boolean closable, boolean maximizable, boolean iconifiable) : creates a new JInternalFrame with a title, closability, maximizability, iconifiability and resizability specified" }, { "code": null, "e": 26275, "s": 26251, "text": "Commonly used methods " }, { "code": null, "e": 31852, "s": 26275, "text": "setFrameIcon(Icon icon) : sets the icon for the frame to the specified imagesetLayout(LayoutManager manager) : sets the layout of the frame to specified layout managersetTitle(String t): set the title of the frame to specified titlegetTitle() : get the title of the framereshape(int x, int y, int width, int height) : resize the frame to specified width and height and a specified locationadd(Component c) : adds the specified component to the container.addImpl(Component c, Object co, int i) : adds the specified component.addInternalFrameListener(InternalFrameListener l) : adds the specified InternalFrameListener to the list.createRootPane() : called by the constructor to set up the JRootPane.dispose() : makes this internal frame invisible, unselected, and closed.fireInternalFrameEvent(int id) : fires an internal frame event.getAccessibleContext() : gets the AccessibleContext associated with this JInternalFrame.getContentPane() : returns the content pane for this internal frame.getDefaultCloseOperation() : returns the default operation that occurs when the user initiates a “close” on this internal frame.getDesktopIcon() : returns the JDesktopIcon used when this JInternalFrame is iconified.getDesktopPane() : convenience method that searches the ancestor hierarchy for a JDesktop instance.getFocusOwner() : If this JInternalFrame is active, returns the child that has focus.getFrameIcon() : returns the image displayed in the title bar of this internal framegetGlassPane() : returns the glass pane for this internal frame.getInternalFrameListeners() : Returns an array of all the InternalFrameListeners added to this JInternalFrame with addInternalFrameListenergetJMenuBar() : returns the current JMenuBar for this JInternalFramegetLastCursor() : returns the last Cursor that was set by the setCursor methodgetLayer() : convenience method for getting the layer attribute of this component.getLayeredPane() : returns the layered pane for this internal frame.getMostRecentFocusOwner() : returns the child component of this JInternalFrame that will receive the focus when this JInternalFrame is selected.getNormalBounds() : If the JInternalFrame is not in maximized state, returns getBounds(); otherwise, returns the bounds that the JInternalFrame would be restored to.getRootPane(): returns the rootPane object for this internal frame.getUI() : returns the look-and-feel object that renders this component.getWarningString() : gets the warning string that is displayed with this internal frame.isClosable() : returns whether this JInternalFrame can be closed by some user action.isClosed() : Returns whether this JInternalFrame is currently closed.isIcon() : returns whether the JInternalFrame is currently iconified.isMaximizable() : gets the value of the maximizable property.isMaximum() : returns whether the JInternalFrame is currently maximized.isResizable() : returns whether the JInternalFrame can be resized or not.isSelected() : returns whether the JInternalFrame is the currently active frame or not.pack() : causes components of this JInternalFrame to be laid out at their preferred size.paintComponent(Graphics g) : Overridden to allow optimized painting when the internal frame is being dragged.paramString() : Returns a string representation of this JInternalFrame.remove(Component c) : removes the specified component from the container.removeInternalFrameListener(InternalFrameListener l) : removes the specified internal frame listener.setClosable(boolean b) : sets whether this JInternalFrame can be closed by some user action.setContentPane(Container c) : sets this JInternalFrame’s contentPane property.setCursor(Cursor c) : sets the cursor image to the specified cursor.setDefaultCloseOperation(int o): sets the operation that will happen by default when the user initiates a “close” on this internal frame.setDesktopIcon(JInternalFrame.JDesktopIcon d) : sets the JDesktopIcon associated with this JInternalFrame.setGlassPane(Component g) : sets this JInternalFrame’s glassPane property.setIcon(boolean b) : Iconifies or de-iconifies this internal frame.setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame.setIconifiable(boolean b) : sets the iconable property, which must be true for the user to be able to make the JInternalFrame an icon.setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame.setLayer(int l) : convenience method for setting the layer attribute of this component.setLayer(Integer l) : convenience method for setting the layer attribute of this component.setLayeredPane(JLayeredPane l) : sets this JInternalFrame’s layeredPane property.setMaximizable(boolean b) : sets the maximizable property, which determines whether the JInternalFrame can be maximized by some user action.setMaximum(boolean b) : Maximizes and restores this internal frame.setNormalBounds(Rectangle r) : sets the normal bounds for this internal frame.setResizable(boolean b) :sets whether the JInternalFrame can be resized by some user action.setRootPane(JRootPane r) : sets the rootPane property for this JInternalFrame.setRootPaneCheckingEnabled(boolean e) : sets whether calls to add and setLayout are forwarded to the contentPane.setSelected(boolean s) : selects or deselects the internal frame if it’s showing.setUI(InternalFrameUI ui) : sets the UI delegate for this JInternalFrame.show() : makes the internal frame visible.toBack(): sends this internal frame to the back.toFront() : Brings this internal frame to the front.updateUI() : notification from the UIManager that the look and feel has changed." }, { "code": null, "e": 31929, "s": 31852, "text": "setFrameIcon(Icon icon) : sets the icon for the frame to the specified image" }, { "code": null, "e": 32021, "s": 31929, "text": "setLayout(LayoutManager manager) : sets the layout of the frame to specified layout manager" }, { "code": null, "e": 32087, "s": 32021, "text": "setTitle(String t): set the title of the frame to specified title" }, { "code": null, "e": 32127, "s": 32087, "text": "getTitle() : get the title of the frame" }, { "code": null, "e": 32246, "s": 32127, "text": "reshape(int x, int y, int width, int height) : resize the frame to specified width and height and a specified location" }, { "code": null, "e": 32312, "s": 32246, "text": "add(Component c) : adds the specified component to the container." }, { "code": null, "e": 32383, "s": 32312, "text": "addImpl(Component c, Object co, int i) : adds the specified component." }, { "code": null, "e": 32489, "s": 32383, "text": "addInternalFrameListener(InternalFrameListener l) : adds the specified InternalFrameListener to the list." }, { "code": null, "e": 32559, "s": 32489, "text": "createRootPane() : called by the constructor to set up the JRootPane." }, { "code": null, "e": 32632, "s": 32559, "text": "dispose() : makes this internal frame invisible, unselected, and closed." }, { "code": null, "e": 32696, "s": 32632, "text": "fireInternalFrameEvent(int id) : fires an internal frame event." }, { "code": null, "e": 32785, "s": 32696, "text": "getAccessibleContext() : gets the AccessibleContext associated with this JInternalFrame." }, { "code": null, "e": 32854, "s": 32785, "text": "getContentPane() : returns the content pane for this internal frame." }, { "code": null, "e": 32983, "s": 32854, "text": "getDefaultCloseOperation() : returns the default operation that occurs when the user initiates a “close” on this internal frame." }, { "code": null, "e": 33071, "s": 32983, "text": "getDesktopIcon() : returns the JDesktopIcon used when this JInternalFrame is iconified." }, { "code": null, "e": 33171, "s": 33071, "text": "getDesktopPane() : convenience method that searches the ancestor hierarchy for a JDesktop instance." }, { "code": null, "e": 33257, "s": 33171, "text": "getFocusOwner() : If this JInternalFrame is active, returns the child that has focus." }, { "code": null, "e": 33342, "s": 33257, "text": "getFrameIcon() : returns the image displayed in the title bar of this internal frame" }, { "code": null, "e": 33407, "s": 33342, "text": "getGlassPane() : returns the glass pane for this internal frame." }, { "code": null, "e": 33547, "s": 33407, "text": "getInternalFrameListeners() : Returns an array of all the InternalFrameListeners added to this JInternalFrame with addInternalFrameListener" }, { "code": null, "e": 33616, "s": 33547, "text": "getJMenuBar() : returns the current JMenuBar for this JInternalFrame" }, { "code": null, "e": 33695, "s": 33616, "text": "getLastCursor() : returns the last Cursor that was set by the setCursor method" }, { "code": null, "e": 33778, "s": 33695, "text": "getLayer() : convenience method for getting the layer attribute of this component." }, { "code": null, "e": 33847, "s": 33778, "text": "getLayeredPane() : returns the layered pane for this internal frame." }, { "code": null, "e": 33992, "s": 33847, "text": "getMostRecentFocusOwner() : returns the child component of this JInternalFrame that will receive the focus when this JInternalFrame is selected." }, { "code": null, "e": 34158, "s": 33992, "text": "getNormalBounds() : If the JInternalFrame is not in maximized state, returns getBounds(); otherwise, returns the bounds that the JInternalFrame would be restored to." }, { "code": null, "e": 34226, "s": 34158, "text": "getRootPane(): returns the rootPane object for this internal frame." }, { "code": null, "e": 34298, "s": 34226, "text": "getUI() : returns the look-and-feel object that renders this component." }, { "code": null, "e": 34387, "s": 34298, "text": "getWarningString() : gets the warning string that is displayed with this internal frame." }, { "code": null, "e": 34473, "s": 34387, "text": "isClosable() : returns whether this JInternalFrame can be closed by some user action." }, { "code": null, "e": 34543, "s": 34473, "text": "isClosed() : Returns whether this JInternalFrame is currently closed." }, { "code": null, "e": 34613, "s": 34543, "text": "isIcon() : returns whether the JInternalFrame is currently iconified." }, { "code": null, "e": 34675, "s": 34613, "text": "isMaximizable() : gets the value of the maximizable property." }, { "code": null, "e": 34748, "s": 34675, "text": "isMaximum() : returns whether the JInternalFrame is currently maximized." }, { "code": null, "e": 34822, "s": 34748, "text": "isResizable() : returns whether the JInternalFrame can be resized or not." }, { "code": null, "e": 34910, "s": 34822, "text": "isSelected() : returns whether the JInternalFrame is the currently active frame or not." }, { "code": null, "e": 35000, "s": 34910, "text": "pack() : causes components of this JInternalFrame to be laid out at their preferred size." }, { "code": null, "e": 35110, "s": 35000, "text": "paintComponent(Graphics g) : Overridden to allow optimized painting when the internal frame is being dragged." }, { "code": null, "e": 35182, "s": 35110, "text": "paramString() : Returns a string representation of this JInternalFrame." }, { "code": null, "e": 35256, "s": 35182, "text": "remove(Component c) : removes the specified component from the container." }, { "code": null, "e": 35358, "s": 35256, "text": "removeInternalFrameListener(InternalFrameListener l) : removes the specified internal frame listener." }, { "code": null, "e": 35451, "s": 35358, "text": "setClosable(boolean b) : sets whether this JInternalFrame can be closed by some user action." }, { "code": null, "e": 35530, "s": 35451, "text": "setContentPane(Container c) : sets this JInternalFrame’s contentPane property." }, { "code": null, "e": 35599, "s": 35530, "text": "setCursor(Cursor c) : sets the cursor image to the specified cursor." }, { "code": null, "e": 35737, "s": 35599, "text": "setDefaultCloseOperation(int o): sets the operation that will happen by default when the user initiates a “close” on this internal frame." }, { "code": null, "e": 35844, "s": 35737, "text": "setDesktopIcon(JInternalFrame.JDesktopIcon d) : sets the JDesktopIcon associated with this JInternalFrame." }, { "code": null, "e": 35919, "s": 35844, "text": "setGlassPane(Component g) : sets this JInternalFrame’s glassPane property." }, { "code": null, "e": 35987, "s": 35919, "text": "setIcon(boolean b) : Iconifies or de-iconifies this internal frame." }, { "code": null, "e": 36064, "s": 35987, "text": "setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame." }, { "code": null, "e": 36199, "s": 36064, "text": "setIconifiable(boolean b) : sets the iconable property, which must be true for the user to be able to make the JInternalFrame an icon." }, { "code": null, "e": 36276, "s": 36199, "text": "setJMenuBar(JMenuBar m) : sets the menuBar property for this JInternalFrame." }, { "code": null, "e": 36364, "s": 36276, "text": "setLayer(int l) : convenience method for setting the layer attribute of this component." }, { "code": null, "e": 36456, "s": 36364, "text": "setLayer(Integer l) : convenience method for setting the layer attribute of this component." }, { "code": null, "e": 36538, "s": 36456, "text": "setLayeredPane(JLayeredPane l) : sets this JInternalFrame’s layeredPane property." }, { "code": null, "e": 36679, "s": 36538, "text": "setMaximizable(boolean b) : sets the maximizable property, which determines whether the JInternalFrame can be maximized by some user action." }, { "code": null, "e": 36747, "s": 36679, "text": "setMaximum(boolean b) : Maximizes and restores this internal frame." }, { "code": null, "e": 36826, "s": 36747, "text": "setNormalBounds(Rectangle r) : sets the normal bounds for this internal frame." }, { "code": null, "e": 36919, "s": 36826, "text": "setResizable(boolean b) :sets whether the JInternalFrame can be resized by some user action." }, { "code": null, "e": 36998, "s": 36919, "text": "setRootPane(JRootPane r) : sets the rootPane property for this JInternalFrame." }, { "code": null, "e": 37112, "s": 36998, "text": "setRootPaneCheckingEnabled(boolean e) : sets whether calls to add and setLayout are forwarded to the contentPane." }, { "code": null, "e": 37194, "s": 37112, "text": "setSelected(boolean s) : selects or deselects the internal frame if it’s showing." }, { "code": null, "e": 37268, "s": 37194, "text": "setUI(InternalFrameUI ui) : sets the UI delegate for this JInternalFrame." }, { "code": null, "e": 37311, "s": 37268, "text": "show() : makes the internal frame visible." }, { "code": null, "e": 37360, "s": 37311, "text": "toBack(): sends this internal frame to the back." }, { "code": null, "e": 37413, "s": 37360, "text": "toFront() : Brings this internal frame to the front." }, { "code": null, "e": 37494, "s": 37413, "text": "updateUI() : notification from the UIManager that the look and feel has changed." }, { "code": null, "e": 37543, "s": 37494, "text": "1. Program to create a simple JInternalFrame : " }, { "code": null, "e": 37548, "s": 37543, "text": "Java" }, { "code": "// java Program to create a simple JInternalFrameimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solution extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // main class public static void main(String[] args) { // create a new frame to f = new JFrame(\"frame\"); // create a internal frame JInternalFrame in = new JInternalFrame(); // set the title of the frame in.setTitle(\"InternalFrame\"); // create a Button JButton b = new JButton(\"button\"); // create a label to display text l = new JLabel(\"This is a JInternal Frame \"); // create a panel JPanel p = new JPanel(); // add label and button to panel p.add(l); p.add(b); // set visibility internal frame in.setVisible(true); // add panel to internal frame in.add(p); // add internal frame to frame f.add(in); // set the size of frame f.setSize(300, 300); f.show(); }}", "e": 38628, "s": 37548, "text": null }, { "code": null, "e": 38639, "s": 38628, "text": "Output : " }, { "code": null, "e": 38687, "s": 38639, "text": "2. program to create multiple internal frames " }, { "code": null, "e": 38692, "s": 38687, "text": "Java" }, { "code": "// java Program to create multiple internal framesimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solution extends JFrame { // frame static JFrame f; // label to display text static JLabel l, l1; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // set layout of frame f.setLayout(new FlowLayout()); // create a internal frame JInternalFrame in = new JInternalFrame(\"frame 1\", true, true, true, true); // create a internal frame JInternalFrame in1 = new JInternalFrame(\"frame 2\", true, true, true, true); // create a Button JButton b = new JButton(\"button\"); JButton b1 = new JButton(\"button1\"); // create a label to display text l = new JLabel(\"This is a JInternal Frame no 1 \"); l1 = new JLabel(\"This is a JInternal Frame no 2 \"); // create a panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // add label and button to panel p.add(l); p.add(b); p1.add(l1); p1.add(b1); // set visibility internal frame in.setVisible(true); in1.setVisible(true); // add panel to internal frame in.add(p); in1.add(p1); // add internal frame to frame f.add(in); f.add(in1); // set the size of frame f.setSize(300, 300); f.show(); }}", "e": 40167, "s": 38692, "text": null }, { "code": null, "e": 40178, "s": 40167, "text": "Output : " }, { "code": null, "e": 40243, "s": 40178, "text": "3 . Program to create multiple frame and set icon to the frame " }, { "code": null, "e": 40248, "s": 40243, "text": "Java" }, { "code": "// java Program to create multiple frame and set icon to the frameimport java.awt.event.*;import java.awt.*;import javax.swing.*;class solution extends JFrame { // frame static JFrame f; // label to display text static JLabel l, l1; // main class public static void main(String[] args) { // create a new frame f = new JFrame(\"frame\"); // set layout of frame f.setLayout(new FlowLayout()); // create a internal frame JInternalFrame in = new JInternalFrame(\"frame 1\", true, true, true, true); // create a internal frame JInternalFrame in1 = new JInternalFrame(\"frame 2\", true, true, true, true); // set icon for internal frames in.setFrameIcon(new ImageIcon(\"f:/gfg.jpg\")); in1.setFrameIcon(new ImageIcon(\"f:/gfg.jpg\")); // create a Button JButton b = new JButton(\"button\"); JButton b1 = new JButton(\"button1\"); // create a label to display text l = new JLabel(\"This is a JInternal Frame no 1 \"); l1 = new JLabel(\"This is a JInternal Frame no 2 \"); // create a panel JPanel p = new JPanel(); JPanel p1 = new JPanel(); // add label and button to panel p.add(l); p.add(b); p1.add(l1); p1.add(b1); // set visibility internal frame in.setVisible(true); in1.setVisible(true); // add panel to internal frame in.add(p); in1.add(p1); // add internal frame to frame f.add(in); f.add(in1); // set the size of frame f.setSize(300, 300); f.show(); }}", "e": 41952, "s": 40248, "text": null }, { "code": null, "e": 41963, "s": 41952, "text": "Output : " }, { "code": null, "e": 42051, "s": 41963, "text": "Note : the above program might not run in an online compiler please use an offline IDE " }, { "code": null, "e": 42064, "s": 42051, "text": "Akanksha_Rai" }, { "code": null, "e": 42073, "s": 42064, "text": "sweetyty" }, { "code": null, "e": 42084, "s": 42073, "text": "java-swing" }, { "code": null, "e": 42089, "s": 42084, "text": "Java" }, { "code": null, "e": 42094, "s": 42089, "text": "Java" }, { "code": null, "e": 42192, "s": 42094, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42201, "s": 42192, "text": "Comments" }, { "code": null, "e": 42214, "s": 42201, "text": "Old Comments" }, { "code": null, "e": 42260, "s": 42214, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 42281, "s": 42260, "text": "Constructors in Java" }, { "code": null, "e": 42296, "s": 42281, "text": "Stream In Java" }, { "code": null, "e": 42313, "s": 42296, "text": "Generics in Java" }, { "code": null, "e": 42332, "s": 42313, "text": "Exceptions in Java" }, { "code": null, "e": 42362, "s": 42332, "text": "Functional Interfaces in Java" }, { "code": null, "e": 42405, "s": 42362, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 42434, "s": 42405, "text": "HashMap get() Method in Java" }, { "code": null, "e": 42450, "s": 42434, "text": "Strings in Java" } ]
Lua - Nested if statements
It is always legal in Lua programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s). The syntax for a nested if statement is as follows − if( boolean_expression 1) then --[ Executes when the boolean expression 1 is true --] if(boolean_expression 2) then --[ Executes when the boolean expression 2 is true --] end end You can nest else if...else in the similar way as you have nested if statement. --[ local variable definition --] a = 100; b = 200; --[ check the boolean condition --] if( a == 100 ) then --[ if condition is true then check the following --] if( b == 200 ) then --[ if condition is true then print the following --] print("Value of a is 100 and b is 200" ); end end print("Exact value of a is :", a ); print("Exact value of b is :", b ); When you build and run the above code, it produces the following result. Value of a is 100 and b is 200 Exact value of a is : 100 Exact value of b is : 200 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2264, "s": 2103, "text": "It is always legal in Lua programming to nest if-else statements, which means you can use one if or else if statement inside another if or else if statement(s)." }, { "code": null, "e": 2317, "s": 2264, "text": "The syntax for a nested if statement is as follows −" }, { "code": null, "e": 2515, "s": 2317, "text": "if( boolean_expression 1)\nthen\n --[ Executes when the boolean expression 1 is true --]\n if(boolean_expression 2)\n then\n --[ Executes when the boolean expression 2 is true --]\n end\nend\n" }, { "code": null, "e": 2595, "s": 2515, "text": "You can nest else if...else in the similar way as you have nested if statement." }, { "code": null, "e": 2980, "s": 2595, "text": "--[ local variable definition --]\na = 100;\nb = 200;\n\n--[ check the boolean condition --]\n\nif( a == 100 )\nthen\n --[ if condition is true then check the following --]\n if( b == 200 )\n then\n --[ if condition is true then print the following --]\n print(\"Value of a is 100 and b is 200\" );\n end\nend\n\nprint(\"Exact value of a is :\", a );\nprint(\"Exact value of b is :\", b );" }, { "code": null, "e": 3053, "s": 2980, "text": "When you build and run the above code, it produces the following result." }, { "code": null, "e": 3137, "s": 3053, "text": "Value of a is 100 and b is 200\nExact value of a is :\t100\nExact value of b is :\t200\n" }, { "code": null, "e": 3170, "s": 3137, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3184, "s": 3170, "text": " Manish Gupta" }, { "code": null, "e": 3217, "s": 3184, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 3233, "s": 3217, "text": " Sanjeev Mittal" }, { "code": null, "e": 3268, "s": 3233, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3284, "s": 3268, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 3291, "s": 3284, "text": " Print" }, { "code": null, "e": 3302, "s": 3291, "text": " Add Notes" } ]
Python - Replace multiple words with K - GeeksforGeeks
22 Apr, 2020 Sometimes, while working with Python strings, we can have a problem in which we need to perform a replace of multiple words with a single word. This can have application in many domains including day-day programming and school programming. Lets discuss certain ways in which this task can be performed. Method #1 : Using join() + split() + list comprehensionThe combination of above functions can be used to perform this task. In this, we split the string into words, check and replace the list words using join and list comprehension. # Python3 code to demonstrate working of # Replace multiple words with K# Using join() + split() + list comprehension # initializing stringtest_str = 'Geeksforgeeks is best for geeks and CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing word list word_list = ["best", 'CS', 'for'] # initializing replace word repl_wrd = 'gfg' # Replace multiple words with K# Using join() + split() + list comprehensionres = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()]) # printing result print("String after multiple replace : " + str(res)) The original string is : Geeksforgeeks is best for geeks and CS String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg Method #2 : Using regex + join()The combination of above functions can be used to perform this task. In this, we find the words using regex and perform the replace using join() and list comprehension. # Python3 code to demonstrate working of # Replace multiple words with K# Using regex + join()import re # initializing stringtest_str = 'Geeksforgeeks is best for geeks and CS' # printing original stringprint("The original string is : " + str(test_str)) # initializing word list word_list = ["best", 'CS', 'for'] # initializing replace word repl_wrd = 'gfg' # Replace multiple words with K# Using regex + join()res = re.sub("|".join(sorted(word_list, key = len, reverse = True)), repl_wrd, test_str) # printing result print("String after multiple replace : " + str(res)) The original string is : Geeksforgeeks is best for geeks and CS String after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python program to check whether a number is Prime or not Python | Convert a list to dictionary
[ { "code": null, "e": 23925, "s": 23897, "text": "\n22 Apr, 2020" }, { "code": null, "e": 24228, "s": 23925, "text": "Sometimes, while working with Python strings, we can have a problem in which we need to perform a replace of multiple words with a single word. This can have application in many domains including day-day programming and school programming. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 24461, "s": 24228, "text": "Method #1 : Using join() + split() + list comprehensionThe combination of above functions can be used to perform this task. In this, we split the string into words, check and replace the list words using join and list comprehension." }, { "code": "# Python3 code to demonstrate working of # Replace multiple words with K# Using join() + split() + list comprehension # initializing stringtest_str = 'Geeksforgeeks is best for geeks and CS' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing word list word_list = [\"best\", 'CS', 'for'] # initializing replace word repl_wrd = 'gfg' # Replace multiple words with K# Using join() + split() + list comprehensionres = ' '.join([repl_wrd if idx in word_list else idx for idx in test_str.split()]) # printing result print(\"String after multiple replace : \" + str(res)) ", "e": 25071, "s": 24461, "text": null }, { "code": null, "e": 25207, "s": 25071, "text": "The original string is : Geeksforgeeks is best for geeks and CS\nString after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg\n" }, { "code": null, "e": 25410, "s": 25209, "text": "Method #2 : Using regex + join()The combination of above functions can be used to perform this task. In this, we find the words using regex and perform the replace using join() and list comprehension." }, { "code": "# Python3 code to demonstrate working of # Replace multiple words with K# Using regex + join()import re # initializing stringtest_str = 'Geeksforgeeks is best for geeks and CS' # printing original stringprint(\"The original string is : \" + str(test_str)) # initializing word list word_list = [\"best\", 'CS', 'for'] # initializing replace word repl_wrd = 'gfg' # Replace multiple words with K# Using regex + join()res = re.sub(\"|\".join(sorted(word_list, key = len, reverse = True)), repl_wrd, test_str) # printing result print(\"String after multiple replace : \" + str(res)) ", "e": 25988, "s": 25410, "text": null }, { "code": null, "e": 26124, "s": 25988, "text": "The original string is : Geeksforgeeks is best for geeks and CS\nString after multiple replace : Geeksforgeeks is gfg gfg geeks and gfg\n" }, { "code": null, "e": 26147, "s": 26124, "text": "Python string-programs" }, { "code": null, "e": 26154, "s": 26147, "text": "Python" }, { "code": null, "e": 26170, "s": 26154, "text": "Python Programs" }, { "code": null, "e": 26268, "s": 26170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26277, "s": 26268, "text": "Comments" }, { "code": null, "e": 26290, "s": 26277, "text": "Old Comments" }, { "code": null, "e": 26322, "s": 26290, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26378, "s": 26322, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26420, "s": 26378, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26462, "s": 26420, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26498, "s": 26462, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 26520, "s": 26498, "text": "Defaultdict in Python" }, { "code": null, "e": 26559, "s": 26520, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26605, "s": 26559, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26662, "s": 26605, "text": "Python program to check whether a number is Prime or not" } ]
Thread Interference and Memory Consistency Errors in Java - GeeksforGeeks
29 Mar, 2019 Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables.When Two threads access the same shared memory This communication in multithreading can cause two types of errors, if not implemented properly: Thread interferenceMemory inconsistency Thread interference Memory inconsistency When multiple threads share the same memory, there is a chance that two or more different threads performing different operations on the same data interleave with each other and create inconsistent data in the memory. Threads interleave when they are performing operations with multiple steps and their sequence of steps overlap. This is called thread interference. Even for a small operation like incrementing or decrementing the value of a variable (say i) using the statement i++ or i–, the virtual machine performs multiple steps as follows: Retrieve the value of i from the memoryIncrement/Decrement the value of i by 1Store the new incremented/decremented value of i back to the memory Retrieve the value of i from the memory Increment/Decrement the value of i by 1 Store the new incremented/decremented value of i back to the memory If there are two threads A and B operating on the same object, A performs the increment operation and B performs decrement operation at the same time, it might lead to data inconsistency. If the initial value of i is 10. Thread A reads the value of i from the memory as 10 and increments its value to 11. Before it could store the new value to the memory, thread B reads the value of i from the memory as 10, since the memory has not been updated yet. Now, thread B decrements the value of i to 9. The new value in the memory now would be either 9 or 11, where the expected value was actually 10. Either one of the thread’s result may be lost and overwritten by the other or there could be no error at all. Being unpredictable, thread interference bugs are difficult to detect and fix. Sequence diagram for thread interference error Example: // Java program to explain the// concept of thread interference.import java.io.*; // Creating thread by creating the// objects of that classclass SharedClass { static int i=10; void increment() { for(int j=0;j<50;j++) { // incrementing value of i i=i+1; System.out.println("i after increment "+i); } } void decrement() { for(int j=0;j<50;j++) { // decrementing value of i i=i-1; System.out.println("i after decrement "+i); } }} class GFG { public static void main(String[] args) { final SharedClass s1 = new SharedClass(); Thread t1 = new Thread() { @Override public void run() { s1.increment(); } }; Thread t2 = new Thread() { @Override public void run() { s1.decrement(); } }; t1.start(); t2.start(); }} In the above code the last line of the expected output should be either “i after increment 10” or “i after decrement 10”, but the actual output may vary due to the interference of the threads. Thread interference is unpredictable, try running the above code several times to find the thread interference error in some cases. The interleaving thread operations would be evidently seen. How to avoid thread interference errorThread interference can be avoided by making the code thread-safe through: Synchronization Access restriction on the same object by multiple threads Declaring the variable as final. Declaring the variable as volatile. Creating immutable objects. In multithreading, there can be possibilities that the changes made by one thread might not be visible to the other threads and they all have inconsistent views of the same shared data. This is known as memory consistency error. Memory consistency is more of an architecture-based concept than Java-based. Accesses to main memory might not occur in the same order in which the CPU initiated them, especially for write operations which often go through hardware write buffers so that the CPU need not wait for them. CPUs guarantee that the order of writes to a single memory location is maintained from the perspective of all CPUs, even if CPUs perceive the write time of other CPUs differently than the actual time. This sometimes leads to memory inconsistency due to lack of visibility of the correct data. Sequence diagram for memory consistency error How to avoid memory consistency errorsMemory consistency errors can be avoided by establishing a happens-before relationship. This relationship guarantees that memory writes operation performed by one thread is visible to a read operation by any other thread on the same shared memory. The following actions can create a happens-before relationship: Thread.start() – This statement makes the effects of code that led up to the creation of the new thread visible to the new thread. Thread.join() – This statement makes the effects of the code in the thread visible to the thread that performed the join. Prashasti Baranwal java-basics Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java How to remove an element from ArrayList in Java? Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 23583, "s": 23555, "text": "\n29 Mar, 2019" }, { "code": null, "e": 23893, "s": 23583, "text": "Java allows multithreading which involves concurrent execution of two or more parts of the program. It enhances CPU utilization by performing multiple tasks simultaneously. The threads communicate with each other by sharing object references and member variables.When Two threads access the same shared memory" }, { "code": null, "e": 23990, "s": 23893, "text": "This communication in multithreading can cause two types of errors, if not implemented properly:" }, { "code": null, "e": 24030, "s": 23990, "text": "Thread interferenceMemory inconsistency" }, { "code": null, "e": 24050, "s": 24030, "text": "Thread interference" }, { "code": null, "e": 24071, "s": 24050, "text": "Memory inconsistency" }, { "code": null, "e": 24437, "s": 24071, "text": "When multiple threads share the same memory, there is a chance that two or more different threads performing different operations on the same data interleave with each other and create inconsistent data in the memory. Threads interleave when they are performing operations with multiple steps and their sequence of steps overlap. This is called thread interference." }, { "code": null, "e": 24617, "s": 24437, "text": "Even for a small operation like incrementing or decrementing the value of a variable (say i) using the statement i++ or i–, the virtual machine performs multiple steps as follows:" }, { "code": null, "e": 24763, "s": 24617, "text": "Retrieve the value of i from the memoryIncrement/Decrement the value of i by 1Store the new incremented/decremented value of i back to the memory" }, { "code": null, "e": 24803, "s": 24763, "text": "Retrieve the value of i from the memory" }, { "code": null, "e": 24843, "s": 24803, "text": "Increment/Decrement the value of i by 1" }, { "code": null, "e": 24911, "s": 24843, "text": "Store the new incremented/decremented value of i back to the memory" }, { "code": null, "e": 25697, "s": 24911, "text": "If there are two threads A and B operating on the same object, A performs the increment operation and B performs decrement operation at the same time, it might lead to data inconsistency. If the initial value of i is 10. Thread A reads the value of i from the memory as 10 and increments its value to 11. Before it could store the new value to the memory, thread B reads the value of i from the memory as 10, since the memory has not been updated yet. Now, thread B decrements the value of i to 9. The new value in the memory now would be either 9 or 11, where the expected value was actually 10. Either one of the thread’s result may be lost and overwritten by the other or there could be no error at all. Being unpredictable, thread interference bugs are difficult to detect and fix." }, { "code": null, "e": 25744, "s": 25697, "text": "Sequence diagram for thread interference error" }, { "code": null, "e": 25753, "s": 25744, "text": "Example:" }, { "code": "// Java program to explain the// concept of thread interference.import java.io.*; // Creating thread by creating the// objects of that classclass SharedClass { static int i=10; void increment() { for(int j=0;j<50;j++) { // incrementing value of i i=i+1; System.out.println(\"i after increment \"+i); } } void decrement() { for(int j=0;j<50;j++) { // decrementing value of i i=i-1; System.out.println(\"i after decrement \"+i); } }} class GFG { public static void main(String[] args) { final SharedClass s1 = new SharedClass(); Thread t1 = new Thread() { @Override public void run() { s1.increment(); } }; Thread t2 = new Thread() { @Override public void run() { s1.decrement(); } }; t1.start(); t2.start(); }}", "e": 26790, "s": 25753, "text": null }, { "code": null, "e": 27175, "s": 26790, "text": "In the above code the last line of the expected output should be either “i after increment 10” or “i after decrement 10”, but the actual output may vary due to the interference of the threads. Thread interference is unpredictable, try running the above code several times to find the thread interference error in some cases. The interleaving thread operations would be evidently seen." }, { "code": null, "e": 27288, "s": 27175, "text": "How to avoid thread interference errorThread interference can be avoided by making the code thread-safe through:" }, { "code": null, "e": 27304, "s": 27288, "text": "Synchronization" }, { "code": null, "e": 27362, "s": 27304, "text": "Access restriction on the same object by multiple threads" }, { "code": null, "e": 27395, "s": 27362, "text": "Declaring the variable as final." }, { "code": null, "e": 27431, "s": 27395, "text": "Declaring the variable as volatile." }, { "code": null, "e": 27459, "s": 27431, "text": "Creating immutable objects." }, { "code": null, "e": 27688, "s": 27459, "text": "In multithreading, there can be possibilities that the changes made by one thread might not be visible to the other threads and they all have inconsistent views of the same shared data. This is known as memory consistency error." }, { "code": null, "e": 28267, "s": 27688, "text": "Memory consistency is more of an architecture-based concept than Java-based. Accesses to main memory might not occur in the same order in which the CPU initiated them, especially for write operations which often go through hardware write buffers so that the CPU need not wait for them. CPUs guarantee that the order of writes to a single memory location is maintained from the perspective of all CPUs, even if CPUs perceive the write time of other CPUs differently than the actual time. This sometimes leads to memory inconsistency due to lack of visibility of the correct data." }, { "code": null, "e": 28313, "s": 28267, "text": "Sequence diagram for memory consistency error" }, { "code": null, "e": 28599, "s": 28313, "text": "How to avoid memory consistency errorsMemory consistency errors can be avoided by establishing a happens-before relationship. This relationship guarantees that memory writes operation performed by one thread is visible to a read operation by any other thread on the same shared memory." }, { "code": null, "e": 28663, "s": 28599, "text": "The following actions can create a happens-before relationship:" }, { "code": null, "e": 28794, "s": 28663, "text": "Thread.start() – This statement makes the effects of code that led up to the creation of the new thread visible to the new thread." }, { "code": null, "e": 28916, "s": 28794, "text": "Thread.join() – This statement makes the effects of the code in the thread visible to the thread that performed the join." }, { "code": null, "e": 28935, "s": 28916, "text": "Prashasti Baranwal" }, { "code": null, "e": 28947, "s": 28935, "text": "java-basics" }, { "code": null, "e": 28967, "s": 28947, "text": "Java-Multithreading" }, { "code": null, "e": 28972, "s": 28967, "text": "Java" }, { "code": null, "e": 28977, "s": 28972, "text": "Java" }, { "code": null, "e": 29075, "s": 28977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29084, "s": 29075, "text": "Comments" }, { "code": null, "e": 29097, "s": 29084, "text": "Old Comments" }, { "code": null, "e": 29127, "s": 29097, "text": "Functional Interfaces in Java" }, { "code": null, "e": 29142, "s": 29127, "text": "Stream In Java" }, { "code": null, "e": 29163, "s": 29142, "text": "Constructors in Java" }, { "code": null, "e": 29209, "s": 29163, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 29228, "s": 29209, "text": "Exceptions in Java" }, { "code": null, "e": 29245, "s": 29228, "text": "Generics in Java" }, { "code": null, "e": 29288, "s": 29245, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 29304, "s": 29288, "text": "Strings in Java" }, { "code": null, "e": 29353, "s": 29304, "text": "How to remove an element from ArrayList in Java?" } ]
What is Bitwise OR Operator (|) in JavaScript?
It performs a Boolean OR operation on each bit of its integer arguments. You can try to run the following code to learn how to work with Bitwise OR Operator (|) − <html> <body> <script> var a = 2; // Bit presentation 10 var b = 3; // Bit presentation 11 document.write("(a | b) => "); result = (a | b); document.write(result); </script> </body> </html>
[ { "code": null, "e": 1135, "s": 1062, "text": "It performs a Boolean OR operation on each bit of its integer arguments." }, { "code": null, "e": 1225, "s": 1135, "text": "You can try to run the following code to learn how to work with Bitwise OR Operator (|) −" }, { "code": null, "e": 1479, "s": 1225, "text": "<html>\n <body>\n <script>\n var a = 2; // Bit presentation 10\n var b = 3; // Bit presentation 11\n\n document.write(\"(a | b) => \");\n result = (a | b);\n document.write(result);\n </script>\n </body>\n</html>" } ]
Creating Alternative Truths with Sine Activation Function in Neural Networks | by Tekin Evrim Ozmermer | Towards Data Science
Hello! Today, I am going to talk about using sine function as activation in neural networks. I will try to answer the questions “What is it?”,“How can it change the future of neural networks?”, “What are the weak sides of this approach?” I will also demonstrate one example at the end. As you may have heard before from thousands of publications, the neural networks are using monotonic functions which are mapping the output of neural network between 0 and 1. This is the right approach since these activation functions give probability-like outputs. But, the disadvantage of this approach is there is only one truth and one wrong for the outputs. But in real life, completely different values may give the same output for an event. So, instead of trying to approach to a small domain of values to get the truth, we need to be able to reach multiple domains of values to get the truth. The paper “Neural networks with periodic and monotonic activation functions: a comparative study in classification problems” written by Josep M.Sopena, Enrique Romero, Rene Alquezar also claims the approach that we use sine activation. The figure below demonstrates the multiple probabilities. A unit with a non-monotonic activation function can divide the space into more than two regions. If the function is periodic, the number of regions is infinite, and it can be interpreted as a wave front spreading through the space of variables. As we can see from the figure, the output of sigmoid function can be 1 only for a specific value. But, the output of sine function can be 1 for infinite times. This, practically, means that if the neural network that should give output 1 for x and x+100 inputs, we can approach the function of model to y(x)=1 and y(x+100)=1 by using sin(x) and sin(x+100). If we would not use sin function, our network has to adjust its weights and biases so that they can map x and x+100 to a range between 0 and 1. It is proved that neural network with monotonic functions are giving satisfactory results. But the real problem of them is training. They are trained so slow because the number of parameters that the network should adjust are reaching to millions. If we would use sin function as the activation, the number of adjustments that the network should make would be less. So, the training times of the networks would decrease significantly. This could reduce the cost of training of neural network models. Uncertainty and easy over-fitting. Because the network with sine activation function is adjusting the weights easily and fast, it also causes over-fitting. Not to over-fit the network, we need to give a small learning rate to the model so that we can prevent over-fitting. Mapping the output of network to infinite probability space is actually increasing the uncertainty. The adjustments for one value may cause the other value to map to a hugely different probability. There can be sure different implementations for the forward and backward operation of sine activation function. I just tried the one that I had in my mind. def error_function_for_sin_single(output,y): to_search_best = np.sin(np.linspace(output-1,output+1,10000)*np.pi/2) index = np.argmin(np.abs(to_search_best-y)) to_be = np.linspace(output-1,output+1,10000)[index] error = to_be-output #print("to be:",to_be,"as is",output,"error",error/10) return errordef error_function_for_sin_multiple(self,output,y): derror_doutput = [] for cnt in range(y.shape[0]): derror_doutput.append(self.error_function_for_sin_single( output[cnt], y[cnt])) derror_doutput = np.array(derror_doutput) #print("____________") return derror_doutput/2 Assume that we have an output array(output) such as [o1,o2,o3,...] which is still not activated by sine function. And we have “to-be” array(y) Firstly, we take each element from array by for loop in error_function_for_sin_multiple function. Then, call error_function_for_sin_single function with the element we took from the array. In error_function_for_sin_single function, we calculate the sine function around the output value(to_search_max). (I multiplied output with pi/2 in sine function because I want value one to be pi/2 which will later map to value 1 as an output of sine function.) Then we find the index of smallest error by calculating the differences between y and to_search_best. The index giving the least error is actually the value that the output should be. So, we find the difference between this value and output so that we can feed back back to neural network for back-propagation. After we find the errors, we append them to a list to give them all to back-propagation. Data-set: MNIST Digit Dagaset Algorithm: Feed-forward neural networks using sine basis function Layers: Input = 4704 (I do basic feature extraction, that’s why it is not 784), L1 = 512, L2: 128, Output: 10 Learning rate: 0.0000001 I tried to over-train the model to map an image to its label to measure the least epoch. Also, the paper I mentioned above has several experiments for sine activation function. One of them is for “spiral problem.” The results from the paper: Standard BP with a simple architecture has not found a solution to this problem (see [Fahlman and Labiere, 1990]). [Lang and Witbrock, 1988] solved it in 20,000 epochs using standard BP with a complex architecture (2–5–5–5–1 with shortcuts). “Supersab” needed an average of 3,500 epochs, “Quickprop” 8,000, “RPROP” 6,000, and “Cascade Correlation” 1,700. To solve this problem we constructed a network with architecture 2–16–1, using the sine as the activation function in the hidden layer, and the hyperbolic tangent in the output layer. This architecture is the simplest of those used to date to deal with this problem. Results are shown in table 1. The importance of the range of initial weights is clear. With small ranges for the non-linear parameters learning is not possible (see two first rows in table 1 I hope that you enjoyed reading this post. While everybody is talking about extremely complex neural networks that are finding solutions to complex problems, I believe that we should still examine the base algorithms of neural networks. Because the changes in fundamentals bring greater impact.
[ { "code": null, "e": 458, "s": 172, "text": "Hello! Today, I am going to talk about using sine function as activation in neural networks. I will try to answer the questions “What is it?”,“How can it change the future of neural networks?”, “What are the weak sides of this approach?” I will also demonstrate one example at the end." }, { "code": null, "e": 1059, "s": 458, "text": "As you may have heard before from thousands of publications, the neural networks are using monotonic functions which are mapping the output of neural network between 0 and 1. This is the right approach since these activation functions give probability-like outputs. But, the disadvantage of this approach is there is only one truth and one wrong for the outputs. But in real life, completely different values may give the same output for an event. So, instead of trying to approach to a small domain of values to get the truth, we need to be able to reach multiple domains of values to get the truth." }, { "code": null, "e": 1353, "s": 1059, "text": "The paper “Neural networks with periodic and monotonic activation functions: a comparative study in classification problems” written by Josep M.Sopena, Enrique Romero, Rene Alquezar also claims the approach that we use sine activation. The figure below demonstrates the multiple probabilities." }, { "code": null, "e": 1598, "s": 1353, "text": "A unit with a non-monotonic activation function can divide the space into more than two regions. If the function is periodic, the number of regions is infinite, and it can be interpreted as a wave front spreading through the space of variables." }, { "code": null, "e": 2099, "s": 1598, "text": "As we can see from the figure, the output of sigmoid function can be 1 only for a specific value. But, the output of sine function can be 1 for infinite times. This, practically, means that if the neural network that should give output 1 for x and x+100 inputs, we can approach the function of model to y(x)=1 and y(x+100)=1 by using sin(x) and sin(x+100). If we would not use sin function, our network has to adjust its weights and biases so that they can map x and x+100 to a range between 0 and 1." }, { "code": null, "e": 2599, "s": 2099, "text": "It is proved that neural network with monotonic functions are giving satisfactory results. But the real problem of them is training. They are trained so slow because the number of parameters that the network should adjust are reaching to millions. If we would use sin function as the activation, the number of adjustments that the network should make would be less. So, the training times of the networks would decrease significantly. This could reduce the cost of training of neural network models." }, { "code": null, "e": 3070, "s": 2599, "text": "Uncertainty and easy over-fitting. Because the network with sine activation function is adjusting the weights easily and fast, it also causes over-fitting. Not to over-fit the network, we need to give a small learning rate to the model so that we can prevent over-fitting. Mapping the output of network to infinite probability space is actually increasing the uncertainty. The adjustments for one value may cause the other value to map to a hugely different probability." }, { "code": null, "e": 3226, "s": 3070, "text": "There can be sure different implementations for the forward and backward operation of sine activation function. I just tried the one that I had in my mind." }, { "code": null, "e": 3836, "s": 3226, "text": "def error_function_for_sin_single(output,y): to_search_best = np.sin(np.linspace(output-1,output+1,10000)*np.pi/2) index = np.argmin(np.abs(to_search_best-y)) to_be = np.linspace(output-1,output+1,10000)[index] error = to_be-output #print(\"to be:\",to_be,\"as is\",output,\"error\",error/10) return errordef error_function_for_sin_multiple(self,output,y): derror_doutput = [] for cnt in range(y.shape[0]): derror_doutput.append(self.error_function_for_sin_single( output[cnt], y[cnt])) derror_doutput = np.array(derror_doutput) #print(\"____________\") return derror_doutput/2" }, { "code": null, "e": 3979, "s": 3836, "text": "Assume that we have an output array(output) such as [o1,o2,o3,...] which is still not activated by sine function. And we have “to-be” array(y)" }, { "code": null, "e": 4077, "s": 3979, "text": "Firstly, we take each element from array by for loop in error_function_for_sin_multiple function." }, { "code": null, "e": 4168, "s": 4077, "text": "Then, call error_function_for_sin_single function with the element we took from the array." }, { "code": null, "e": 4430, "s": 4168, "text": "In error_function_for_sin_single function, we calculate the sine function around the output value(to_search_max). (I multiplied output with pi/2 in sine function because I want value one to be pi/2 which will later map to value 1 as an output of sine function.)" }, { "code": null, "e": 4532, "s": 4430, "text": "Then we find the index of smallest error by calculating the differences between y and to_search_best." }, { "code": null, "e": 4741, "s": 4532, "text": "The index giving the least error is actually the value that the output should be. So, we find the difference between this value and output so that we can feed back back to neural network for back-propagation." }, { "code": null, "e": 4830, "s": 4741, "text": "After we find the errors, we append them to a list to give them all to back-propagation." }, { "code": null, "e": 4860, "s": 4830, "text": "Data-set: MNIST Digit Dagaset" }, { "code": null, "e": 4926, "s": 4860, "text": "Algorithm: Feed-forward neural networks using sine basis function" }, { "code": null, "e": 5036, "s": 4926, "text": "Layers: Input = 4704 (I do basic feature extraction, that’s why it is not 784), L1 = 512, L2: 128, Output: 10" }, { "code": null, "e": 5061, "s": 5036, "text": "Learning rate: 0.0000001" }, { "code": null, "e": 5150, "s": 5061, "text": "I tried to over-train the model to map an image to its label to measure the least epoch." }, { "code": null, "e": 5275, "s": 5150, "text": "Also, the paper I mentioned above has several experiments for sine activation function. One of them is for “spiral problem.”" }, { "code": null, "e": 5303, "s": 5275, "text": "The results from the paper:" }, { "code": null, "e": 6116, "s": 5303, "text": "Standard BP with a simple architecture has not found a solution to this problem (see [Fahlman and Labiere, 1990]). [Lang and Witbrock, 1988] solved it in 20,000 epochs using standard BP with a complex architecture (2–5–5–5–1 with shortcuts). “Supersab” needed an average of 3,500 epochs, “Quickprop” 8,000, “RPROP” 6,000, and “Cascade Correlation” 1,700. To solve this problem we constructed a network with architecture 2–16–1, using the sine as the activation function in the hidden layer, and the hyperbolic tangent in the output layer. This architecture is the simplest of those used to date to deal with this problem. Results are shown in table 1. The importance of the range of initial weights is clear. With small ranges for the non-linear parameters learning is not possible (see two first rows in table 1" } ]