title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How can I stop running a MySQL query?
Before stopping a running query of MySQL, first we need to see how many processes are running with the help of show command. The query for that is given as follows − mysql> show processlist; After executing the above query, we will get the output with some id’s. This is given as follows − +----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+ | 4 | event_scheduler | localhost | NULL | Daemon | 71034 | Waiting on empty queue | NULL | | 8 | Manish | localhost:53496 | business | Query | 0 | starting |show processlist| +----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+ 2 rows in set (0.00 sec) As seen from the above output, the db currently in use is ‘business’. and its id is 8. To stop the query the command call can be used with the given id that is in process list. The syntax for that is as follows − call mysql.rds_kill(valueOfGivenIdInProcesslist); Now, the above syntax is applied to the query and valueOfGivenIdInProcesslist is put as 8. This is shown below − mysql> CALL mysql.rds_kill(8); After executing the above query, the following output is obtained − ERROR 2013 (HY000): Lost connection to MySQL server during query This happens as the above query stops running. The use command is used to check if it has stopped or not. The syntax for that is as follows − use yourDatabaseName; The above syntax is applied to the mydatabase name ‘business’ in the system. The query is as follows − mysql> use business; After executing the above query, the following output is obtained − No connection. Trying to reconnect... Connection id: 10 Current database: *** NONE *** Database changed mysql> So, it is clear that the query has stopped because the message is coming “Trying to reconnect...” in MySQL. And it is also showing that the current database is “none”. After some time the connection with the database is resumed.
[ { "code": null, "e": 1187, "s": 1062, "text": "Before stopping a running query of MySQL, first we need to see how many processes are\nrunning with the help of show command." }, { "code": null, "e": 1228, "s": 1187, "text": "The query for that is given as follows −" }, { "code": null, "e": 1253, "s": 1228, "text": "mysql> show processlist;" }, { "code": null, "e": 1352, "s": 1253, "text": "After executing the above query, we will get the output with some id’s. This is given as follows −" }, { "code": null, "e": 1959, "s": 1352, "text": "+----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+\n| Id | User | Host | db | Command | Time | State | Info |\n+----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+\n| 4 | event_scheduler | localhost | NULL | Daemon | 71034 | Waiting on empty queue |\nNULL |\n| 8 | Manish | localhost:53496 | business | Query | 0 | starting |show processlist|\n+----+-----------------+-----------------+----------+---------+-------+------------------------+------------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 2172, "s": 1959, "text": "As seen from the above output, the db currently in use is ‘business’. and its id is 8. To stop the\nquery the command call can be used with the given id that is in process list. The syntax for that\nis as follows −" }, { "code": null, "e": 2223, "s": 2172, "text": "call mysql.rds_kill(valueOfGivenIdInProcesslist);\n" }, { "code": null, "e": 2336, "s": 2223, "text": "Now, the above syntax is applied to the query and valueOfGivenIdInProcesslist is put as 8. This\nis shown below −" }, { "code": null, "e": 2367, "s": 2336, "text": "mysql> CALL mysql.rds_kill(8);" }, { "code": null, "e": 2435, "s": 2367, "text": "After executing the above query, the following output is obtained −" }, { "code": null, "e": 2501, "s": 2435, "text": "ERROR 2013 (HY000): Lost connection to MySQL server during query\n" }, { "code": null, "e": 2643, "s": 2501, "text": "This happens as the above query stops running. The use command is used to check if it has\nstopped or not. The syntax for that is as follows −" }, { "code": null, "e": 2665, "s": 2643, "text": "use yourDatabaseName;" }, { "code": null, "e": 2768, "s": 2665, "text": "The above syntax is applied to the mydatabase name ‘business’ in the system. The query is as\nfollows −" }, { "code": null, "e": 2790, "s": 2768, "text": "mysql> use business;\n" }, { "code": null, "e": 2858, "s": 2790, "text": "After executing the above query, the following output is obtained −" }, { "code": null, "e": 2972, "s": 2858, "text": "No connection. Trying to reconnect...\nConnection id: 10\nCurrent database: *** NONE ***\n\n\n\nDatabase changed\nmysql>" }, { "code": null, "e": 3201, "s": 2972, "text": "So, it is clear that the query has stopped because the message is coming “Trying to\nreconnect...” in MySQL. And it is also showing that the current database is “none”. After some\ntime the connection with the database is resumed." } ]
Convert min Heap to max Heap in C++
In this tutorial, we will be discussing a program to convert min heap to max heap. For this we will be provided with the array representation of the min heap. Our task is to convert that given min heap to max heap in O(n) time complexity. Live Demo #include<bits/stdc++.h> using namespace std; //converting a given subtree into a heap void convert_arrayheap(int arr[], int i, int n){ int l = 2*i + 1; int r = 2*i + 2; int largest = i; if (l < n && arr[l] > arr[i]) largest = l; if (r < n && arr[r] > arr[largest]) largest = r; if (largest != i){ swap(arr[i], arr[largest]); convert_arrayheap(arr, largest, n); } } //finally building the max heap void convert_maxheap(int arr[], int n){ //heapify all the node elements for (int i = (n-2)/2; i >= 0; --i) convert_arrayheap(arr, i, n); } //printing the array void printArray(int* arr, int size){ for (int i = 0; i < size; ++i) printf("%d ", arr[i]); } int main(){ int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9}; int n = sizeof(arr)/sizeof(arr[0]); printf("Min Heap array : "); printArray(arr, n); convert_maxheap(arr, n); printf("\nMax Heap array : "); printArray(arr, n); return 0; } Min Heap array : 3 5 9 6 8 20 10 12 18 9 Max Heap array : 20 18 10 12 9 9 3 5 6 8
[ { "code": null, "e": 1145, "s": 1062, "text": "In this tutorial, we will be discussing a program to convert min heap to max heap." }, { "code": null, "e": 1301, "s": 1145, "text": "For this we will be provided with the array representation of the min heap. Our task is to convert that given min heap to max heap in O(n) time complexity." }, { "code": null, "e": 1312, "s": 1301, "text": " Live Demo" }, { "code": null, "e": 2279, "s": 1312, "text": "#include<bits/stdc++.h>\nusing namespace std;\n//converting a given subtree into a heap\nvoid convert_arrayheap(int arr[], int i, int n){\n int l = 2*i + 1;\n int r = 2*i + 2;\n int largest = i;\n if (l < n && arr[l] > arr[i])\n largest = l;\n if (r < n && arr[r] > arr[largest])\n largest = r;\n if (largest != i){\n swap(arr[i], arr[largest]);\n convert_arrayheap(arr, largest, n);\n }\n}\n//finally building the max heap\nvoid convert_maxheap(int arr[], int n){\n //heapify all the node elements\n for (int i = (n-2)/2; i >= 0; --i)\n convert_arrayheap(arr, i, n);\n}\n//printing the array\nvoid printArray(int* arr, int size){\n for (int i = 0; i < size; ++i)\n printf(\"%d \", arr[i]);\n}\nint main(){\n int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9};\n int n = sizeof(arr)/sizeof(arr[0]);\n printf(\"Min Heap array : \");\n printArray(arr, n);\n convert_maxheap(arr, n);\n printf(\"\\nMax Heap array : \");\n printArray(arr, n);\n return 0;\n}" }, { "code": null, "e": 2363, "s": 2279, "text": "Min Heap array : 3 5 9 6 8 20 10 12 18 9\nMax Heap array : 20 18 10 12 9 9 3 5 6 8\n\n" } ]
Filter the records of current day, month and year in MySQL?
Let’s say you have a table with UserLoginTime column wherein we have stored some values for sample. This is the login time of users and we want to filter all these records on the basis of current day, month and year i.e. the current date. We will be Let us now create the table we discussed above mysql> create table userLoginInformation - > ( - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, - > UserName varchar(20), - > UserLoginTime datetime - > ); Query OK, 0 rows affected (0.79 sec) Insert some records in the table using insert command. The query is as follows mysql> insert into userLoginInformation(UserName,UserLoginTime) values('John','2016-02-12'); Query OK, 1 row affected (0.18 sec) mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Carol','2019-01-31'); Query OK, 1 row affected (0.16 sec) mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Bob','2019-02-19'); Query OK, 1 row affected (0.12 sec) mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Sam','2018-02-19'); Query OK, 1 row affected (0.16 sec) mysql> insert into userLoginInformation(UserName,UserLoginTime) values('Larry','2017-04-18'); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement. The query is as follows mysql> select *from userLoginInformation; The following is the output +--------+----------+---------------------+ | UserId | UserName | UserLoginTime | +--------+----------+---------------------+ | 1 | John | 2016-02-12 00:00:00 | | 2 | Carol | 2019-01-31 00:00:00 | | 3 | Bob | 2019-02-19 00:00:00 | | 4 | Sam | 2018-02-19 00:00:00 | | 5 | Larry | 2017-04-18 00:00:00 | +--------+----------+---------------------+ 5 rows in set (0.00 sec) Now, we will filter records on the basis of current date using the YEAR() and now(). Here, we are using now() to get the current date mysql> select *from userLoginInformation where YEAR(UserLoginTime)=YEAR(now()); The following is the output +--------+----------+---------------------+ | UserId | UserName | UserLoginTime | +--------+----------+---------------------+ | 2 | Carol | 2019-01-31 00:00:00 | | 3 | Bob | 2019-02-19 00:00:00 | +--------+----------+---------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1312, "s": 1062, "text": "Let’s say you have a table with UserLoginTime column wherein we have stored some values for sample. This is the login time of users and we want to filter all these records on the basis of current day, month and year i.e. the current date. We will be" }, { "code": null, "e": 1359, "s": 1312, "text": "Let us now create the table we discussed above" }, { "code": null, "e": 1570, "s": 1359, "text": "mysql> create table userLoginInformation\n - > (\n - > UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n - > UserName varchar(20),\n - > UserLoginTime datetime\n - > );\nQuery OK, 0 rows affected (0.79 sec)" }, { "code": null, "e": 1625, "s": 1570, "text": "Insert some records in the table using insert command." }, { "code": null, "e": 1649, "s": 1625, "text": "The query is as follows" }, { "code": null, "e": 2294, "s": 1649, "text": "mysql> insert into userLoginInformation(UserName,UserLoginTime) values('John','2016-02-12');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into userLoginInformation(UserName,UserLoginTime) values('Carol','2019-01-31');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into userLoginInformation(UserName,UserLoginTime) values('Bob','2019-02-19');\nQuery OK, 1 row affected (0.12 sec)\nmysql> insert into userLoginInformation(UserName,UserLoginTime) values('Sam','2018-02-19');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into userLoginInformation(UserName,UserLoginTime) values('Larry','2017-04-18');\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2353, "s": 2294, "text": "Display all records from the table using select statement." }, { "code": null, "e": 2377, "s": 2353, "text": "The query is as follows" }, { "code": null, "e": 2419, "s": 2377, "text": "mysql> select *from userLoginInformation;" }, { "code": null, "e": 2447, "s": 2419, "text": "The following is the output" }, { "code": null, "e": 2868, "s": 2447, "text": "+--------+----------+---------------------+\n| UserId | UserName | UserLoginTime |\n+--------+----------+---------------------+\n| 1 | John | 2016-02-12 00:00:00 |\n| 2 | Carol | 2019-01-31 00:00:00 |\n| 3 | Bob | 2019-02-19 00:00:00 |\n| 4 | Sam | 2018-02-19 00:00:00 |\n| 5 | Larry | 2017-04-18 00:00:00 |\n+--------+----------+---------------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 3002, "s": 2868, "text": "Now, we will filter records on the basis of current date using the YEAR() and now(). Here, we are using now() to get the current date" }, { "code": null, "e": 3082, "s": 3002, "text": "mysql> select *from userLoginInformation where YEAR(UserLoginTime)=YEAR(now());" }, { "code": null, "e": 3110, "s": 3082, "text": "The following is the output" }, { "code": null, "e": 3399, "s": 3110, "text": "+--------+----------+---------------------+\n| UserId | UserName | UserLoginTime |\n+--------+----------+---------------------+\n| 2 | Carol | 2019-01-31 00:00:00 |\n| 3 | Bob | 2019-02-19 00:00:00 |\n+--------+----------+---------------------+\n2 rows in set (0.00 sec)" } ]
PySpark – Extracting single value from DataFrame
17 Jun, 2021 In this article, we are going to extract a single value from the pyspark dataframe columns. To do this we will use the first() and head() functions. Single value means only one value, we can extract this value based on the column name Syntax: dataframe.first()[‘column name’] Dataframe.head()[‘Index’] Where, dataframe is the input dataframe and column name is the specific column Index is the row and columns. So we are going to create the dataframe using the nested list. Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data data =[["1","sravan","vignan"], ["2","ojaswi","vvit"], ["3","rohith","vvit"], ["4","sridevi","vignan"], ["1","sravan","vignan"], ["5","gnanesh","iit"]] # specify column namescolumns=['student ID','student NAME','college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print("Actual data in dataframe")# show dataframedataframe.show() Output: Actual data in dataframe +----------+------------+-------+ |student ID|student NAME|college| +----------+------------+-------+ | 1| sravan| vignan| | 2| ojaswi| vvit| | 3| rohith| vvit| | 4| sridevi| vignan| | 1| sravan| vignan| | 5| gnanesh| iit| +----------+------------+-------+ Example 1: Python program to extract a single value from a particular column using first(). Python3 # extract single value based on# column in the dataframedataframe.first()['student ID'] Output: '1' Example 2: Extract a single value using head(). Python3 # extract single value based# on column in the dataframedataframe.head()[0] Output: '1' Example 3: Extract a single value using head(). Python3 # extract single value based# on column in the dataframedataframe.head()[2] Output: 'vignan' Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 177, "s": 28, "text": "In this article, we are going to extract a single value from the pyspark dataframe columns. To do this we will use the first() and head() functions." }, { "code": null, "e": 263, "s": 177, "text": "Single value means only one value, we can extract this value based on the column name" }, { "code": null, "e": 272, "s": 263, "text": "Syntax: " }, { "code": null, "e": 305, "s": 272, "text": "dataframe.first()[‘column name’]" }, { "code": null, "e": 331, "s": 305, "text": "Dataframe.head()[‘Index’]" }, { "code": null, "e": 338, "s": 331, "text": "Where," }, { "code": null, "e": 410, "s": 338, "text": "dataframe is the input dataframe and column name is the specific column" }, { "code": null, "e": 440, "s": 410, "text": "Index is the row and columns." }, { "code": null, "e": 503, "s": 440, "text": "So we are going to create the dataframe using the nested list." }, { "code": null, "e": 511, "s": 503, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of students data data =[[\"1\",\"sravan\",\"vignan\"], [\"2\",\"ojaswi\",\"vvit\"], [\"3\",\"rohith\",\"vvit\"], [\"4\",\"sridevi\",\"vignan\"], [\"1\",\"sravan\",\"vignan\"], [\"5\",\"gnanesh\",\"iit\"]] # specify column namescolumns=['student ID','student NAME','college'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data,columns) print(\"Actual data in dataframe\")# show dataframedataframe.show()", "e": 1181, "s": 511, "text": null }, { "code": null, "e": 1189, "s": 1181, "text": "Output:" }, { "code": null, "e": 1554, "s": 1189, "text": "Actual data in dataframe\n+----------+------------+-------+\n|student ID|student NAME|college|\n+----------+------------+-------+\n| 1| sravan| vignan|\n| 2| ojaswi| vvit|\n| 3| rohith| vvit|\n| 4| sridevi| vignan|\n| 1| sravan| vignan|\n| 5| gnanesh| iit|\n+----------+------------+-------+" }, { "code": null, "e": 1646, "s": 1554, "text": "Example 1: Python program to extract a single value from a particular column using first()." }, { "code": null, "e": 1654, "s": 1646, "text": "Python3" }, { "code": "# extract single value based on# column in the dataframedataframe.first()['student ID']", "e": 1742, "s": 1654, "text": null }, { "code": null, "e": 1750, "s": 1742, "text": "Output:" }, { "code": null, "e": 1754, "s": 1750, "text": "'1'" }, { "code": null, "e": 1802, "s": 1754, "text": "Example 2: Extract a single value using head()." }, { "code": null, "e": 1810, "s": 1802, "text": "Python3" }, { "code": "# extract single value based# on column in the dataframedataframe.head()[0]", "e": 1886, "s": 1810, "text": null }, { "code": null, "e": 1894, "s": 1886, "text": "Output:" }, { "code": null, "e": 1898, "s": 1894, "text": "'1'" }, { "code": null, "e": 1946, "s": 1898, "text": "Example 3: Extract a single value using head()." }, { "code": null, "e": 1954, "s": 1946, "text": "Python3" }, { "code": "# extract single value based# on column in the dataframedataframe.head()[2]", "e": 2030, "s": 1954, "text": null }, { "code": null, "e": 2038, "s": 2030, "text": "Output:" }, { "code": null, "e": 2047, "s": 2038, "text": "'vignan'" }, { "code": null, "e": 2054, "s": 2047, "text": "Picked" }, { "code": null, "e": 2069, "s": 2054, "text": "Python-Pyspark" }, { "code": null, "e": 2076, "s": 2069, "text": "Python" }, { "code": null, "e": 2174, "s": 2076, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2192, "s": 2174, "text": "Python Dictionary" }, { "code": null, "e": 2234, "s": 2192, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2256, "s": 2234, "text": "Enumerate() in Python" }, { "code": null, "e": 2291, "s": 2256, "text": "Read a file line by line in Python" }, { "code": null, "e": 2317, "s": 2291, "text": "Python String | replace()" }, { "code": null, "e": 2349, "s": 2317, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2378, "s": 2349, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2405, "s": 2378, "text": "Python Classes and Objects" }, { "code": null, "e": 2426, "s": 2405, "text": "Python OOPs Concepts" } ]
How do I get the index of an item in Tkinter.Listbox?
We use the Tkinter Listbox widget to create a list of items. Each item in the listbox has some indexes that are assigned to them sequentially in vertical order. Let us suppose that we want to get the index of a clicked item in the listbox. Then, we have to first create a button that will capture the current selection of the items using list.curselection() method and then, we will print the index using the get() method. # Import the required libraries from tkinter import * # Create an instance of tkinter frame or window win = Tk() # Set the size of the window win.geometry("700x350") # Create a Listbox widget lb = Listbox(win, width=100, height=10, font=('Times 13'), selectbackground="black") lb.pack() # Define a function to edit the listbox ite def save(): for item in lb.curselection(): print("You have selected " + str(item+1)) # Add items in the Listbox lb.insert("end", "A", "B", "C", "D", "E", "F") # Add a Button To Edit and Delete the Listbox Item Button(win, text="Save", command=save).pack() win.mainloop() If we run the above code, it will display a window containing a list of alphabets (A-F). Select an item from the list and click the "Save" button to get the index of the selected item printed on the console. You have selected 3
[ { "code": null, "e": 1348, "s": 1187, "text": "We use the Tkinter Listbox widget to create a list of items. Each item in the listbox has some indexes that are assigned to them sequentially in vertical order." }, { "code": null, "e": 1610, "s": 1348, "text": "Let us suppose that we want to get the index of a clicked item in the listbox. Then, we have to first create a button that will capture the current selection of the items using list.curselection() method and then, we will print the index using the get() method." }, { "code": null, "e": 2228, "s": 1610, "text": "# Import the required libraries\nfrom tkinter import *\n\n# Create an instance of tkinter frame or window\nwin = Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\n# Create a Listbox widget\nlb = Listbox(win, width=100, height=10, font=('Times 13'), selectbackground=\"black\")\nlb.pack()\n\n# Define a function to edit the listbox ite\ndef save():\n for item in lb.curselection():\n print(\"You have selected \" + str(item+1))\n\n# Add items in the Listbox\nlb.insert(\"end\", \"A\", \"B\", \"C\", \"D\", \"E\", \"F\")\n\n# Add a Button To Edit and Delete the Listbox Item\nButton(win, text=\"Save\", command=save).pack()\n\nwin.mainloop()" }, { "code": null, "e": 2317, "s": 2228, "text": "If we run the above code, it will display a window containing a list of alphabets (A-F)." }, { "code": null, "e": 2436, "s": 2317, "text": "Select an item from the list and click the \"Save\" button to get the index of the selected item printed on the console." }, { "code": null, "e": 2456, "s": 2436, "text": "You have selected 3" } ]
What is Web API and why we use it ?
31 May, 2020 API stands for Application Programming Interface. API is actually some kind of interface which is having a set of functions. These set of functions will allow programmers to acquire some specific features or the data of an application. Web API is an API as the name suggests, it can be accessed over the web using the HTTP protocol. It is a framework that helps you to create and develop HTTP based RESTFUL services. The web API can be developed by using different technologies such as java, ASP.NET, etc. Web API is used in either a web server or a web browser. Basically Web API is a web development concept. It is limited to Web Application’s client-side and also it does not include a web server or web browser details. If an application is to be used on a distributed system and to provide services on different devices like laptops, mobiles, etc then web API services are used. Web API is the enhanced form of the web application. ASP.NET Web API: ASP.NET stands for Active Server Pages.NET. It is mostly used for creating web pages and web technologies. It is considered a very important tool for developers to build dynamic web pages using languages like C# and Visual Basic. ASP.NET Web API is a framework that helps you to build services by making it easy to reach a wide range of clients including browsers, mobiles, tablets, etc. With the help of ASP.NET, you can use the same framework and same patterns for creating web pages and services both. Where to use Web API? Web APIs are very useful in implementation of RESTFUL web services using .NET framework.Web API helps in enabling the development of HTTP services to reach out to client entities like browser, devices or tablets.ASP.NET Web API can be used with MVC for any type of application.A web API can help you develop ASP.NET application via AJAX.Hence, web API makes it easier for the developers to build an ASP.NET application that is compatible with any browser and almost any device. Web APIs are very useful in implementation of RESTFUL web services using .NET framework. Web API helps in enabling the development of HTTP services to reach out to client entities like browser, devices or tablets. ASP.NET Web API can be used with MVC for any type of application. A web API can help you develop ASP.NET application via AJAX. Hence, web API makes it easier for the developers to build an ASP.NET application that is compatible with any browser and almost any device. Why to Choose Web API? A Web API services are preferable over other services to use with a native application that does not support SOAP but require web services. For creating resource-oriented services, the web API services are the best to choose. By using HTTP or restful service, these services are established. If you want good performance and fast development of services, the web API services are very helpful. For developing light weighted and maintainable web services, web API services are really helpful to develop that service. It supports any text pattern like JSON, XML etc. The devices that have tight bandwidth or having a limitation in bandwidth, then the Web API services are the best for those devices. How to use Web API? Web API receives requests from different types of client devices like mobile, laptop, etc, and then sends those requests to the webserver to process those requests and returns the desired output to the client. Web API is a System to System interaction, in which the data or information from one system can be accessed by another system, after the completion of execution the resultant data or we can say as output is shown to the viewer. API provides data to its programmers which is made available to outside users. When programmers decide to make some of their data available to the public, they “expose endpoints, ” meaning they publish a portion of the language they have used to build their program. Other programmers can then extract the data from the application by building URLs or using HTTP clients to request data from those endpoints. Server Side: A server-side web API is a programmatic interface. It consists of one or more publicly exposed endpoints. It defines a request-response message system. Mashup is a web application that is a server-side API that combines several server-side APIs. Webhook is a server-side API that takes input as a uniform resource identifier. Client Side: Client Side web APIs target standardized JavaScript bindings. Google created their native client architecture designed to replace native plug-ins with secure native sandboxed extensions and applications. Steps to use Web API: Most APIs require an API key. Once you find an API you want to play with, look in the documentation for access requirements. Most APIs will ask you to complete an identity verification, like signing in with your Google account. You’ll get a unique string of letters and numbers to use when accessing the API. The easiest way to start using an API is by finding an HTTP client online, like REST-Client, Postman, or Paw. These ready-made tools help you structure your requests to access existing APIs with the API key you received. You’ll still need to know some of the syntaxes from the documentation, but there is very little coding knowledge required. The next best way to pull data from an API is by building a URL from existing API documentation. Popular API Examples: Google Maps API’s: Google Maps APIs allows developers to use Google Maps on Webpages using a JavaScript or Flash interface.YouTube API’s: Google’s API lets developers integrate YouTube and functionality into websites or applications. YouTube APIs include the YouTube analytics API, YouTube Data API, YouTube live streaming API, YouTube Player APIs and others.The Flickr APIs: It is used by developers to access the Flick photo sharing community data.Twitter APIs: Twitter offers two APIs, the REST API allows developers to access core Twitter data and the search API provides methods for developers to interact with twitter search and trends data. Google Maps API’s: Google Maps APIs allows developers to use Google Maps on Webpages using a JavaScript or Flash interface. YouTube API’s: Google’s API lets developers integrate YouTube and functionality into websites or applications. YouTube APIs include the YouTube analytics API, YouTube Data API, YouTube live streaming API, YouTube Player APIs and others. The Flickr APIs: It is used by developers to access the Flick photo sharing community data. Twitter APIs: Twitter offers two APIs, the REST API allows developers to access core Twitter data and the search API provides methods for developers to interact with twitter search and trends data. Picked Web-API Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Node.js fs.readFileSync() Method Remove elements from a JavaScript Array How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Open URL in New Tab using JavaScript ? How to execute PHP code using command line ?
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2020" }, { "code": null, "e": 289, "s": 52, "text": "API stands for Application Programming Interface. API is actually some kind of interface which is having a set of functions. These set of functions will allow programmers to acquire some specific features or the data of an application. " }, { "code": null, "e": 990, "s": 289, "text": "Web API is an API as the name suggests, it can be accessed over the web using the HTTP protocol. It is a framework that helps you to create and develop HTTP based RESTFUL services. The web API can be developed by using different technologies such as java, ASP.NET, etc. Web API is used in either a web server or a web browser. Basically Web API is a web development concept. It is limited to Web Application’s client-side and also it does not include a web server or web browser details. If an application is to be used on a distributed system and to provide services on different devices like laptops, mobiles, etc then web API services are used. Web API is the enhanced form of the web application." }, { "code": null, "e": 1512, "s": 990, "text": "ASP.NET Web API: ASP.NET stands for Active Server Pages.NET. It is mostly used for creating web pages and web technologies. It is considered a very important tool for developers to build dynamic web pages using languages like C# and Visual Basic. ASP.NET Web API is a framework that helps you to build services by making it easy to reach a wide range of clients including browsers, mobiles, tablets, etc. With the help of ASP.NET, you can use the same framework and same patterns for creating web pages and services both." }, { "code": null, "e": 1534, "s": 1512, "text": "Where to use Web API?" }, { "code": null, "e": 2012, "s": 1534, "text": "Web APIs are very useful in implementation of RESTFUL web services using .NET framework.Web API helps in enabling the development of HTTP services to reach out to client entities like browser, devices or tablets.ASP.NET Web API can be used with MVC for any type of application.A web API can help you develop ASP.NET application via AJAX.Hence, web API makes it easier for the developers to build an ASP.NET application that is compatible with any browser and almost any device." }, { "code": null, "e": 2101, "s": 2012, "text": "Web APIs are very useful in implementation of RESTFUL web services using .NET framework." }, { "code": null, "e": 2226, "s": 2101, "text": "Web API helps in enabling the development of HTTP services to reach out to client entities like browser, devices or tablets." }, { "code": null, "e": 2292, "s": 2226, "text": "ASP.NET Web API can be used with MVC for any type of application." }, { "code": null, "e": 2353, "s": 2292, "text": "A web API can help you develop ASP.NET application via AJAX." }, { "code": null, "e": 2494, "s": 2353, "text": "Hence, web API makes it easier for the developers to build an ASP.NET application that is compatible with any browser and almost any device." }, { "code": null, "e": 2517, "s": 2494, "text": "Why to Choose Web API?" }, { "code": null, "e": 2657, "s": 2517, "text": "A Web API services are preferable over other services to use with a native application that does not support SOAP but require web services." }, { "code": null, "e": 2809, "s": 2657, "text": "For creating resource-oriented services, the web API services are the best to choose. By using HTTP or restful service, these services are established." }, { "code": null, "e": 2911, "s": 2809, "text": "If you want good performance and fast development of services, the web API services are very helpful." }, { "code": null, "e": 3082, "s": 2911, "text": "For developing light weighted and maintainable web services, web API services are really helpful to develop that service. It supports any text pattern like JSON, XML etc." }, { "code": null, "e": 3215, "s": 3082, "text": "The devices that have tight bandwidth or having a limitation in bandwidth, then the Web API services are the best for those devices." }, { "code": null, "e": 3673, "s": 3215, "text": "How to use Web API? Web API receives requests from different types of client devices like mobile, laptop, etc, and then sends those requests to the webserver to process those requests and returns the desired output to the client. Web API is a System to System interaction, in which the data or information from one system can be accessed by another system, after the completion of execution the resultant data or we can say as output is shown to the viewer." }, { "code": null, "e": 4082, "s": 3673, "text": "API provides data to its programmers which is made available to outside users. When programmers decide to make some of their data available to the public, they “expose endpoints, ” meaning they publish a portion of the language they have used to build their program. Other programmers can then extract the data from the application by building URLs or using HTTP clients to request data from those endpoints." }, { "code": null, "e": 4421, "s": 4082, "text": "Server Side: A server-side web API is a programmatic interface. It consists of one or more publicly exposed endpoints. It defines a request-response message system. Mashup is a web application that is a server-side API that combines several server-side APIs. Webhook is a server-side API that takes input as a uniform resource identifier." }, { "code": null, "e": 4638, "s": 4421, "text": "Client Side: Client Side web APIs target standardized JavaScript bindings. Google created their native client architecture designed to replace native plug-ins with secure native sandboxed extensions and applications." }, { "code": null, "e": 4660, "s": 4638, "text": "Steps to use Web API:" }, { "code": null, "e": 4969, "s": 4660, "text": "Most APIs require an API key. Once you find an API you want to play with, look in the documentation for access requirements. Most APIs will ask you to complete an identity verification, like signing in with your Google account. You’ll get a unique string of letters and numbers to use when accessing the API." }, { "code": null, "e": 5313, "s": 4969, "text": "The easiest way to start using an API is by finding an HTTP client online, like REST-Client, Postman, or Paw. These ready-made tools help you structure your requests to access existing APIs with the API key you received. You’ll still need to know some of the syntaxes from the documentation, but there is very little coding knowledge required." }, { "code": null, "e": 5410, "s": 5313, "text": "The next best way to pull data from an API is by building a URL from existing API documentation." }, { "code": null, "e": 5432, "s": 5410, "text": "Popular API Examples:" }, { "code": null, "e": 6080, "s": 5432, "text": "Google Maps API’s: Google Maps APIs allows developers to use Google Maps on Webpages using a JavaScript or Flash interface.YouTube API’s: Google’s API lets developers integrate YouTube and functionality into websites or applications. YouTube APIs include the YouTube analytics API, YouTube Data API, YouTube live streaming API, YouTube Player APIs and others.The Flickr APIs: It is used by developers to access the Flick photo sharing community data.Twitter APIs: Twitter offers two APIs, the REST API allows developers to access core Twitter data and the search API provides methods for developers to interact with twitter search and trends data." }, { "code": null, "e": 6204, "s": 6080, "text": "Google Maps API’s: Google Maps APIs allows developers to use Google Maps on Webpages using a JavaScript or Flash interface." }, { "code": null, "e": 6441, "s": 6204, "text": "YouTube API’s: Google’s API lets developers integrate YouTube and functionality into websites or applications. YouTube APIs include the YouTube analytics API, YouTube Data API, YouTube live streaming API, YouTube Player APIs and others." }, { "code": null, "e": 6533, "s": 6441, "text": "The Flickr APIs: It is used by developers to access the Flick photo sharing community data." }, { "code": null, "e": 6731, "s": 6533, "text": "Twitter APIs: Twitter offers two APIs, the REST API allows developers to access core Twitter data and the search API provides methods for developers to interact with twitter search and trends data." }, { "code": null, "e": 6738, "s": 6731, "text": "Picked" }, { "code": null, "e": 6746, "s": 6738, "text": "Web-API" }, { "code": null, "e": 6763, "s": 6746, "text": "Web Technologies" }, { "code": null, "e": 6790, "s": 6763, "text": "Web technologies Questions" }, { "code": null, "e": 6888, "s": 6790, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6949, "s": 6888, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6992, "s": 6949, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7064, "s": 6992, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 7104, "s": 7064, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7137, "s": 7104, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 7177, "s": 7137, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7237, "s": 7177, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 7298, "s": 7237, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 7344, "s": 7298, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed
03 May, 2021 Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]. Examples : Input: arr[] = {1, 20, 2, 10} Output: 72 We can get 72 by rotating array twice. {2, 10, 1, 20} 20*3 + 1*2 + 10*1 + 2*0 = 72 Input: arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9} Output: 330 We can get 330 by rotating array 9 times. {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 0*1 + 1*2 + 2*3 ... 9*10 = 330 We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to find all rotations one by one, check sum of every rotation and return the maximum sum. Time complexity of this solution is O(n2). We can solve this problem in O(n) time using an Efficient Solution. Let Rj be value of i*arr[i] with j rotations. The idea is to calculate next rotation value from previous rotation, i.e., calculate Rj from Rj-1. We can calculate initial value of result as R0, then keep calculating next rotation values. How to efficiently calculate Rj from Rj-1? This can be done in O(1) time. Below are details. Let us calculate initial value of i*arr[i] with no rotation R0 = 0*arr[0] + 1*arr[1] +...+ (n-1)*arr[n-1] After 1 rotation arr[n-1], becomes first element of array, arr[0] becomes second element, arr[1] becomes third element and so on. R1 = 0*arr[n-1] + 1*arr[0] +...+ (n-1)*arr[n-2] R1 - R0 = arr[0] + arr[1] + ... + arr[n-2] - (n-1)*arr[n-1] After 2 rotations arr[n-2], becomes first element of array, arr[n-1] becomes second element, arr[0] becomes third element and so on. R2 = 0*arr[n-2] + 1*arr[n-1] +...+ (n-1)*arr[n-3] R2 - R1 = arr[0] + arr[1] + ... + arr[n-3] - (n-1)*arr[n-2] + arr[n-1] If we take a closer look at above values, we can observe below pattern Rj - Rj-1 = arrSum - n * arr[n-j] Where arrSum is sum of all array elements, i.e., arrSum = ∑ arr[i] 0<=i<=n-1 Below is complete algorithm: 1) Compute sum of all array elements. Let this sum be 'arrSum'. 2) Compute R0 by doing i*arr[i] for given array. Let this value be currVal. 3) Initialize result: maxVal = currVal // maxVal is result. // This loop computes Rj from Rj-1 4) Do following for j = 1 to n-1 ......a) currVal = currVal + arrSum-n*arr[n-j]; ......b) If (currVal > maxVal) maxVal = currVal 5) Return maxVal Below is the implementation of above idea : C++ Java Python C# PHP Javascript // C++ program to find max value of i*arr[i]#include <iostream>using namespace std; // Returns max possible value of i*arr[i]int maxSum(int arr[], int n){ // Find array sum and i*arr[i] with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i=0; i<n; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j=1; j<n; j++) { currVal = currVal + arrSum-n*arr[n-j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal;} // Driver programint main(void){ int arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << "\nMax sum is " << maxSum(arr, n); return 0;} // Java program to find max value of i*arr[i] import java.util.Arrays; class Test{ static int arr[] = new int[]{10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Returns max possible value of i*arr[i] static int maxSum() { // Find array sum and i*arr[i] with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i=0; i<arr.length; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j=1; j<arr.length; j++) { currVal = currVal + arrSum-arr.length*arr[arr.length-j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal; } // Driver method to test the above function public static void main(String[] args) { System.out.println("Max sum is " + maxSum()); }} '''Python program to find maximum value of Sum(i*arr[i])''' # returns max possible value of Sum(i*arr[i])def maxSum(arr): # stores sum of arr[i] arrSum = 0 # stores sum of i*arr[i] currVal = 0 n = len(arr) for i in range(0, n): arrSum = arrSum + arr[i] currVal = currVal + (i*arr[i]) # initialize result maxVal = currVal # try all rotations one by one and find the maximum # rotation sum for j in range(1, n): currVal = currVal + arrSum-n*arr[n-j] if currVal > maxVal: maxVal = currVal # return result return maxVal # test maxsum(arr) functionarr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]print "Max sum is: ", maxSum(arr) // C# program to find max value of i*arr[i]using System; class Test{ static int []arr = new int[]{10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Returns max possible value of i*arr[i] static int maxSum() { // Find array sum and i*arr[i] // with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i = 0; i < arr.Length; i++) { arrSum = arrSum + arr[i]; currVal = currVal + (i * arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j = 1; j < arr.Length; j++) { currVal = currVal + arrSum - arr.Length * arr[arr.Length - j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal; } // Driver Code public static void Main() { Console.WriteLine("Max sum is " + maxSum()); }} // This article is contributed by vt_m. <?php// PHP program to find max// value of i*arr[i] // Returns max possible// value of i*arr[i]function maxSum($arr, $n){ // Find array sum and // i*arr[i] with no rotation // Stores sum of arr[i] $arrSum = 0; // Stores sum of i*arr[i] $currVal = 0; for ($i = 0; $i < $n; $i++) { $arrSum = $arrSum + $arr[$i]; $currVal = $currVal + ($i * $arr[$i]); } // Initialize result as // 0 rotation sum $maxVal = $currVal; // Try all rotations one // by one and find the // maximum rotation sum. for ($j = 1; $j < $n; $j++) { $currVal = $currVal + $arrSum - $n * $arr[$n - $j]; if ($currVal > $maxVal) $maxVal = $currVal; } // Return result return $maxVal;} // Driver Code$arr = array (10, 1, 2, 3, 4, 5, 6, 7, 8, 9);$n = sizeof($arr);echo "Max sum is " , maxSum($arr, $n); // This code is contributed by m_kit?> <script>// JavaScript program to find max value of i*arr[i] // Returns max possible value of i*arr[i]function maxSum(arr, n){ // Find array sum and i*arr[i] with no rotation let arrSum = 0; // Stores sum of arr[i] let currVal = 0; // Stores sum of i*arr[i] for (let i=0; i<n; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } // Initialize result as 0 rotation sum let maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (let j=1; j<n; j++) { currVal = currVal + arrSum-n*arr[n-j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal;} // Driver program let arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let n = arr.length; document.write("Max sum is " + maxSum(arr, n)); // This code is contributed by Surbhi Tyagi.</script> Output : Max sum is 330 Time Complexity : O(n) Auxiliary Space : O(1) This article is contributed by Nitesh Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t Praveen Sinha SohamGidwani 13manujchaturvedi surbhityagi15 rotation Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 May, 2021" }, { "code": null, "e": 216, "s": 54, "text": "Given an array, only rotation operation is allowed on array. We can rotate the array as many times as we want. Return the maximum possible summation of i*arr[i]." }, { "code": null, "e": 229, "s": 216, "text": "Examples : " }, { "code": null, "e": 519, "s": 229, "text": "Input: arr[] = {1, 20, 2, 10}\nOutput: 72\nWe can get 72 by rotating array twice.\n{2, 10, 1, 20}\n20*3 + 1*2 + 10*1 + 2*0 = 72\n\nInput: arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9}\nOutput: 330\nWe can get 330 by rotating array 9 times.\n{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};\n0*1 + 1*2 + 2*3 ... 9*10 = 330" }, { "code": null, "e": 753, "s": 519, "text": "We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to find all rotations one by one, check sum of every rotation and return the maximum sum. Time complexity of this solution is O(n2). " }, { "code": null, "e": 1059, "s": 753, "text": "We can solve this problem in O(n) time using an Efficient Solution. Let Rj be value of i*arr[i] with j rotations. The idea is to calculate next rotation value from previous rotation, i.e., calculate Rj from Rj-1. We can calculate initial value of result as R0, then keep calculating next rotation values. " }, { "code": null, "e": 1154, "s": 1059, "text": "How to efficiently calculate Rj from Rj-1? This can be done in O(1) time. Below are details. " }, { "code": null, "e": 1955, "s": 1154, "text": "Let us calculate initial value of i*arr[i] with no rotation\nR0 = 0*arr[0] + 1*arr[1] +...+ (n-1)*arr[n-1]\n\nAfter 1 rotation arr[n-1], becomes first element of array, \narr[0] becomes second element, arr[1] becomes third element\nand so on.\nR1 = 0*arr[n-1] + 1*arr[0] +...+ (n-1)*arr[n-2]\n\nR1 - R0 = arr[0] + arr[1] + ... + arr[n-2] - (n-1)*arr[n-1]\n\nAfter 2 rotations arr[n-2], becomes first element of array, \narr[n-1] becomes second element, arr[0] becomes third element\nand so on.\nR2 = 0*arr[n-2] + 1*arr[n-1] +...+ (n-1)*arr[n-3]\n\nR2 - R1 = arr[0] + arr[1] + ... + arr[n-3] - (n-1)*arr[n-2] + arr[n-1]\n\nIf we take a closer look at above values, we can observe \nbelow pattern\n\nRj - Rj-1 = arrSum - n * arr[n-j]\n\nWhere arrSum is sum of all array elements, i.e., \n\narrSum = ∑ arr[i]\n 0<=i<=n-1 " }, { "code": null, "e": 1985, "s": 1955, "text": "Below is complete algorithm: " }, { "code": null, "e": 2391, "s": 1985, "text": "1) Compute sum of all array elements. Let this sum be 'arrSum'.\n\n2) Compute R0 by doing i*arr[i] for given array. \n Let this value be currVal.\n\n3) Initialize result: maxVal = currVal // maxVal is result.\n\n// This loop computes Rj from Rj-1 \n4) Do following for j = 1 to n-1\n......a) currVal = currVal + arrSum-n*arr[n-j];\n......b) If (currVal > maxVal)\n maxVal = currVal \n\n5) Return maxVal" }, { "code": null, "e": 2435, "s": 2391, "text": "Below is the implementation of above idea :" }, { "code": null, "e": 2439, "s": 2435, "text": "C++" }, { "code": null, "e": 2444, "s": 2439, "text": "Java" }, { "code": null, "e": 2451, "s": 2444, "text": "Python" }, { "code": null, "e": 2454, "s": 2451, "text": "C#" }, { "code": null, "e": 2458, "s": 2454, "text": "PHP" }, { "code": null, "e": 2469, "s": 2458, "text": "Javascript" }, { "code": "// C++ program to find max value of i*arr[i]#include <iostream>using namespace std; // Returns max possible value of i*arr[i]int maxSum(int arr[], int n){ // Find array sum and i*arr[i] with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i=0; i<n; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j=1; j<n; j++) { currVal = currVal + arrSum-n*arr[n-j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal;} // Driver programint main(void){ int arr[] = {10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int n = sizeof(arr)/sizeof(arr[0]); cout << \"\\nMax sum is \" << maxSum(arr, n); return 0;}", "e": 3379, "s": 2469, "text": null }, { "code": "// Java program to find max value of i*arr[i] import java.util.Arrays; class Test{ static int arr[] = new int[]{10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Returns max possible value of i*arr[i] static int maxSum() { // Find array sum and i*arr[i] with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i=0; i<arr.length; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j=1; j<arr.length; j++) { currVal = currVal + arrSum-arr.length*arr[arr.length-j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal; } // Driver method to test the above function public static void main(String[] args) { System.out.println(\"Max sum is \" + maxSum()); }}", "e": 4472, "s": 3379, "text": null }, { "code": "'''Python program to find maximum value of Sum(i*arr[i])''' # returns max possible value of Sum(i*arr[i])def maxSum(arr): # stores sum of arr[i] arrSum = 0 # stores sum of i*arr[i] currVal = 0 n = len(arr) for i in range(0, n): arrSum = arrSum + arr[i] currVal = currVal + (i*arr[i]) # initialize result maxVal = currVal # try all rotations one by one and find the maximum # rotation sum for j in range(1, n): currVal = currVal + arrSum-n*arr[n-j] if currVal > maxVal: maxVal = currVal # return result return maxVal # test maxsum(arr) functionarr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]print \"Max sum is: \", maxSum(arr)", "e": 5178, "s": 4472, "text": null }, { "code": "// C# program to find max value of i*arr[i]using System; class Test{ static int []arr = new int[]{10, 1, 2, 3, 4, 5, 6, 7, 8, 9}; // Returns max possible value of i*arr[i] static int maxSum() { // Find array sum and i*arr[i] // with no rotation int arrSum = 0; // Stores sum of arr[i] int currVal = 0; // Stores sum of i*arr[i] for (int i = 0; i < arr.Length; i++) { arrSum = arrSum + arr[i]; currVal = currVal + (i * arr[i]); } // Initialize result as 0 rotation sum int maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (int j = 1; j < arr.Length; j++) { currVal = currVal + arrSum - arr.Length * arr[arr.Length - j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal; } // Driver Code public static void Main() { Console.WriteLine(\"Max sum is \" + maxSum()); }} // This article is contributed by vt_m.", "e": 6350, "s": 5178, "text": null }, { "code": "<?php// PHP program to find max// value of i*arr[i] // Returns max possible// value of i*arr[i]function maxSum($arr, $n){ // Find array sum and // i*arr[i] with no rotation // Stores sum of arr[i] $arrSum = 0; // Stores sum of i*arr[i] $currVal = 0; for ($i = 0; $i < $n; $i++) { $arrSum = $arrSum + $arr[$i]; $currVal = $currVal + ($i * $arr[$i]); } // Initialize result as // 0 rotation sum $maxVal = $currVal; // Try all rotations one // by one and find the // maximum rotation sum. for ($j = 1; $j < $n; $j++) { $currVal = $currVal + $arrSum - $n * $arr[$n - $j]; if ($currVal > $maxVal) $maxVal = $currVal; } // Return result return $maxVal;} // Driver Code$arr = array (10, 1, 2, 3, 4, 5, 6, 7, 8, 9);$n = sizeof($arr);echo \"Max sum is \" , maxSum($arr, $n); // This code is contributed by m_kit?>", "e": 7317, "s": 6350, "text": null }, { "code": "<script>// JavaScript program to find max value of i*arr[i] // Returns max possible value of i*arr[i]function maxSum(arr, n){ // Find array sum and i*arr[i] with no rotation let arrSum = 0; // Stores sum of arr[i] let currVal = 0; // Stores sum of i*arr[i] for (let i=0; i<n; i++) { arrSum = arrSum + arr[i]; currVal = currVal+(i*arr[i]); } // Initialize result as 0 rotation sum let maxVal = currVal; // Try all rotations one by one and find // the maximum rotation sum. for (let j=1; j<n; j++) { currVal = currVal + arrSum-n*arr[n-j]; if (currVal > maxVal) maxVal = currVal; } // Return result return maxVal;} // Driver program let arr = [10, 1, 2, 3, 4, 5, 6, 7, 8, 9]; let n = arr.length; document.write(\"Max sum is \" + maxSum(arr, n)); // This code is contributed by Surbhi Tyagi.</script>", "e": 8213, "s": 7317, "text": null }, { "code": null, "e": 8223, "s": 8213, "text": "Output : " }, { "code": null, "e": 8238, "s": 8223, "text": "Max sum is 330" }, { "code": null, "e": 8284, "s": 8238, "text": "Time Complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 8454, "s": 8284, "text": "This article is contributed by Nitesh Singh. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 8460, "s": 8454, "text": "jit_t" }, { "code": null, "e": 8474, "s": 8460, "text": "Praveen Sinha" }, { "code": null, "e": 8487, "s": 8474, "text": "SohamGidwani" }, { "code": null, "e": 8505, "s": 8487, "text": "13manujchaturvedi" }, { "code": null, "e": 8519, "s": 8505, "text": "surbhityagi15" }, { "code": null, "e": 8528, "s": 8519, "text": "rotation" }, { "code": null, "e": 8535, "s": 8528, "text": "Arrays" }, { "code": null, "e": 8542, "s": 8535, "text": "Arrays" } ]
Reverse a Doubly Linked List
24 Jun, 2022 Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example. (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes, change prev of the head (or start) and change the head pointer in the end. C++ C Java Python3 C# Javascript /* C++ program to reverse a doubly linked list */#include <bits/stdc++.h>using namespace std; /* a node of the doubly linked list */class Node { public: int data; Node *next; Node *prev; }; /* Function to reverse a Doubly Linked List */void reverse(Node **head_ref) { Node *temp = NULL; Node *current = *head_ref; /* swap next and prev for all nodes of doubly linked list */ while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } /* Before changing the head, check for the cases like empty list and list with only one node */ if(temp != NULL ) *head_ref = temp->prev; } /* UTILITY FUNCTIONS *//* Function to insert a node at thebeginning of the Doubly Linked List */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(Node *node) { while(node != NULL) { cout << node->data << " "; node = node->next; } } /* Driver code */int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << "Original Linked list" << endl; printList(head); /* Reverse doubly linked list */ reverse(&head); cout << "\nReversed Linked list" << endl; printList(head); return 0;} // This code is contributed by rathbhupendra /* Program to reverse a doubly linked list */#include <stdio.h>#include <stdlib.h> /* a node of the doubly linked list */struct Node{ int data; struct Node *next; struct Node *prev; }; /* Function to reverse a Doubly Linked List */void reverse(struct Node **head_ref){ struct Node *temp = NULL; struct Node *current = *head_ref; /* swap next and prev for all nodes of doubly linked list */ while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } /* Before changing head, check for the cases like empty list and list with only one node */ if(temp != NULL ) *head_ref = temp->prev;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(struct Node *node){ while(node!=NULL) { printf("%d ", node->data); node = node->next; }} /* Driver code*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); printf("\n Original Linked list "); printList(head); /* Reverse doubly linked list */ reverse(&head); printf("\n Reversed Linked list "); printList(head); getchar();} // Java program to reverse a doubly linked list class LinkedList { static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List */ void reverse() { Node temp = null; Node current = head; /* swap next and prev for all nodes of doubly linked list */ while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } /* Before changing head, check for the cases like empty list and list with only one node */ if (temp != null) { head = temp.prev; } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.push(2); list.push(4); list.push(8); list.push(10); System.out.println("Original linked list "); list.printList(head); list.reverse(); System.out.println(""); System.out.println("The reversed Linked List is "); list.printList(head); }} // This code has been contributed by Mayank Jaiswal # Program to reverse a doubly linked list # A node of the doubly linked list class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function reverse a Doubly Linked List def reverse(self): temp = None current = self.head # Swap next and prev for all nodes of # doubly linked list while current is not None: temp = current.prev current.prev = current.next current.next = temp current = current.prev # Before changing head, check for the cases like # empty list and list with only one node if temp is not None: self.head = temp.prev # Given a reference to the head of a list and an # integer,inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): while(node is not None): print(node.data,end=' ') node = node.next # Driver codedll = DoublyLinkedList()dll.push(2)dll.push(4)dll.push(8)dll.push(10) print ("\nOriginal Linked List")dll.printList(dll.head) # Reverse doubly linked listdll.reverse() print ("\nReversed Linked List")dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // A C# program to reverse a doubly linked listusing System; public class LinkedList { static Node head; class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List */ void reverse() { Node temp = null; Node current = head; /* swap next and prev for all nodes of doubly linked list */ while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } /* Before changing head, check for the cases like empty list and list with only one node */ if (temp != null) { head = temp.prev; } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Driver code public static void Main(String[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.push(2); list.push(4); list.push(8); list.push(10); Console.WriteLine("Original linked list "); list.printList(head); list.reverse(); Console.WriteLine(""); Console.WriteLine("The reversed Linked List is "); list.printList(head); }} // This code is contributed by 29AjayKumar <script>// javascript program to reverse a doubly linked list var head; class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } /* Function to reverse a Doubly Linked List */ function reverse() {var temp = null;var current = head; /* * swap next and prev for all nodes of doubly linked list */ while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } /* * Before changing head, check for the cases like empty list and list with only * one node */ if (temp != null) { head = temp.prev; } } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(new_data) { /* allocate node */var new_node = new Node(new_data); /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* * Function to print nodes in a given doubly linked list This function is same * as printList() of singly linked list */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } /* * Let us create a sorted linked list to test the functions Created linked list * will be 10->8->4->2 */ push(2); push(4); push(8); push(10); document.write("Original linked list <br/>"); printList(head); reverse(); document.write("<br/>"); document.write("The reversed Linked List is <br/>"); printList(head); // This code contributed by gauravrajput1</script> Output: Original linked list 10 8 4 2 The reversed Linked List is 2 4 8 10 Time Complexity: O(N), where N denotes the number of nodes in the doubly linked list.Auxiliary Space: O(1) We can also swap data instead of pointers to reverse the Doubly Linked List. Method used for reversing array can be used to swap data. Swapping data can be costly compared to pointers if the size of the data item(s) is more. Please write comments if you find any of the above codes/algorithms incorrect, or find better ways to solve the same problem. Method 2: The same question can also be done by using Stacks. Steps: Keep pushing the node’s data in the stack. -> O(n)The keep popping the elements out and updating the Doubly Linked List Keep pushing the node’s data in the stack. -> O(n) The keep popping the elements out and updating the Doubly Linked List C++ Java Python3 C# Javascript // C++ program to reverse a doubly linked list#include <bits/stdc++.h>using namespace std;struct LinkedList { struct Node { int data; Node *next, *prev; Node(int d) { data = d; next = prev = NULL; } }; Node* head = NULL; /* Function to reverse a Doubly Linked List using Stacks */ void reverse() { stack<int> st; Node* temp = head; while (temp != NULL) { st.push(temp->data); temp = temp->next; } // added all the elements sequence wise in the // st temp = head; while (temp != NULL) { temp->data = st.top(); st.pop(); temp = temp->next; } // popped all the elements and the added in the // linked list, // which are in the reversed order-> } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void Push(int new_data) { /* allocate node */ Node* new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = head; /* change prev of head node to new node */ if (head != NULL) { head->prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node* node) { while (node) { cout << node->data << " "; node = node->next; } }}; // Driver Codeint main(){ LinkedList list; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.Push(2); list.Push(4); list.Push(8); list.Push(10); cout << "Original linked list " << endl; list.printList(list.head); list.reverse(); cout << endl; cout << "The reversed Linked List is " << endl; list.printList(list.head);} // This code is contributed by Pratham76 // Java program to reverse a doubly linked listimport java.util.*;class LinkedList { static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List using Stacks */ void reverse() { Stack<Integer> stack = new Stack<>(); Node temp = head; while (temp != null) { stack.push(temp.data); temp = temp.next; } // added all the elements sequence wise in the // stack temp = head; while (temp != null) { temp.data = stack.pop(); temp = temp.next; } // popped all the elements and the added in the // linked list, // which are in the reversed order. } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + " "); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.push(2); list.push(4); list.push(8); list.push(10); System.out.println("Original linked list "); list.printList(head); list.reverse(); System.out.println(""); System.out.println("The reversed Linked List is "); list.printList(head); }} // This code has been contributed by Rashita Mehta """function to reverse a doubly-linked listswap next and prev pointers for all the nodeschange prev of the head nodechange head pointer"""class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None """ method to reverse a Doubly-Linked List using Stacks """ def reverseUsingStacks(self): stack = [] temp = self.head while temp is not None: stack.append(temp.data) temp = temp.next # Add all the elements in the stack # in a sequence to the stack temp = self.head while temp is not None: temp.data = stack.pop() temp = temp.next # Popped all the elements and the # added in the linked list, # in a reversed order. """ method to push a new item before the head """ def push(self, new_data): new_node = Node(new_data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node """ method to traverse the doubly-linked list and print every node in the list """ def printList(self, node): while(node is not None): print(node.data) node = node. next # driver program for the doubly-linked listdll = DoublyLinkedList()dll.push(2)dll.push(4)dll.push(8)dll.push(10) print("original doubly-linked list")dll.printList(dll.head) # reverse a doubly-linked listdll.reverseUsingStacks() print(" reversed doubly-linked list")dll.printList(dll.head) // C# program to reverse a doubly linked listusing System;using System.Collections;using System.Collections.Generic;class LinkedList { public static Node head; public class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List using Stacks */ public void reverse() { Stack stack = new Stack(); Node temp = head; while (temp != null) { stack.Push(temp.data); temp = temp.next; } // added all the elements sequence wise in the // stack temp = head; while (temp != null) { temp.data = (int)stack.Pop(); temp = temp.next; } // popped all the elements and the added in the // linked list, // which are in the reversed order. } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ public void Push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ public void printList(Node node) { while (node != null) { Console.Write(node.data + " "); node = node.next; } } // Driver Code public static void Main(string[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.Push(2); list.Push(4); list.Push(8); list.Push(10); Console.WriteLine("Original linked list "); list.printList(head); list.reverse(); Console.WriteLine(""); Console.WriteLine("The reversed Linked List is "); list.printList(head); }} // This code is contributed by rutvik_56 <script> // Javascript program to reverse a doubly linked listclass Node { constructor(d) { this.data = d; this.next = this.prev = null; }} let head; // Function to reverse a Doubly // Linked List using Stacksfunction reverse(){ let stack = []; let temp = head; while (temp != null) { stack.push(temp.data); temp = temp.next; } // Added all the elements sequence // wise in the stack temp = head; while (temp != null) { temp.data = stack.pop(); temp = temp.next; } // Popped all the elements and the // added in the linked list, // which are in the reversed order.} // UTILITY FUNCTIONS // Function to insert a node at the // beginning of the Doubly Linked List function push(new_data){ /* Allocate node */ let new_node = new Node(new_data); /* Since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* Link the old list off the new node */ new_node.next = head; /* Change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* Move the head to point to the new node */ head = new_node;} // Function to print nodes in a given // doubly linked list. This function// is same as printList() of singly// linked listfunction printList(node){ while (node != null) { document.write(node.data + " "); node = node.next; }} // Driver Code // Let us create a sorted linked list // to test the functions Created linked// list will be 10->8->4->2push(2);push(4);push(8);push(10); document.write("Original linked list <br>");printList(head); reverse();document.write("<br>");document.write("The reversed Linked List is <br>");printList(head); // This code is contributed by rag2127 </script> Original linked list 10 8 4 2 The reversed Linked List is 2 4 8 10 Time Complexity: O(N)Auxiliary Space: O(N) In this method, we traverse the linked list once and add elements to the stack, and again traverse the whole for updating all the elements. The whole takes 2n time, which is the time complexity of O(n). gurunath10 29AjayKumar rathbhupendra shubham_singh Akanksha_Rai nidhi_biet mehtarashita18 rutvik_56 pratham76 humphreykibet GauravRajput1 rag2127 simranarora5sos simmytarika5 khushboogoyal499 amartyaghoshgfg hardikkoriintern doubly linked list Linked List Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. LinkedList in Java Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion) Detect loop in a linked list Merge two sorted linked lists Find the middle of a given linked list What is Data Structure: Types, Classifications and Applications Linked List vs Array Merge Sort for Linked Lists Implementing a Linked List in Java using Class
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Jun, 2022" }, { "code": null, "e": 133, "s": 52, "text": "Given a Doubly Linked List, the task is to reverse the given Doubly Linked List." }, { "code": null, "e": 166, "s": 133, "text": "See below diagrams for example. " }, { "code": null, "e": 200, "s": 166, "text": "(a) Original Doubly Linked List " }, { "code": null, "e": 234, "s": 200, "text": "(b) Reversed Doubly Linked List " }, { "code": null, "e": 433, "s": 234, "text": "Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes, change prev of the head (or start) and change the head pointer in the end." }, { "code": null, "e": 437, "s": 433, "text": "C++" }, { "code": null, "e": 439, "s": 437, "text": "C" }, { "code": null, "e": 444, "s": 439, "text": "Java" }, { "code": null, "e": 452, "s": 444, "text": "Python3" }, { "code": null, "e": 455, "s": 452, "text": "C#" }, { "code": null, "e": 466, "s": 455, "text": "Javascript" }, { "code": "/* C++ program to reverse a doubly linked list */#include <bits/stdc++.h>using namespace std; /* a node of the doubly linked list */class Node { public: int data; Node *next; Node *prev; }; /* Function to reverse a Doubly Linked List */void reverse(Node **head_ref) { Node *temp = NULL; Node *current = *head_ref; /* swap next and prev for all nodes of doubly linked list */ while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } /* Before changing the head, check for the cases like empty list and list with only one node */ if(temp != NULL ) *head_ref = temp->prev; } /* UTILITY FUNCTIONS *//* Function to insert a node at thebeginning of the Doubly Linked List */void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node(); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(Node *node) { while(node != NULL) { cout << node->data << \" \"; node = node->next; } } /* Driver code */int main() { /* Start with the empty list */ Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); cout << \"Original Linked list\" << endl; printList(head); /* Reverse doubly linked list */ reverse(&head); cout << \"\\nReversed Linked list\" << endl; printList(head); return 0;} // This code is contributed by rathbhupendra", "e": 2688, "s": 466, "text": null }, { "code": "/* Program to reverse a doubly linked list */#include <stdio.h>#include <stdlib.h> /* a node of the doubly linked list */struct Node{ int data; struct Node *next; struct Node *prev; }; /* Function to reverse a Doubly Linked List */void reverse(struct Node **head_ref){ struct Node *temp = NULL; struct Node *current = *head_ref; /* swap next and prev for all nodes of doubly linked list */ while (current != NULL) { temp = current->prev; current->prev = current->next; current->next = temp; current = current->prev; } /* Before changing head, check for the cases like empty list and list with only one node */ if(temp != NULL ) *head_ref = temp->prev;} /* UTILITY FUNCTIONS *//* Function to insert a node at the beginning of the Doubly Linked List */void push(struct Node** head_ref, int new_data){ /* allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* put in the data */ new_node->data = new_data; /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = (*head_ref); /* change prev of head node to new node */ if((*head_ref) != NULL) (*head_ref)->prev = new_node ; /* move the head to point to the new node */ (*head_ref) = new_node;} /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */void printList(struct Node *node){ while(node!=NULL) { printf(\"%d \", node->data); node = node->next; }} /* Driver code*/int main(){ /* Start with the empty list */ struct Node* head = NULL; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ push(&head, 2); push(&head, 4); push(&head, 8); push(&head, 10); printf(\"\\n Original Linked list \"); printList(head); /* Reverse doubly linked list */ reverse(&head); printf(\"\\n Reversed Linked list \"); printList(head); getchar();}", "e": 4870, "s": 2688, "text": null }, { "code": "// Java program to reverse a doubly linked list class LinkedList { static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List */ void reverse() { Node temp = null; Node current = head; /* swap next and prev for all nodes of doubly linked list */ while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } /* Before changing head, check for the cases like empty list and list with only one node */ if (temp != null) { head = temp.prev; } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } public static void main(String[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.push(2); list.push(4); list.push(8); list.push(10); System.out.println(\"Original linked list \"); list.printList(head); list.reverse(); System.out.println(\"\"); System.out.println(\"The reversed Linked List is \"); list.printList(head); }} // This code has been contributed by Mayank Jaiswal", "e": 7173, "s": 4870, "text": null }, { "code": "# Program to reverse a doubly linked list # A node of the doubly linked list class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: # Constructor for empty Doubly Linked List def __init__(self): self.head = None # Function reverse a Doubly Linked List def reverse(self): temp = None current = self.head # Swap next and prev for all nodes of # doubly linked list while current is not None: temp = current.prev current.prev = current.next current.next = temp current = current.prev # Before changing head, check for the cases like # empty list and list with only one node if temp is not None: self.head = temp.prev # Given a reference to the head of a list and an # integer,inserts a new node on the front of list def push(self, new_data): # 1. Allocates node # 2. Put the data in it new_node = Node(new_data) # 3. Make next of new node as head and # previous as None (already None) new_node.next = self.head # 4. change prev of head node to new_node if self.head is not None: self.head.prev = new_node # 5. move the head to point to the new node self.head = new_node def printList(self, node): while(node is not None): print(node.data,end=' ') node = node.next # Driver codedll = DoublyLinkedList()dll.push(2)dll.push(4)dll.push(8)dll.push(10) print (\"\\nOriginal Linked List\")dll.printList(dll.head) # Reverse doubly linked listdll.reverse() print (\"\\nReversed Linked List\")dll.printList(dll.head) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 9040, "s": 7173, "text": null }, { "code": "// A C# program to reverse a doubly linked listusing System; public class LinkedList { static Node head; class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List */ void reverse() { Node temp = null; Node current = head; /* swap next and prev for all nodes of doubly linked list */ while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } /* Before changing head, check for the cases like empty list and list with only one node */ if (temp != null) { head = temp.prev; } } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Driver code public static void Main(String[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.push(2); list.push(4); list.push(8); list.push(10); Console.WriteLine(\"Original linked list \"); list.printList(head); list.reverse(); Console.WriteLine(\"\"); Console.WriteLine(\"The reversed Linked List is \"); list.printList(head); }} // This code is contributed by 29AjayKumar", "e": 11384, "s": 9040, "text": null }, { "code": "<script>// javascript program to reverse a doubly linked list var head; class Node { constructor(val) { this.data = val; this.prev = null; this.next = null; } } /* Function to reverse a Doubly Linked List */ function reverse() {var temp = null;var current = head; /* * swap next and prev for all nodes of doubly linked list */ while (current != null) { temp = current.prev; current.prev = current.next; current.next = temp; current = current.prev; } /* * Before changing head, check for the cases like empty list and list with only * one node */ if (temp != null) { head = temp.prev; } } /* UTILITY FUNCTIONS */ /* * Function to insert a node at the beginning of the Doubly Linked List */ function push(new_data) { /* allocate node */var new_node = new Node(new_data); /* * since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* * Function to print nodes in a given doubly linked list This function is same * as printList() of singly linked list */ function printList(node) { while (node != null) { document.write(node.data + \" \"); node = node.next; } } /* * Let us create a sorted linked list to test the functions Created linked list * will be 10->8->4->2 */ push(2); push(4); push(8); push(10); document.write(\"Original linked list <br/>\"); printList(head); reverse(); document.write(\"<br/>\"); document.write(\"The reversed Linked List is <br/>\"); printList(head); // This code contributed by gauravrajput1</script>", "e": 13580, "s": 11384, "text": null }, { "code": null, "e": 13589, "s": 13580, "text": "Output: " }, { "code": null, "e": 13659, "s": 13589, "text": "Original linked list \n10 8 4 2 \nThe reversed Linked List is \n2 4 8 10" }, { "code": null, "e": 13766, "s": 13659, "text": "Time Complexity: O(N), where N denotes the number of nodes in the doubly linked list.Auxiliary Space: O(1)" }, { "code": null, "e": 13991, "s": 13766, "text": "We can also swap data instead of pointers to reverse the Doubly Linked List. Method used for reversing array can be used to swap data. Swapping data can be costly compared to pointers if the size of the data item(s) is more." }, { "code": null, "e": 14117, "s": 13991, "text": "Please write comments if you find any of the above codes/algorithms incorrect, or find better ways to solve the same problem." }, { "code": null, "e": 14180, "s": 14117, "text": "Method 2: The same question can also be done by using Stacks. " }, { "code": null, "e": 14187, "s": 14180, "text": "Steps:" }, { "code": null, "e": 14307, "s": 14187, "text": "Keep pushing the node’s data in the stack. -> O(n)The keep popping the elements out and updating the Doubly Linked List" }, { "code": null, "e": 14358, "s": 14307, "text": "Keep pushing the node’s data in the stack. -> O(n)" }, { "code": null, "e": 14428, "s": 14358, "text": "The keep popping the elements out and updating the Doubly Linked List" }, { "code": null, "e": 14432, "s": 14428, "text": "C++" }, { "code": null, "e": 14437, "s": 14432, "text": "Java" }, { "code": null, "e": 14445, "s": 14437, "text": "Python3" }, { "code": null, "e": 14448, "s": 14445, "text": "C#" }, { "code": null, "e": 14459, "s": 14448, "text": "Javascript" }, { "code": "// C++ program to reverse a doubly linked list#include <bits/stdc++.h>using namespace std;struct LinkedList { struct Node { int data; Node *next, *prev; Node(int d) { data = d; next = prev = NULL; } }; Node* head = NULL; /* Function to reverse a Doubly Linked List using Stacks */ void reverse() { stack<int> st; Node* temp = head; while (temp != NULL) { st.push(temp->data); temp = temp->next; } // added all the elements sequence wise in the // st temp = head; while (temp != NULL) { temp->data = st.top(); st.pop(); temp = temp->next; } // popped all the elements and the added in the // linked list, // which are in the reversed order-> } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void Push(int new_data) { /* allocate node */ Node* new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node->prev = NULL; /* link the old list off the new node */ new_node->next = head; /* change prev of head node to new node */ if (head != NULL) { head->prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node* node) { while (node) { cout << node->data << \" \"; node = node->next; } }}; // Driver Codeint main(){ LinkedList list; /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.Push(2); list.Push(4); list.Push(8); list.Push(10); cout << \"Original linked list \" << endl; list.printList(list.head); list.reverse(); cout << endl; cout << \"The reversed Linked List is \" << endl; list.printList(list.head);} // This code is contributed by Pratham76", "e": 16680, "s": 14459, "text": null }, { "code": "// Java program to reverse a doubly linked listimport java.util.*;class LinkedList { static Node head; static class Node { int data; Node next, prev; Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List using Stacks */ void reverse() { Stack<Integer> stack = new Stack<>(); Node temp = head; while (temp != null) { stack.push(temp.data); temp = temp.next; } // added all the elements sequence wise in the // stack temp = head; while (temp != null) { temp.data = stack.pop(); temp = temp.next; } // popped all the elements and the added in the // linked list, // which are in the reversed order. } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ void push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ void printList(Node node) { while (node != null) { System.out.print(node.data + \" \"); node = node.next; } } // Driver Code public static void main(String[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.push(2); list.push(4); list.push(8); list.push(10); System.out.println(\"Original linked list \"); list.printList(head); list.reverse(); System.out.println(\"\"); System.out.println(\"The reversed Linked List is \"); list.printList(head); }} // This code has been contributed by Rashita Mehta", "e": 19035, "s": 16680, "text": null }, { "code": "\"\"\"function to reverse a doubly-linked listswap next and prev pointers for all the nodeschange prev of the head nodechange head pointer\"\"\"class Node: def __init__(self, data): self.data = data self.next = None self.prev = None class DoublyLinkedList: def __init__(self): self.head = None \"\"\" method to reverse a Doubly-Linked List using Stacks \"\"\" def reverseUsingStacks(self): stack = [] temp = self.head while temp is not None: stack.append(temp.data) temp = temp.next # Add all the elements in the stack # in a sequence to the stack temp = self.head while temp is not None: temp.data = stack.pop() temp = temp.next # Popped all the elements and the # added in the linked list, # in a reversed order. \"\"\" method to push a new item before the head \"\"\" def push(self, new_data): new_node = Node(new_data) new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node \"\"\" method to traverse the doubly-linked list and print every node in the list \"\"\" def printList(self, node): while(node is not None): print(node.data) node = node. next # driver program for the doubly-linked listdll = DoublyLinkedList()dll.push(2)dll.push(4)dll.push(8)dll.push(10) print(\"original doubly-linked list\")dll.printList(dll.head) # reverse a doubly-linked listdll.reverseUsingStacks() print(\" reversed doubly-linked list\")dll.printList(dll.head)", "e": 20700, "s": 19035, "text": null }, { "code": "// C# program to reverse a doubly linked listusing System;using System.Collections;using System.Collections.Generic;class LinkedList { public static Node head; public class Node { public int data; public Node next, prev; public Node(int d) { data = d; next = prev = null; } } /* Function to reverse a Doubly Linked List using Stacks */ public void reverse() { Stack stack = new Stack(); Node temp = head; while (temp != null) { stack.Push(temp.data); temp = temp.next; } // added all the elements sequence wise in the // stack temp = head; while (temp != null) { temp.data = (int)stack.Pop(); temp = temp.next; } // popped all the elements and the added in the // linked list, // which are in the reversed order. } /* UTILITY FUNCTIONS */ /* Function to insert a node at the beginning of the * Doubly Linked List */ public void Push(int new_data) { /* allocate node */ Node new_node = new Node(new_data); /* since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* link the old list off the new node */ new_node.next = head; /* change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* move the head to point to the new node */ head = new_node; } /* Function to print nodes in a given doubly linked list This function is same as printList() of singly linked list */ public void printList(Node node) { while (node != null) { Console.Write(node.data + \" \"); node = node.next; } } // Driver Code public static void Main(string[] args) { LinkedList list = new LinkedList(); /* Let us create a sorted linked list to test the functions Created linked list will be 10->8->4->2 */ list.Push(2); list.Push(4); list.Push(8); list.Push(10); Console.WriteLine(\"Original linked list \"); list.printList(head); list.reverse(); Console.WriteLine(\"\"); Console.WriteLine(\"The reversed Linked List is \"); list.printList(head); }} // This code is contributed by rutvik_56", "e": 23126, "s": 20700, "text": null }, { "code": "<script> // Javascript program to reverse a doubly linked listclass Node { constructor(d) { this.data = d; this.next = this.prev = null; }} let head; // Function to reverse a Doubly // Linked List using Stacksfunction reverse(){ let stack = []; let temp = head; while (temp != null) { stack.push(temp.data); temp = temp.next; } // Added all the elements sequence // wise in the stack temp = head; while (temp != null) { temp.data = stack.pop(); temp = temp.next; } // Popped all the elements and the // added in the linked list, // which are in the reversed order.} // UTILITY FUNCTIONS // Function to insert a node at the // beginning of the Doubly Linked List function push(new_data){ /* Allocate node */ let new_node = new Node(new_data); /* Since we are adding at the beginning, prev is always NULL */ new_node.prev = null; /* Link the old list off the new node */ new_node.next = head; /* Change prev of head node to new node */ if (head != null) { head.prev = new_node; } /* Move the head to point to the new node */ head = new_node;} // Function to print nodes in a given // doubly linked list. This function// is same as printList() of singly// linked listfunction printList(node){ while (node != null) { document.write(node.data + \" \"); node = node.next; }} // Driver Code // Let us create a sorted linked list // to test the functions Created linked// list will be 10->8->4->2push(2);push(4);push(8);push(10); document.write(\"Original linked list <br>\");printList(head); reverse();document.write(\"<br>\");document.write(\"The reversed Linked List is <br>\");printList(head); // This code is contributed by rag2127 </script>", "e": 24969, "s": 23126, "text": null }, { "code": null, "e": 25039, "s": 24969, "text": "Original linked list \n10 8 4 2 \nThe reversed Linked List is \n2 4 8 10" }, { "code": null, "e": 25082, "s": 25039, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 25285, "s": 25082, "text": "In this method, we traverse the linked list once and add elements to the stack, and again traverse the whole for updating all the elements. The whole takes 2n time, which is the time complexity of O(n)." }, { "code": null, "e": 25296, "s": 25285, "text": "gurunath10" }, { "code": null, "e": 25308, "s": 25296, "text": "29AjayKumar" }, { "code": null, "e": 25322, "s": 25308, "text": "rathbhupendra" }, { "code": null, "e": 25336, "s": 25322, "text": "shubham_singh" }, { "code": null, "e": 25349, "s": 25336, "text": "Akanksha_Rai" }, { "code": null, "e": 25360, "s": 25349, "text": "nidhi_biet" }, { "code": null, "e": 25375, "s": 25360, "text": "mehtarashita18" }, { "code": null, "e": 25385, "s": 25375, "text": "rutvik_56" }, { "code": null, "e": 25395, "s": 25385, "text": "pratham76" }, { "code": null, "e": 25409, "s": 25395, "text": "humphreykibet" }, { "code": null, "e": 25423, "s": 25409, "text": "GauravRajput1" }, { "code": null, "e": 25431, "s": 25423, "text": "rag2127" }, { "code": null, "e": 25447, "s": 25431, "text": "simranarora5sos" }, { "code": null, "e": 25460, "s": 25447, "text": "simmytarika5" }, { "code": null, "e": 25477, "s": 25460, "text": "khushboogoyal499" }, { "code": null, "e": 25493, "s": 25477, "text": "amartyaghoshgfg" }, { "code": null, "e": 25510, "s": 25493, "text": "hardikkoriintern" }, { "code": null, "e": 25529, "s": 25510, "text": "doubly linked list" }, { "code": null, "e": 25541, "s": 25529, "text": "Linked List" }, { "code": null, "e": 25553, "s": 25541, "text": "Linked List" }, { "code": null, "e": 25651, "s": 25553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25670, "s": 25651, "text": "LinkedList in Java" }, { "code": null, "e": 25702, "s": 25670, "text": "Introduction to Data Structures" }, { "code": null, "e": 25758, "s": 25702, "text": "Doubly Linked List | Set 1 (Introduction and Insertion)" }, { "code": null, "e": 25787, "s": 25758, "text": "Detect loop in a linked list" }, { "code": null, "e": 25817, "s": 25787, "text": "Merge two sorted linked lists" }, { "code": null, "e": 25856, "s": 25817, "text": "Find the middle of a given linked list" }, { "code": null, "e": 25920, "s": 25856, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 25941, "s": 25920, "text": "Linked List vs Array" }, { "code": null, "e": 25969, "s": 25941, "text": "Merge Sort for Linked Lists" } ]
How to Integrate Google reCAPTCHA in Android?
24 Jan, 2021 Google reCAPTCHA is one of the services provided by Google which is used to verify whether the user is a bot or not. The Google reCAPTCHA is seen in many websites and applications to verify the users. In this article, we will take a look at the implementation of Google reCAPTCHA in Android. We will be building a simple application in which we will be displaying a Google reCAPTCHA verify user button, after clicking that button we will display the Google reCAPTCHA to our user and verify them. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. While using reCAPTCHA it makes several calls from your application to the Safety Net server and from the Safety Net server to your application. So you can get to know about these calls in more detail in the below diagram. Steps in which we make API calls: For using reCAPTCHA in your application we have to generate a Site key and Secret Key which we have to add to our application. The site key is used in our Android application and the secret key is stored on the server. With the help of this site, key reCAPTCHA will be generated and it will verify if the user is a robot or not. After making verification by reCAPTCHA our application will communicate with our captcha server and it will return a response using your site key. Now our application will send a token to our server and our server will then send a token to the reCAPTCHA server with our Secret key. Then reCAPTCHA server will send a success response to our server and the server will send a success response to our application. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding the dependency for volley and Safety Net As we will be using the API provided by Google. So for using this API we will be using Volley for handling our HTTP requests and a safety net for connecting to Google reCAPTCHA. implementation ‘com.android.volley:volley:1.1.1’ implementation ‘com.google.android.gms:play-services-safetynet:15.0.1’ After adding this dependency now sync your project and now we will move towards the creation of our API key which we will require for Google reCAPTCHA. Step 3: Generating API key for using Google reCAPTCHA For using Google reCAPTCHA we have to build two keys such as site key and site secret key which we have to use for authentication. For creating a new API key navigate to this Google developers site. And refer to the following diagram to generate the API keys. After adding this data accept reCAPTCHA terms and then click on Submit option. Step 4: Adding permissions for the Internet As we are calling the API for Google reCAPTCHA so we have to add permissions for the Internet in our AndroidManifest.xml. Navigate to the app > AndroidManifest.xml and add the below code to it. XML <uses-permission android:name="android.permission.INTERNET"/> Step 5: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><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" android:orientation="vertical" tools:context=".MainActivity"> <!--button for displaying our reCAPTCHA dialog box--> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="Verify captcha" /> </RelativeLayout> Step 6: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.android.volley.DefaultRetryPolicy;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import com.google.android.gms.common.api.ApiException;import com.google.android.gms.common.api.CommonStatusCodes;import com.google.android.gms.safetynet.SafetyNet;import com.google.android.gms.safetynet.SafetyNetApi;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener; import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // variables for our button and // strings and request queue. Button btnverifyCaptcha; String SITE_KEY = "Enter Your Site Key Here"; String SECRET_KEY = "Enter Your Secret Key Here"; RequestQueue queue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); queue = Volley.newRequestQueue(getApplicationContext()); btnverifyCaptcha = findViewById(R.id.button); btnverifyCaptcha.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { verifyGoogleReCAPTCHA(); } }); } private void verifyGoogleReCAPTCHA() { // below line is use for getting our safety // net client and verify with reCAPTCHA SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY) // after getting our client we have // to add on success listener. .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() { @Override public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) { // in below line we are checking the response token. if (!response.getTokenResult().isEmpty()) { // if the response token is not empty then we // are calling our verification method. handleVerification(response.getTokenResult()); } } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // this method is called when we get any error. if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // below line is use to display an error message which we get. Log.d("TAG", "Error message: " + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode())); } else { // below line is use to display a toast message for any error. Toast.makeText(MainActivity.this, "Error found is : " + e, Toast.LENGTH_SHORT).show(); } } }); } protected void handleVerification(final String responseToken) { // inside handle verification method we are // verifying our user with response token. // url to sen our site key and secret key // to below url using POST method. String url = "https://www.google.com/recaptcha/api/siteverify"; // in this we are making a string request and // using a post method to pass the data. StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // inside on response method we are checking if the // response is successful or not. try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getBoolean("success")) { // if the response is successful then we are // showing below toast message. Toast.makeText(MainActivity.this, "User verified with reCAPTCHA", Toast.LENGTH_SHORT).show(); } else { // if the response if failure we are displaying // a below toast message. Toast.makeText(getApplicationContext(), String.valueOf(jsonObject.getString("error-codes")), Toast.LENGTH_LONG).show(); } } catch (Exception ex) { // if we get any exception then we are // displaying an error message in logcat. Log.d("TAG", "JSON exception: " + ex.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // inside error response we are displaying // a log message in our logcat. Log.d("TAG", "Error message: " + error.getMessage()); } }) { // below is the getParamns method in which we will // be passing our response token and secret key to the above url. @Override protected Map<String, String> getParams() { // we are passing data using hashmap // key and value pair. Map<String, String> params = new HashMap<>(); params.put("secret", SECRET_KEY); params.put("response", responseToken); return params; } }; // below line of code is use to set retry // policy if the api fails in one try. request.setRetryPolicy(new DefaultRetryPolicy( // we are setting time for retry is 5 seconds. 50000, // below line is to perform maximum retries. DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); // at last we are adding our request to queue. queue.add(request); }} After adding this code make sure to add the keys which we have generated inside your app. After adding the keys run your app and see the output of the app. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2021" }, { "code": null, "e": 321, "s": 28, "text": "Google reCAPTCHA is one of the services provided by Google which is used to verify whether the user is a bot or not. The Google reCAPTCHA is seen in many websites and applications to verify the users. In this article, we will take a look at the implementation of Google reCAPTCHA in Android. " }, { "code": null, "e": 692, "s": 321, "text": "We will be building a simple application in which we will be displaying a Google reCAPTCHA verify user button, after clicking that button we will display the Google reCAPTCHA to our user and verify them. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 915, "s": 692, "text": "While using reCAPTCHA it makes several calls from your application to the Safety Net server and from the Safety Net server to your application. So you can get to know about these calls in more detail in the below diagram. " }, { "code": null, "e": 950, "s": 915, "text": "Steps in which we make API calls: " }, { "code": null, "e": 1169, "s": 950, "text": "For using reCAPTCHA in your application we have to generate a Site key and Secret Key which we have to add to our application. The site key is used in our Android application and the secret key is stored on the server." }, { "code": null, "e": 1279, "s": 1169, "text": "With the help of this site, key reCAPTCHA will be generated and it will verify if the user is a robot or not." }, { "code": null, "e": 1426, "s": 1279, "text": "After making verification by reCAPTCHA our application will communicate with our captcha server and it will return a response using your site key." }, { "code": null, "e": 1690, "s": 1426, "text": "Now our application will send a token to our server and our server will then send a token to the reCAPTCHA server with our Secret key. Then reCAPTCHA server will send a success response to our server and the server will send a success response to our application." }, { "code": null, "e": 1719, "s": 1690, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1881, "s": 1719, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 1937, "s": 1881, "text": "Step 2: Adding the dependency for volley and Safety Net" }, { "code": null, "e": 2116, "s": 1937, "text": "As we will be using the API provided by Google. So for using this API we will be using Volley for handling our HTTP requests and a safety net for connecting to Google reCAPTCHA. " }, { "code": null, "e": 2165, "s": 2116, "text": "implementation ‘com.android.volley:volley:1.1.1’" }, { "code": null, "e": 2240, "s": 2165, "text": "implementation ‘com.google.android.gms:play-services-safetynet:15.0.1’ " }, { "code": null, "e": 2392, "s": 2240, "text": "After adding this dependency now sync your project and now we will move towards the creation of our API key which we will require for Google reCAPTCHA." }, { "code": null, "e": 2446, "s": 2392, "text": "Step 3: Generating API key for using Google reCAPTCHA" }, { "code": null, "e": 2706, "s": 2446, "text": "For using Google reCAPTCHA we have to build two keys such as site key and site secret key which we have to use for authentication. For creating a new API key navigate to this Google developers site. And refer to the following diagram to generate the API keys." }, { "code": null, "e": 2786, "s": 2706, "text": "After adding this data accept reCAPTCHA terms and then click on Submit option. " }, { "code": null, "e": 2831, "s": 2786, "text": "Step 4: Adding permissions for the Internet " }, { "code": null, "e": 3026, "s": 2831, "text": "As we are calling the API for Google reCAPTCHA so we have to add permissions for the Internet in our AndroidManifest.xml. Navigate to the app > AndroidManifest.xml and add the below code to it. " }, { "code": null, "e": 3030, "s": 3026, "text": "XML" }, { "code": "<uses-permission android:name=\"android.permission.INTERNET\"/>", "e": 3092, "s": 3030, "text": null }, { "code": null, "e": 3140, "s": 3092, "text": "Step 5: Working with the activity_main.xml file" }, { "code": null, "e": 3283, "s": 3140, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. " }, { "code": null, "e": 3287, "s": 3283, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--button for displaying our reCAPTCHA dialog box--> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:text=\"Verify captcha\" /> </RelativeLayout>", "e": 3904, "s": 3287, "text": null }, { "code": null, "e": 3952, "s": 3904, "text": "Step 6: Working with the MainActivity.java file" }, { "code": null, "e": 4142, "s": 3952, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 4147, "s": 4142, "text": "Java" }, { "code": "import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.Toast; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity; import com.android.volley.DefaultRetryPolicy;import com.android.volley.Request;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.StringRequest;import com.android.volley.toolbox.Volley;import com.google.android.gms.common.api.ApiException;import com.google.android.gms.common.api.CommonStatusCodes;import com.google.android.gms.safetynet.SafetyNet;import com.google.android.gms.safetynet.SafetyNetApi;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener; import org.json.JSONObject; import java.util.HashMap;import java.util.Map; public class MainActivity extends AppCompatActivity { // variables for our button and // strings and request queue. Button btnverifyCaptcha; String SITE_KEY = \"Enter Your Site Key Here\"; String SECRET_KEY = \"Enter Your Secret Key Here\"; RequestQueue queue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); queue = Volley.newRequestQueue(getApplicationContext()); btnverifyCaptcha = findViewById(R.id.button); btnverifyCaptcha.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { verifyGoogleReCAPTCHA(); } }); } private void verifyGoogleReCAPTCHA() { // below line is use for getting our safety // net client and verify with reCAPTCHA SafetyNet.getClient(this).verifyWithRecaptcha(SITE_KEY) // after getting our client we have // to add on success listener. .addOnSuccessListener(this, new OnSuccessListener<SafetyNetApi.RecaptchaTokenResponse>() { @Override public void onSuccess(SafetyNetApi.RecaptchaTokenResponse response) { // in below line we are checking the response token. if (!response.getTokenResult().isEmpty()) { // if the response token is not empty then we // are calling our verification method. handleVerification(response.getTokenResult()); } } }) .addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // this method is called when we get any error. if (e instanceof ApiException) { ApiException apiException = (ApiException) e; // below line is use to display an error message which we get. Log.d(\"TAG\", \"Error message: \" + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode())); } else { // below line is use to display a toast message for any error. Toast.makeText(MainActivity.this, \"Error found is : \" + e, Toast.LENGTH_SHORT).show(); } } }); } protected void handleVerification(final String responseToken) { // inside handle verification method we are // verifying our user with response token. // url to sen our site key and secret key // to below url using POST method. String url = \"https://www.google.com/recaptcha/api/siteverify\"; // in this we are making a string request and // using a post method to pass the data. StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() { @Override public void onResponse(String response) { // inside on response method we are checking if the // response is successful or not. try { JSONObject jsonObject = new JSONObject(response); if (jsonObject.getBoolean(\"success\")) { // if the response is successful then we are // showing below toast message. Toast.makeText(MainActivity.this, \"User verified with reCAPTCHA\", Toast.LENGTH_SHORT).show(); } else { // if the response if failure we are displaying // a below toast message. Toast.makeText(getApplicationContext(), String.valueOf(jsonObject.getString(\"error-codes\")), Toast.LENGTH_LONG).show(); } } catch (Exception ex) { // if we get any exception then we are // displaying an error message in logcat. Log.d(\"TAG\", \"JSON exception: \" + ex.getMessage()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // inside error response we are displaying // a log message in our logcat. Log.d(\"TAG\", \"Error message: \" + error.getMessage()); } }) { // below is the getParamns method in which we will // be passing our response token and secret key to the above url. @Override protected Map<String, String> getParams() { // we are passing data using hashmap // key and value pair. Map<String, String> params = new HashMap<>(); params.put(\"secret\", SECRET_KEY); params.put(\"response\", responseToken); return params; } }; // below line of code is use to set retry // policy if the api fails in one try. request.setRetryPolicy(new DefaultRetryPolicy( // we are setting time for retry is 5 seconds. 50000, // below line is to perform maximum retries. DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); // at last we are adding our request to queue. queue.add(request); }}", "e": 11009, "s": 4147, "text": null }, { "code": null, "e": 11166, "s": 11009, "text": "After adding this code make sure to add the keys which we have generated inside your app. After adding the keys run your app and see the output of the app. " }, { "code": null, "e": 11174, "s": 11166, "text": "android" }, { "code": null, "e": 11198, "s": 11174, "text": "Technical Scripter 2020" }, { "code": null, "e": 11206, "s": 11198, "text": "Android" }, { "code": null, "e": 11211, "s": 11206, "text": "Java" }, { "code": null, "e": 11230, "s": 11211, "text": "Technical Scripter" }, { "code": null, "e": 11235, "s": 11230, "text": "Java" }, { "code": null, "e": 11243, "s": 11235, "text": "Android" } ]
DELETE request using XMLHttpRequest by making Custom HTTP library
22 Jul, 2020 The task here is to show how the XMLHttpRequest can be used to DELETE data to an API by making a custom HTTP library. A placeholder API that contains an array of objects would be used as an example. The DELETE request is performed on this API. The URL of the API is https://jsonplaceholder.typicode.com/posts/ Prerequisites: Basic knowledge of HTML, CSS, and JavaScript is required. An HTML file has to be created where the basic HTML markup is added as shown in the example below. At the end of the body, we attach two scripts which are library.js and app.js in the respective order. We will then created these files. A function easyHTTP is first made and a new XMLHttpRequest() object is initialized.A new prototype is created for the delete method using easyHTTP.prototype.delete. It contains two parameters url and a callback.A new request is opened using the open method. It takes three parameters, the first one is the type of the request (GET, POST, PUT or DELETE), the second is the URL for the API and last one is a boolean value, where true means an asynchronous call and false means synchronous call.The onload handler is used to display the data. It is executed after the API call is done. The status of the response is checked. If the status code is 200 then a callback function is run which contains two arguments, error and response text. If status code is not 200 then the callback function will simply print the error message.The last step is to send the request using the send() function. A function easyHTTP is first made and a new XMLHttpRequest() object is initialized. A new prototype is created for the delete method using easyHTTP.prototype.delete. It contains two parameters url and a callback. A new request is opened using the open method. It takes three parameters, the first one is the type of the request (GET, POST, PUT or DELETE), the second is the URL for the API and last one is a boolean value, where true means an asynchronous call and false means synchronous call. The onload handler is used to display the data. It is executed after the API call is done. The status of the response is checked. If the status code is 200 then a callback function is run which contains two arguments, error and response text. If status code is not 200 then the callback function will simply print the error message. The last step is to send the request using the send() function. We will first instantiate easyHTTP that is created earlier using the new keyword.We then pass the URL and a callback function in the delete prototype function.The callback function will contain two arguments, that is, error to print if any error occurs and response to get the actual response. We will first instantiate easyHTTP that is created earlier using the new keyword. We then pass the URL and a callback function in the delete prototype function. The callback function will contain two arguments, that is, error to print if any error occurs and response to get the actual response. The code examples below demonstrate the creation of all the required files. HTML <!DOCTYPE html><html lang="en"><head> <title>Delete request</title></head><body> <h1> Delete request using xmlhttpRequest/ Ajax by making custom HTTP library. </h1> <!-- Including library.js and app.js files --> <script src="library.js"></script> <script src="app.js"></script></body></html> Javascript function easyHTTP() { // Initialising new XMLHttpRequest method. this.http = new XMLHttpRequest();} // Make an HTTP Delete RequesteasyHTTP.prototype.delete = function (url, callback) { // Open an request (GET/POST/PUT/DELETE, // PATH, ASYNC - TRUE/FALSE) this.http.open("DELETE", url, true); // Assigning this to self to have // scope of this into the function let self = this; // When the response is ready this.http.onload = function () { // Checking status if (self.http.status === 200) { // Callback function (Error, response text) callback(null, "Post Deleted"); } else { // Callback function (Error message) callback("Error: " + self.http.status); } }; // Send the request this.http.send();}; Javascript // Instantiate easyHTTPconst http = new easyHTTP(); // Use the delete prototype// method with (URL, callback(error, response text))http.delete("https://jsonplaceholder.typicode.com/posts/1", function ( err, response) { if (err) { console.log(err); } else { console.log(response); }}); Output: Open the index.html file in any browser and open the developer console. The output of the program would be visible here. The DELETE request along with its details can also be observed by using the Networks tab. HTML5 JavaScript-Misc HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? How to Insert Form Data into Database using PHP ? DOM (Document Object Model) How to make elements float to center? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js How to calculate the number of days between two dates in javascript? Node.js | fs.writeFileSync() Method
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2020" }, { "code": null, "e": 339, "s": 28, "text": "The task here is to show how the XMLHttpRequest can be used to DELETE data to an API by making a custom HTTP library. A placeholder API that contains an array of objects would be used as an example. The DELETE request is performed on this API. The URL of the API is https://jsonplaceholder.typicode.com/posts/ " }, { "code": null, "e": 354, "s": 339, "text": "Prerequisites:" }, { "code": null, "e": 412, "s": 354, "text": "Basic knowledge of HTML, CSS, and JavaScript is required." }, { "code": null, "e": 648, "s": 412, "text": "An HTML file has to be created where the basic HTML markup is added as shown in the example below. At the end of the body, we attach two scripts which are library.js and app.js in the respective order. We will then created these files." }, { "code": null, "e": 1536, "s": 648, "text": "A function easyHTTP is first made and a new XMLHttpRequest() object is initialized.A new prototype is created for the delete method using easyHTTP.prototype.delete. It contains two parameters url and a callback.A new request is opened using the open method. It takes three parameters, the first one is the type of the request (GET, POST, PUT or DELETE), the second is the URL for the API and last one is a boolean value, where true means an asynchronous call and false means synchronous call.The onload handler is used to display the data. It is executed after the API call is done. The status of the response is checked. If the status code is 200 then a callback function is run which contains two arguments, error and response text. If status code is not 200 then the callback function will simply print the error message.The last step is to send the request using the send() function." }, { "code": null, "e": 1620, "s": 1536, "text": "A function easyHTTP is first made and a new XMLHttpRequest() object is initialized." }, { "code": null, "e": 1749, "s": 1620, "text": "A new prototype is created for the delete method using easyHTTP.prototype.delete. It contains two parameters url and a callback." }, { "code": null, "e": 2031, "s": 1749, "text": "A new request is opened using the open method. It takes three parameters, the first one is the type of the request (GET, POST, PUT or DELETE), the second is the URL for the API and last one is a boolean value, where true means an asynchronous call and false means synchronous call." }, { "code": null, "e": 2364, "s": 2031, "text": "The onload handler is used to display the data. It is executed after the API call is done. The status of the response is checked. If the status code is 200 then a callback function is run which contains two arguments, error and response text. If status code is not 200 then the callback function will simply print the error message." }, { "code": null, "e": 2428, "s": 2364, "text": "The last step is to send the request using the send() function." }, { "code": null, "e": 2722, "s": 2428, "text": "We will first instantiate easyHTTP that is created earlier using the new keyword.We then pass the URL and a callback function in the delete prototype function.The callback function will contain two arguments, that is, error to print if any error occurs and response to get the actual response." }, { "code": null, "e": 2804, "s": 2722, "text": "We will first instantiate easyHTTP that is created earlier using the new keyword." }, { "code": null, "e": 2883, "s": 2804, "text": "We then pass the URL and a callback function in the delete prototype function." }, { "code": null, "e": 3018, "s": 2883, "text": "The callback function will contain two arguments, that is, error to print if any error occurs and response to get the actual response." }, { "code": null, "e": 3094, "s": 3018, "text": "The code examples below demonstrate the creation of all the required files." }, { "code": null, "e": 3099, "s": 3094, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Delete request</title></head><body> <h1> Delete request using xmlhttpRequest/ Ajax by making custom HTTP library. </h1> <!-- Including library.js and app.js files --> <script src=\"library.js\"></script> <script src=\"app.js\"></script></body></html>", "e": 3406, "s": 3099, "text": null }, { "code": null, "e": 3417, "s": 3406, "text": "Javascript" }, { "code": "function easyHTTP() { // Initialising new XMLHttpRequest method. this.http = new XMLHttpRequest();} // Make an HTTP Delete RequesteasyHTTP.prototype.delete = function (url, callback) { // Open an request (GET/POST/PUT/DELETE, // PATH, ASYNC - TRUE/FALSE) this.http.open(\"DELETE\", url, true); // Assigning this to self to have // scope of this into the function let self = this; // When the response is ready this.http.onload = function () { // Checking status if (self.http.status === 200) { // Callback function (Error, response text) callback(null, \"Post Deleted\"); } else { // Callback function (Error message) callback(\"Error: \" + self.http.status); } }; // Send the request this.http.send();};", "e": 4189, "s": 3417, "text": null }, { "code": null, "e": 4200, "s": 4189, "text": "Javascript" }, { "code": "// Instantiate easyHTTPconst http = new easyHTTP(); // Use the delete prototype// method with (URL, callback(error, response text))http.delete(\"https://jsonplaceholder.typicode.com/posts/1\", function ( err, response) { if (err) { console.log(err); } else { console.log(response); }});", "e": 4497, "s": 4200, "text": null }, { "code": null, "e": 4506, "s": 4497, "text": "Output: " }, { "code": null, "e": 4717, "s": 4506, "text": "Open the index.html file in any browser and open the developer console. The output of the program would be visible here. The DELETE request along with its details can also be observed by using the Networks tab." }, { "code": null, "e": 4723, "s": 4717, "text": "HTML5" }, { "code": null, "e": 4739, "s": 4723, "text": "JavaScript-Misc" }, { "code": null, "e": 4744, "s": 4739, "text": "HTML" }, { "code": null, "e": 4755, "s": 4744, "text": "JavaScript" }, { "code": null, "e": 4772, "s": 4755, "text": "Web Technologies" }, { "code": null, "e": 4777, "s": 4772, "text": "HTML" }, { "code": null, "e": 4875, "s": 4777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4939, "s": 4875, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 5000, "s": 4939, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 5050, "s": 5000, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 5078, "s": 5050, "text": "DOM (Document Object Model)" }, { "code": null, "e": 5116, "s": 5078, "text": "How to make elements float to center?" }, { "code": null, "e": 5177, "s": 5116, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5249, "s": 5177, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5276, "s": 5249, "text": "File uploading in React.js" }, { "code": null, "e": 5345, "s": 5276, "text": "How to calculate the number of days between two dates in javascript?" } ]
Convert CSV to Pandas Dataframe
02 Dec, 2020 In this article, we will discuss how to convert CSV to Pandas Dataframe, this operation can be performed using pandas.read_csv reads a comma-separated values (csv) file into DataFrame. Example 1: In the below program we are going to convert nba.csv into a data frame and then display it. Python # import pandas module import pandas as pd # making dataframe df = pd.read_csv("nba.csv") # output the dataframeprint(df) Output: Example 2: Here is another example to convert a CSV dataset into pandas data frame. Python # import pandas module import pandas as pd # making dataframe df = pd.read_csv("nba.csv") # output the dataframeprint(df) Output: Python pandas-io Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Dec, 2020" }, { "code": null, "e": 239, "s": 54, "text": "In this article, we will discuss how to convert CSV to Pandas Dataframe, this operation can be performed using pandas.read_csv reads a comma-separated values (csv) file into DataFrame." }, { "code": null, "e": 342, "s": 239, "text": "Example 1: In the below program we are going to convert nba.csv into a data frame and then display it." }, { "code": null, "e": 349, "s": 342, "text": "Python" }, { "code": "# import pandas module import pandas as pd # making dataframe df = pd.read_csv(\"nba.csv\") # output the dataframeprint(df)", "e": 478, "s": 349, "text": null }, { "code": null, "e": 486, "s": 478, "text": "Output:" }, { "code": null, "e": 571, "s": 486, "text": "Example 2: Here is another example to convert a CSV dataset into pandas data frame. " }, { "code": null, "e": 578, "s": 571, "text": "Python" }, { "code": "# import pandas module import pandas as pd # making dataframe df = pd.read_csv(\"nba.csv\") # output the dataframeprint(df)", "e": 707, "s": 578, "text": null }, { "code": null, "e": 715, "s": 707, "text": "Output:" }, { "code": null, "e": 732, "s": 715, "text": "Python pandas-io" }, { "code": null, "e": 746, "s": 732, "text": "Python-pandas" }, { "code": null, "e": 770, "s": 746, "text": "Technical Scripter 2020" }, { "code": null, "e": 777, "s": 770, "text": "Python" }, { "code": null, "e": 796, "s": 777, "text": "Technical Scripter" }, { "code": null, "e": 894, "s": 796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 926, "s": 894, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 953, "s": 926, "text": "Python Classes and Objects" }, { "code": null, "e": 974, "s": 953, "text": "Python OOPs Concepts" }, { "code": null, "e": 997, "s": 974, "text": "Introduction To PYTHON" }, { "code": null, "e": 1028, "s": 997, "text": "Python | os.path.join() method" }, { "code": null, "e": 1084, "s": 1028, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1126, "s": 1084, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1168, "s": 1126, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1207, "s": 1168, "text": "Python | Get unique values from a list" } ]
Stack.Count Property in C#
04 Feb, 2019 This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to Count. Retrieving the value of this property is an O(1) operation. Syntax: public virtual int Count { get; } Return Value: It returns the number of elements contained in the Stack having type System.Int32. Below programs illustrate the use of above-discussed property: Example 1: // C# code illustrate the// Stack.Count Propertyusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Chandigarh"); myStack.Push("Delhi"); myStack.Push("Noida"); myStack.Push("Himachal"); myStack.Push("Punjab"); myStack.Push("Jammu"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements"+ " in the Stack are : "); Console.WriteLine(myStack.Count); }} Total number of elements in the Stack are : 6 Example 2: // C# code illustrate the// Stack.Count Propertyusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements"+ " in the Stack are : "); // The function should return 0 // as the Stack is empty and it // doesn't contain any element Console.WriteLine(myStack.Count); }} Total number of elements in the Stack are : 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.count?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-Stack C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# Dictionary with examples C# | How to check whether a List contains a specified element C# | Multiple inheritance using interfaces C# | Arrays of Strings C# | IsNullOrEmpty() Method String.Split() Method in C# with Examples Introduction to .NET Framework Differences Between .NET Core and .NET Framework C# | Delegates
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Feb, 2019" }, { "code": null, "e": 395, "s": 28, "text": "This method(comes under System.Collections namespace) is used to get the number of elements contained in the Stack. The capacity is the number of elements that the Stack can store and the count is the number of elements that are actually in the Stack. The capacity is always greater than or equal to Count. Retrieving the value of this property is an O(1) operation." }, { "code": null, "e": 403, "s": 395, "text": "Syntax:" }, { "code": null, "e": 437, "s": 403, "text": "public virtual int Count { get; }" }, { "code": null, "e": 534, "s": 437, "text": "Return Value: It returns the number of elements contained in the Stack having type System.Int32." }, { "code": null, "e": 597, "s": 534, "text": "Below programs illustrate the use of above-discussed property:" }, { "code": null, "e": 608, "s": 597, "text": "Example 1:" }, { "code": "// C# code illustrate the// Stack.Count Propertyusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Chandigarh\"); myStack.Push(\"Delhi\"); myStack.Push(\"Noida\"); myStack.Push(\"Himachal\"); myStack.Push(\"Punjab\"); myStack.Push(\"Jammu\"); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements\"+ \" in the Stack are : \"); Console.WriteLine(myStack.Count); }}", "e": 1291, "s": 608, "text": null }, { "code": null, "e": 1338, "s": 1291, "text": "Total number of elements in the Stack are : 6\n" }, { "code": null, "e": 1349, "s": 1338, "text": "Example 2:" }, { "code": "// C# code illustrate the// Stack.Count Propertyusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements\"+ \" in the Stack are : \"); // The function should return 0 // as the Stack is empty and it // doesn't contain any element Console.WriteLine(myStack.Count); }}", "e": 1909, "s": 1349, "text": null }, { "code": null, "e": 1956, "s": 1909, "text": "Total number of elements in the Stack are : 0\n" }, { "code": null, "e": 1967, "s": 1956, "text": "Reference:" }, { "code": null, "e": 2066, "s": 1967, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack.count?view=netframework-4.7.2" }, { "code": null, "e": 2095, "s": 2066, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 2120, "s": 2095, "text": "CSharp-Collections-Stack" }, { "code": null, "e": 2123, "s": 2120, "text": "C#" }, { "code": null, "e": 2221, "s": 2123, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2275, "s": 2221, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 2303, "s": 2275, "text": "C# Dictionary with examples" }, { "code": null, "e": 2365, "s": 2303, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 2408, "s": 2365, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2431, "s": 2408, "text": "C# | Arrays of Strings" }, { "code": null, "e": 2459, "s": 2431, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 2501, "s": 2459, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 2532, "s": 2501, "text": "Introduction to .NET Framework" }, { "code": null, "e": 2581, "s": 2532, "text": "Differences Between .NET Core and .NET Framework" } ]
GATE | GATE-CS-2017 (Set 2) | Question 64
28 Jun, 2021 Two transactions T1 and T2 are given as: T1: r1(X)w1(X)r1(Y)w1(Y) T2 : r2(Y)w2(Y)r2(Z)w2(Z) where ri(V) denotes a read operation by transaction Ti on a variable V and wi(V) denotes a write operation by transaction Ti on a variable V. The total number of conflict serializable schedules that can be formed by T1 and T2 is ______ Note: This question appeared as Numerical Answer Type.(A) 54(B) 55(C) 56(D) 57Answer: (A)Explanation: For schedules to be conflict serializable they should be free from RW, WW, WR conflicts.In the conflict serializable schedule we have to see that the operations in both the transactions occurring on same data item should not conflict. Data item y is shared between the two transactions so the read and write operations in T1 on data item y can produce RW, WR, WW conflict with the read and write operations of transaction T2 on data item y.Another constraint is that the order of operations of each transaction should be maintained. We can not change the order of operation on transaction. Suppose if read(x) is before write(x) in T1 then it should be in the same order in resulting conflict serializable schedule.In T1 we have two conflicting operations r1(y) and w1(y)In T2 we have two conflicting operations r2(y) and w2(y)Both the read and write of T1 on y should be performed together either before the read write pair of T2 or after read write pair to T2 because interleaving them will result in inconsistency because both these transaction are performing operation on same object. There is only one way to have (conflict) serializable schedule as T1->T2, because last operation of T1 and first operation of T2 conflicts each other. Now See How many schedules are conflict serializable to T2->T1. T1- r1(x) w1(x) r1(y) w1(y) Now See T2 from right, if we see T2 from right, see the first conflicting operationw2(z) and r2(z) don’t have any conflict with any operation, but w(y) has conflictPick W2(y) and see, at how many places it can be there. Case1: w2(y) r1(x) w1(x) r1(y) w1(y) Case2: r1(x) w2(y) w1(x) r1(y) w1(y) Case3: r1(x) w1(x) w2(y) r1(y) w1(y) Pick each case and see,how many positions other operation of T2 can take. Case1: w2(y) r1(x) w1(x) r1(y) w1(y) How many positions w2(z) and r2(z) can take ?(note that these w2(z) and r2(z) cant come before w2(y))that is 5C1 + 5C2 = 15 (either both can take same space or two different spaces)Now see, for each of these 15 positions, how many can r2(y) take ?Obiviously r2(y) cant come before w2(y) therefore one position.15×1 = 15 total possible schedules from case 1. Case2: r1(x) w1(y) w1(x) r1(y) w1(y) How many positions w2(z) and r2(z) can take ?that is 4C1 + 4C2 = 10 (either both can take same space or two different spaces)Now see, for each of these 10 positions, how many can r2(y) take ?Only 2 positions, because it has to come before w1(y).10×2 = 20 total possible schedules from case 2. Case3: r1(x) w1(x) w2(y) r1(y) w1(y) How many positions w2(z) and r2(x) can take ?that is 3C1 + 3C2 = 6Now see, for each of these 6 positions, how many can r2(y) take ?Only 3 positions, because it has to come before w2(y).6×3 = 18 total possible schedules from case 3.total schedules that are conflict serializable as T2->T1 = 15+20+18 = 53.total schedules that are conflict serializable as T1->T2 = 1. total schedules that are conflict serializable as either T2->​​​​​​​T1 or T1->T2 = 53+1 = 54. This solution is contributed by Parul Sharma.Quiz of this Question GATE-CS-2017 (Set 2) GATE-GATE-CS-2017 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE CS 2008 | Question 40 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE CS 2011 | Question 49 GATE | GATE CS 1996 | Question 38 GATE | GATE-CS-2004 | Question 31 GATE | GATE IT 2006 | Question 20
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 93, "s": 52, "text": "Two transactions T1 and T2 are given as:" }, { "code": null, "e": 146, "s": 93, "text": "T1: r1(X)w1(X)r1(Y)w1(Y)\n\nT2 : r2(Y)w2(Y)r2(Z)w2(Z)\n" }, { "code": null, "e": 382, "s": 146, "text": "where ri(V) denotes a read operation by transaction Ti on a variable V and wi(V) denotes a write operation by transaction Ti on a variable V. The total number of conflict serializable schedules that can be formed by T1 and T2 is ______" }, { "code": null, "e": 1572, "s": 382, "text": "Note: This question appeared as Numerical Answer Type.(A) 54(B) 55(C) 56(D) 57Answer: (A)Explanation: For schedules to be conflict serializable they should be free from RW, WW, WR conflicts.In the conflict serializable schedule we have to see that the operations in both the transactions occurring on same data item should not conflict. Data item y is shared between the two transactions so the read and write operations in T1 on data item y can produce RW, WR, WW conflict with the read and write operations of transaction T2 on data item y.Another constraint is that the order of operations of each transaction should be maintained. We can not change the order of operation on transaction. Suppose if read(x) is before write(x) in T1 then it should be in the same order in resulting conflict serializable schedule.In T1 we have two conflicting operations r1(y) and w1(y)In T2 we have two conflicting operations r2(y) and w2(y)Both the read and write of T1 on y should be performed together either before the read write pair of T2 or after read write pair to T2 because interleaving them will result in inconsistency because both these transaction are performing operation on same object." }, { "code": null, "e": 1787, "s": 1572, "text": "There is only one way to have (conflict) serializable schedule as T1->T2, because last operation of T1 and first operation of T2 conflicts each other. Now See How many schedules are conflict serializable to T2->T1." }, { "code": null, "e": 1846, "s": 1787, "text": "T1-\n r1(x) w1(x) r1(y) w1(y) \n" }, { "code": null, "e": 2066, "s": 1846, "text": "Now See T2 from right, if we see T2 from right, see the first conflicting operationw2(z) and r2(z) don’t have any conflict with any operation, but w(y) has conflictPick W2(y) and see, at how many places it can be there." }, { "code": null, "e": 2273, "s": 2066, "text": "Case1: w2(y) r1(x) w1(x) r1(y) w1(y) \nCase2: r1(x) w2(y) w1(x) r1(y) w1(y) \nCase3: r1(x) w1(x) w2(y) r1(y) w1(y) \n" }, { "code": null, "e": 2349, "s": 2273, "text": " Pick each case and see,how many positions other operation of T2 can take." }, { "code": null, "e": 2776, "s": 2349, "text": "Case1: w2(y) r1(x) w1(x) r1(y) w1(y) How many positions w2(z) and r2(z) can take ?(note that these w2(z) and r2(z) cant come before w2(y))that is 5C1 + 5C2 = 15 (either both can take same space or two different spaces)Now see, for each of these 15 positions, how many can r2(y) take ?Obiviously r2(y) cant come before w2(y) therefore one position.15×1 = 15 total possible schedules from case 1." }, { "code": null, "e": 3137, "s": 2776, "text": "Case2: r1(x) w1(y) w1(x) r1(y) w1(y) How many positions w2(z) and r2(z) can take ?that is 4C1 + 4C2 = 10 (either both can take same space or two different spaces)Now see, for each of these 10 positions, how many can r2(y) take ?Only 2 positions, because it has to come before w1(y).10×2 = 20 total possible schedules from case 2." }, { "code": null, "e": 3668, "s": 3137, "text": " Case3: r1(x) w1(x) w2(y) r1(y) w1(y) How many positions w2(z) and r2(x) can take ?that is 3C1 + 3C2 = 6Now see, for each of these 6 positions, how many can r2(y) take ?Only 3 positions, because it has to come before w2(y).6×3 = 18 total possible schedules from case 3.total schedules that are conflict serializable as T2->T1 = 15+20+18 = 53.total schedules that are conflict serializable as T1->T2 = 1. total schedules that are conflict serializable as either T2->​​​​​​​T1 or T1->T2 = 53+1 = 54." }, { "code": null, "e": 3735, "s": 3668, "text": "This solution is contributed by Parul Sharma.Quiz of this Question" }, { "code": null, "e": 3756, "s": 3735, "text": "GATE-CS-2017 (Set 2)" }, { "code": null, "e": 3782, "s": 3756, "text": "GATE-GATE-CS-2017 (Set 2)" }, { "code": null, "e": 3787, "s": 3782, "text": "GATE" }, { "code": null, "e": 3885, "s": 3787, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3927, "s": 3885, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 3989, "s": 3927, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 4023, "s": 3989, "text": "GATE | GATE CS 2008 | Question 40" }, { "code": null, "e": 4065, "s": 4023, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 4099, "s": 4065, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 4141, "s": 4099, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 4175, "s": 4141, "text": "GATE | GATE CS 2011 | Question 49" }, { "code": null, "e": 4209, "s": 4175, "text": "GATE | GATE CS 1996 | Question 38" }, { "code": null, "e": 4243, "s": 4209, "text": "GATE | GATE-CS-2004 | Question 31" } ]
Creating and Executing a .jar File in Linux Terminal
06 Jul, 2021 JAR – Java Archive. It is like a zip file but for java classes. It combines all the .class files in Java into a single .jar file. It is used to download all java classes on HTTP in a single operation. These can be created using the “jar” CLI tool. It also has an optional META-INF which can include files like – MANIFEST.MF – manifest file is used to define the extension and package-related data. INDEX.LIST – It contains location information for packages defined in an application or extension. x.SF – This is the signature file where ‘x’ is the base file name. x.DSA – This file stores the digital signature of the corresponding signature file. services/ – This directory stores all the service provider configuration files. The most common and majorly used file is MANIFEST.MF Java (JDK + JRE) must be installed. Check by using command – Java --version jar --version Let us consider 4 class files – Class1, Class2, Class3, Class4 Java class Class2 { public static void cls2Method(){ System.out.println(" Hello from Class2 "); }} class Class3 { public static void cls3Method(){ System.out.println(" Hello from Class3 "); }} class Class4 { public static void cls4Method(){ System.out.println(" Hello from Class4 "); }} public class Class1 { public static void main(String[] args){ System.out.println(" Hello from Class1 "); Class2.cls2Method(); Class3.cls3Method(); Class4.cls4Method(); }} Output Hello from Class1 Hello from Class2 Hello from Class3 Hello from Class4 Let’s move them into one jar file called “allClasses.jar”. Run the command: jar –create –file allClasses.jar Class1.class Class2.class Class3.class To get a clear output use –verbose jar –create –verbose –file allClasses.jar Class1.class Class2.class Class3.class Output: This will create an allClasses.jar file in the folder. Let’s understand the above command thoroughly. –create: It is an option to create a jar file. We can perform more operations like extract, update, etc.–verbose: It gives a crisp and clear output and shows what’s going on behind the scenes.–file filename: filename is the name for the jar file. Extension(.jar) is optional.In the end, we specify the whole list of files to put in the jar file. –create: It is an option to create a jar file. We can perform more operations like extract, update, etc. –verbose: It gives a crisp and clear output and shows what’s going on behind the scenes. –file filename: filename is the name for the jar file. Extension(.jar) is optional. In the end, we specify the whole list of files to put in the jar file. The shorthand for this command will be – jar -cvf allClasses.jar * Note: * represents all the files in the current folder. Use * with caution. To update, jar -uf allClasses.jar Class4.class -u is for the –update. This will update allClasses.jar files with the new Class4.class. From the verbose output, it is clear that compression is taking place, to bypass compression or to archive files without compression use the option –no-compress. jar –create –verbose –no-compress –file allClasses.jar Class1.class Class2.class Class3.class or jar -cvf0 allClasses.jar * Output: Execution is fairly simple of jar files. Just use the command java -jar allClasses.jar If this gives an error – no main manifest attribute, in allClasses.jar Open ./META-INF/MANIFEST.MF file and add a line in it. Main-Class: classname In our case, the class name will be “Class1” as it’s our main class. Now, the file will look like this:- Manifest-Version: 1.0 Created-By: Ubuntu Main-Class: Class1 Again run the command java -jar allClasses.jar Output: Hello from Class1 Hello from Class2 Hello from Class3 Hello from Class4 Caution: Don’t leave any space between lines in the MANIFEST.MF file else it will show the unexpected error. If you still get the error and not able to find the error, use the below workaround – java -cp allClasses.jar Class1 where Class1 is the name of the main class. Note: To Extract use command – jar --extract --file allClasses.jar or jar -xf allClasses.jar Picked Java Linux-Unix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Sed Command in Linux/Unix with examples AWK command in Unix/Linux with examples grep command in Unix/Linux cut command in Linux with examples cp command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Jul, 2021" }, { "code": null, "e": 340, "s": 28, "text": "JAR – Java Archive. It is like a zip file but for java classes. It combines all the .class files in Java into a single .jar file. It is used to download all java classes on HTTP in a single operation. These can be created using the “jar” CLI tool. It also has an optional META-INF which can include files like –" }, { "code": null, "e": 426, "s": 340, "text": "MANIFEST.MF – manifest file is used to define the extension and package-related data." }, { "code": null, "e": 525, "s": 426, "text": "INDEX.LIST – It contains location information for packages defined in an application or extension." }, { "code": null, "e": 593, "s": 525, "text": "x.SF – This is the signature file where ‘x’ is the base file name." }, { "code": null, "e": 677, "s": 593, "text": "x.DSA – This file stores the digital signature of the corresponding signature file." }, { "code": null, "e": 757, "s": 677, "text": "services/ – This directory stores all the service provider configuration files." }, { "code": null, "e": 810, "s": 757, "text": "The most common and majorly used file is MANIFEST.MF" }, { "code": null, "e": 872, "s": 810, "text": "Java (JDK + JRE) must be installed. Check by using command – " }, { "code": null, "e": 887, "s": 872, "text": "Java --version" }, { "code": null, "e": 901, "s": 887, "text": "jar --version" }, { "code": null, "e": 964, "s": 901, "text": "Let us consider 4 class files – Class1, Class2, Class3, Class4" }, { "code": null, "e": 969, "s": 964, "text": "Java" }, { "code": "class Class2 { public static void cls2Method(){ System.out.println(\" Hello from Class2 \"); }} class Class3 { public static void cls3Method(){ System.out.println(\" Hello from Class3 \"); }} class Class4 { public static void cls4Method(){ System.out.println(\" Hello from Class4 \"); }} public class Class1 { public static void main(String[] args){ System.out.println(\" Hello from Class1 \"); Class2.cls2Method(); Class3.cls3Method(); Class4.cls4Method(); }}", "e": 1503, "s": 969, "text": null }, { "code": null, "e": 1510, "s": 1503, "text": "Output" }, { "code": null, "e": 1586, "s": 1510, "text": "Hello from Class1 \nHello from Class2 \nHello from Class3 \nHello from Class4 " }, { "code": null, "e": 1646, "s": 1586, "text": "Let’s move them into one jar file called “allClasses.jar”. " }, { "code": null, "e": 1664, "s": 1646, "text": "Run the command: " }, { "code": null, "e": 1736, "s": 1664, "text": "jar –create –file allClasses.jar Class1.class Class2.class Class3.class" }, { "code": null, "e": 1771, "s": 1736, "text": "To get a clear output use –verbose" }, { "code": null, "e": 1852, "s": 1771, "text": "jar –create –verbose –file allClasses.jar Class1.class Class2.class Class3.class" }, { "code": null, "e": 1860, "s": 1852, "text": "Output:" }, { "code": null, "e": 1963, "s": 1860, "text": "This will create an allClasses.jar file in the folder. Let’s understand the above command thoroughly. " }, { "code": null, "e": 2309, "s": 1963, "text": "–create: It is an option to create a jar file. We can perform more operations like extract, update, etc.–verbose: It gives a crisp and clear output and shows what’s going on behind the scenes.–file filename: filename is the name for the jar file. Extension(.jar) is optional.In the end, we specify the whole list of files to put in the jar file." }, { "code": null, "e": 2414, "s": 2309, "text": "–create: It is an option to create a jar file. We can perform more operations like extract, update, etc." }, { "code": null, "e": 2503, "s": 2414, "text": "–verbose: It gives a crisp and clear output and shows what’s going on behind the scenes." }, { "code": null, "e": 2587, "s": 2503, "text": "–file filename: filename is the name for the jar file. Extension(.jar) is optional." }, { "code": null, "e": 2658, "s": 2587, "text": "In the end, we specify the whole list of files to put in the jar file." }, { "code": null, "e": 2699, "s": 2658, "text": "The shorthand for this command will be –" }, { "code": null, "e": 2725, "s": 2699, "text": "jar -cvf allClasses.jar *" }, { "code": null, "e": 2802, "s": 2725, "text": "Note: * represents all the files in the current folder. Use * with caution. " }, { "code": null, "e": 2813, "s": 2802, "text": "To update," }, { "code": null, "e": 2849, "s": 2813, "text": "jar -uf allClasses.jar Class4.class" }, { "code": null, "e": 2873, "s": 2849, "text": "-u is for the –update. " }, { "code": null, "e": 2938, "s": 2873, "text": "This will update allClasses.jar files with the new Class4.class." }, { "code": null, "e": 3101, "s": 2938, "text": "From the verbose output, it is clear that compression is taking place, to bypass compression or to archive files without compression use the option –no-compress." }, { "code": null, "e": 3195, "s": 3101, "text": "jar –create –verbose –no-compress –file allClasses.jar Class1.class Class2.class Class3.class" }, { "code": null, "e": 3199, "s": 3195, "text": "or " }, { "code": null, "e": 3226, "s": 3199, "text": "jar -cvf0 allClasses.jar *" }, { "code": null, "e": 3234, "s": 3226, "text": "Output:" }, { "code": null, "e": 3296, "s": 3234, "text": "Execution is fairly simple of jar files. Just use the command" }, { "code": null, "e": 3321, "s": 3296, "text": "java -jar allClasses.jar" }, { "code": null, "e": 3392, "s": 3321, "text": "If this gives an error – no main manifest attribute, in allClasses.jar" }, { "code": null, "e": 3449, "s": 3392, "text": "Open ./META-INF/MANIFEST.MF file and add a line in it. " }, { "code": null, "e": 3471, "s": 3449, "text": "Main-Class: classname" }, { "code": null, "e": 3541, "s": 3471, "text": "In our case, the class name will be “Class1” as it’s our main class. " }, { "code": null, "e": 3577, "s": 3541, "text": "Now, the file will look like this:-" }, { "code": null, "e": 3637, "s": 3577, "text": "Manifest-Version: 1.0\nCreated-By: Ubuntu\nMain-Class: Class1" }, { "code": null, "e": 3659, "s": 3637, "text": "Again run the command" }, { "code": null, "e": 3684, "s": 3659, "text": "java -jar allClasses.jar" }, { "code": null, "e": 3692, "s": 3684, "text": "Output:" }, { "code": null, "e": 3768, "s": 3692, "text": "Hello from Class1 \nHello from Class2 \nHello from Class3 \nHello from Class4 " }, { "code": null, "e": 3877, "s": 3768, "text": "Caution: Don’t leave any space between lines in the MANIFEST.MF file else it will show the unexpected error." }, { "code": null, "e": 3963, "s": 3877, "text": "If you still get the error and not able to find the error, use the below workaround –" }, { "code": null, "e": 3994, "s": 3963, "text": "java -cp allClasses.jar Class1" }, { "code": null, "e": 4039, "s": 3994, "text": "where Class1 is the name of the main class. " }, { "code": null, "e": 4045, "s": 4039, "text": "Note:" }, { "code": null, "e": 4070, "s": 4045, "text": "To Extract use command –" }, { "code": null, "e": 4106, "s": 4070, "text": "jar --extract --file allClasses.jar" }, { "code": null, "e": 4109, "s": 4106, "text": "or" }, { "code": null, "e": 4132, "s": 4109, "text": "jar -xf allClasses.jar" }, { "code": null, "e": 4139, "s": 4132, "text": "Picked" }, { "code": null, "e": 4144, "s": 4139, "text": "Java" }, { "code": null, "e": 4155, "s": 4144, "text": "Linux-Unix" }, { "code": null, "e": 4160, "s": 4155, "text": "Java" }, { "code": null, "e": 4258, "s": 4160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4273, "s": 4258, "text": "Stream In Java" }, { "code": null, "e": 4294, "s": 4273, "text": "Introduction to Java" }, { "code": null, "e": 4315, "s": 4294, "text": "Constructors in Java" }, { "code": null, "e": 4334, "s": 4315, "text": "Exceptions in Java" }, { "code": null, "e": 4351, "s": 4334, "text": "Generics in Java" }, { "code": null, "e": 4391, "s": 4351, "text": "Sed Command in Linux/Unix with examples" }, { "code": null, "e": 4431, "s": 4391, "text": "AWK command in Unix/Linux with examples" }, { "code": null, "e": 4458, "s": 4431, "text": "grep command in Unix/Linux" }, { "code": null, "e": 4493, "s": 4458, "text": "cut command in Linux with examples" } ]
Reaching a point using clockwise or anticlockwise movements
08 Jun, 2022 Given starting and ending position and a number N. Given that we are allowed to move in only four directions as shown in the image below. The directions of moves are U(), R, Dand L. We need to write a program to determine if starting from the given starting position we can reach the given end position in exactly N moves in moving about any direction(Clockwise or Anticlockwise). Examples : Input: start = U , end = L , N = 3 Output: Clockwise Explanation: Step 1: move clockwise to reach R Step 2: move clockwise to reach D Step 3: move clockwise to reach L So we reach from U to L in 3 steps moving in clockwise direction. Input: start = R , end = L , N = 3 Output: Not possible Explanation: It is not possible to start from R and end at L in 3 steps moving about in any direction. Input: start = D , end = R , N = 7 Output: Clockwise Explanation: Starting at D, we complete one complete clockwise round in 4 steps to reach D again, then it takes 3 step to reach R The idea to solve this problem is to observe that we can complete one round in 4 steps by traveling in any direction (clockwise or anti-clockwise), so taking n%4 steps is equivalent to taking n steps from the starting point. Therefore n is reduced to n%4. Consider the values of ‘U’ as 0, ‘R’ as 1, ‘D’ as 2 and ‘L’ as 3. If the abs(value(a)-value(b)) is 2 and n is also 2, then we can move either in clockwise or anticlockwise direction to reach the end position from the start position. If moving k steps in clockwise direction take us to the end position from start position then we can say that the condition for clockwise move will be (value(a)+k)%4==value(b). Similarly, the condition for anticlockwise move will be (value(a)+k*3)%4==value(b) since taking k step from position a in clockwise direction is equivalent to taking (a + k*3)%4 steps in anticlockwise direction. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP program to determine if// starting from the starting// position we can reach the // end position in N moves// moving about any direction#include <bits/stdc++.h>using namespace std; // function that returns mark// up value of directionsint value(char a){ if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3;} // function to print// the possible movevoid printMove(char a, char b, int n){ // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and the // difference between moves is 2 if (n == 2 and abs(value(a) - value(b)) == 2) cout << "Clockwise or Anticlockwise"; // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) cout << "Anticlockwise"; // clockwise condition else if ((value(a) + n) % 4 == value(b)) cout << "Clockwise"; else cout << "Not Possible";} // Driver Codeint main(){ char a = 'D', b = 'R'; int n = 7; printMove(a, b, n); return 0;} // Java program to determine if// starting from the starting// position we can reach the// end position in N moves// moving about any directionclass GFG{ // function that returns mark // up value of directions static int value(char a) { if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3; return -1; } // function to print // the possible move static void printMove(char a, char b, int n) { // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and // the difference // between moves is 2 if (n == 2 && Math.abs(value(a) - value(b)) == 2) System.out.println("Clockwise " + " or Anticlockwise"); // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) System.out.println("Anticlockwise"); // clockwise condition else if ((value(a) + n) % 4 == value(b)) System.out.println("Clockwise"); else System.out.println("Not Possible"); } // Driver Code public static void main(String args[]) { char a = 'D', b = 'R'; int n = 7; printMove(a, b, n); }} // This code is contributed by Sam007 # python program to determine# if starting from the starting# position we can reach the end# position in N moves moving # any direction # function that returns mark# up value of directionsdef value(a): if (a == 'U'): return 0 if (a == 'R'): return 1 if (a == 'D'): return 2 if (a == 'L'): return 3 # function to print# the possible movedef printMove(a, b, n): # mod with 4 as completing # 4 steps means completing # one single round n = n % 4; # when n is 2 and # the difference # between moves is 2 if (n == 2 and abs(value(a) - value(b)) == 2): print ("Clockwise or Anticlockwise") # anticlockwise condition elif ((value(a) + n * 3) % 4 == value(b)): print ("Anticlockwise") # clockwise condition elif ((value(a) + n) % 4 == value(b)): print ("Clockwise") else: print ("Not Possible") # Driver Codea = 'D'b = 'R'n = 7printMove(a, b, n) # This code is contributed by Sam007. // C# program to determine// if starting from the// starting position we// can reach the end position// in N moves moving about// any directionusing System; class GFG{ // function that returns mark // up value of directions static int value(char a) { if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3; return -1; } // function to print // the possible move static void printMove(char a, char b, int n) { // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and // the difference // between moves is 2 if (n == 2 && Math.Abs(value(a) - value(b)) == 2) Console.Write("Clockwise " + "or Anticlockwise"); // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) Console.Write("Anticlockwise"); // clockwise condition else if ((value(a) + n) % 4 == value(b)) Console.WriteLine("Clockwise"); else Console.WriteLine("Not Possible"); } // Driver Code public static void Main() { char a = 'D', b = 'R'; int n = 7; printMove(a, b, n); }} // This code is contributed by Sam007 <?php// PHP program to determine// if starting from the// starting position we can// reach the end position in// N moves moving about// any direction // function that returns mark// up value of directions function value($a){ if ($a == 'U') return 0; if ($a == 'R') return 1; if ($a == 'D') return 2; if ($a == 'L') return 3;} // function to print// the possible movefunction printMove($a, $b,$n){ // mod with 4 as completing // 4 steps means completing // one single round $n = $n % 4; // when n is 2 and the // difference between // moves is 2 if ($n == 2 and abs(value($a) - value($b)) == 2) echo "Clockwise or Anticlockwise"; // anticlockwise condition else if ((value($a) + $n * 3) % 4 == value($b)) echo "Anticlockwise"; // clockwise condition else if ((value($a) + $n) % 4 == value($b)) echo "Clockwise"; else echo "Not Possible";} // Driver Code$a = 'D'; $b = 'R';$n = 7;printMove($a, $b, $n); // This code is contributed ajit.?> <script> // JavaScript program to determine if// starting from the starting// position we can reach the// end position in N moves// moving about any direction // function that returns mark // up value of directions function value(a) { if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3; return -1; } // function to print // the possible move function printMove(a, b, n) { // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and // the difference // between moves is 2 if (n == 2 && Math.abs(value(a) - value(b)) == 2) document.write("Clockwise " + " or Anticlockwise"); // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) document.write("Anticlockwise"); // clockwise condition else if ((value(a) + n) % 4 == value(b)) document.write("Clockwise"); else document.write("Not Possible"); } // Driver code let a = 'D', b = 'R'; let n = 7; printMove(a, b, n); // This code is contributed by code_hunt.</script> Output : Clockwise Time Complexity: O(1), as we are not using any loop or recursion to traverse. Auxiliary Space: O(1), as we are not using any extra space. Sam007 jit_t Akanksha_Rai code_hunt varshagumber28 rohitkumarsinghcna programming-puzzle Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2022" }, { "code": null, "e": 411, "s": 28, "text": "Given starting and ending position and a number N. Given that we are allowed to move in only four directions as shown in the image below. The directions of moves are U(), R, Dand L. We need to write a program to determine if starting from the given starting position we can reach the given end position in exactly N moves in moving about any direction(Clockwise or Anticlockwise). " }, { "code": null, "e": 424, "s": 411, "text": "Examples : " }, { "code": null, "e": 1040, "s": 424, "text": "Input: start = U , end = L , N = 3 \nOutput: Clockwise \nExplanation: Step 1: move clockwise to reach R\n Step 2: move clockwise to reach D\n Step 3: move clockwise to reach L \nSo we reach from U to L in 3 steps moving in \nclockwise direction.\n\nInput: start = R , end = L , N = 3\nOutput: Not possible \nExplanation: It is not possible to start from \nR and end at L in 3 steps moving about in any \ndirection. \n\nInput: start = D , end = R , N = 7 \nOutput: Clockwise\nExplanation: Starting at D, we complete one \ncomplete clockwise round in 4 steps to reach D \nagain, then it takes 3 step to reach R " }, { "code": null, "e": 1973, "s": 1042, "text": "The idea to solve this problem is to observe that we can complete one round in 4 steps by traveling in any direction (clockwise or anti-clockwise), so taking n%4 steps is equivalent to taking n steps from the starting point. Therefore n is reduced to n%4. Consider the values of ‘U’ as 0, ‘R’ as 1, ‘D’ as 2 and ‘L’ as 3. If the abs(value(a)-value(b)) is 2 and n is also 2, then we can move either in clockwise or anticlockwise direction to reach the end position from the start position. If moving k steps in clockwise direction take us to the end position from start position then we can say that the condition for clockwise move will be (value(a)+k)%4==value(b). Similarly, the condition for anticlockwise move will be (value(a)+k*3)%4==value(b) since taking k step from position a in clockwise direction is equivalent to taking (a + k*3)%4 steps in anticlockwise direction. Below is the implementation of the above approach: " }, { "code": null, "e": 1977, "s": 1973, "text": "C++" }, { "code": null, "e": 1982, "s": 1977, "text": "Java" }, { "code": null, "e": 1990, "s": 1982, "text": "Python3" }, { "code": null, "e": 1993, "s": 1990, "text": "C#" }, { "code": null, "e": 1997, "s": 1993, "text": "PHP" }, { "code": null, "e": 2008, "s": 1997, "text": "Javascript" }, { "code": "// CPP program to determine if// starting from the starting// position we can reach the // end position in N moves// moving about any direction#include <bits/stdc++.h>using namespace std; // function that returns mark// up value of directionsint value(char a){ if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3;} // function to print// the possible movevoid printMove(char a, char b, int n){ // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and the // difference between moves is 2 if (n == 2 and abs(value(a) - value(b)) == 2) cout << \"Clockwise or Anticlockwise\"; // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) cout << \"Anticlockwise\"; // clockwise condition else if ((value(a) + n) % 4 == value(b)) cout << \"Clockwise\"; else cout << \"Not Possible\";} // Driver Codeint main(){ char a = 'D', b = 'R'; int n = 7; printMove(a, b, n); return 0;}", "e": 3117, "s": 2008, "text": null }, { "code": "// Java program to determine if// starting from the starting// position we can reach the// end position in N moves// moving about any directionclass GFG{ // function that returns mark // up value of directions static int value(char a) { if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3; return -1; } // function to print // the possible move static void printMove(char a, char b, int n) { // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and // the difference // between moves is 2 if (n == 2 && Math.abs(value(a) - value(b)) == 2) System.out.println(\"Clockwise \" + \" or Anticlockwise\"); // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) System.out.println(\"Anticlockwise\"); // clockwise condition else if ((value(a) + n) % 4 == value(b)) System.out.println(\"Clockwise\"); else System.out.println(\"Not Possible\"); } // Driver Code public static void main(String args[]) { char a = 'D', b = 'R'; int n = 7; printMove(a, b, n); }} // This code is contributed by Sam007", "e": 4640, "s": 3117, "text": null }, { "code": "# python program to determine# if starting from the starting# position we can reach the end# position in N moves moving # any direction # function that returns mark# up value of directionsdef value(a): if (a == 'U'): return 0 if (a == 'R'): return 1 if (a == 'D'): return 2 if (a == 'L'): return 3 # function to print# the possible movedef printMove(a, b, n): # mod with 4 as completing # 4 steps means completing # one single round n = n % 4; # when n is 2 and # the difference # between moves is 2 if (n == 2 and abs(value(a) - value(b)) == 2): print (\"Clockwise or Anticlockwise\") # anticlockwise condition elif ((value(a) + n * 3) % 4 == value(b)): print (\"Anticlockwise\") # clockwise condition elif ((value(a) + n) % 4 == value(b)): print (\"Clockwise\") else: print (\"Not Possible\") # Driver Codea = 'D'b = 'R'n = 7printMove(a, b, n) # This code is contributed by Sam007.", "e": 5644, "s": 4640, "text": null }, { "code": "// C# program to determine// if starting from the// starting position we// can reach the end position// in N moves moving about// any directionusing System; class GFG{ // function that returns mark // up value of directions static int value(char a) { if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3; return -1; } // function to print // the possible move static void printMove(char a, char b, int n) { // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and // the difference // between moves is 2 if (n == 2 && Math.Abs(value(a) - value(b)) == 2) Console.Write(\"Clockwise \" + \"or Anticlockwise\"); // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) Console.Write(\"Anticlockwise\"); // clockwise condition else if ((value(a) + n) % 4 == value(b)) Console.WriteLine(\"Clockwise\"); else Console.WriteLine(\"Not Possible\"); } // Driver Code public static void Main() { char a = 'D', b = 'R'; int n = 7; printMove(a, b, n); }} // This code is contributed by Sam007", "e": 7155, "s": 5644, "text": null }, { "code": "<?php// PHP program to determine// if starting from the// starting position we can// reach the end position in// N moves moving about// any direction // function that returns mark// up value of directions function value($a){ if ($a == 'U') return 0; if ($a == 'R') return 1; if ($a == 'D') return 2; if ($a == 'L') return 3;} // function to print// the possible movefunction printMove($a, $b,$n){ // mod with 4 as completing // 4 steps means completing // one single round $n = $n % 4; // when n is 2 and the // difference between // moves is 2 if ($n == 2 and abs(value($a) - value($b)) == 2) echo \"Clockwise or Anticlockwise\"; // anticlockwise condition else if ((value($a) + $n * 3) % 4 == value($b)) echo \"Anticlockwise\"; // clockwise condition else if ((value($a) + $n) % 4 == value($b)) echo \"Clockwise\"; else echo \"Not Possible\";} // Driver Code$a = 'D'; $b = 'R';$n = 7;printMove($a, $b, $n); // This code is contributed ajit.?>", "e": 8259, "s": 7155, "text": null }, { "code": "<script> // JavaScript program to determine if// starting from the starting// position we can reach the// end position in N moves// moving about any direction // function that returns mark // up value of directions function value(a) { if (a == 'U') return 0; if (a == 'R') return 1; if (a == 'D') return 2; if (a == 'L') return 3; return -1; } // function to print // the possible move function printMove(a, b, n) { // mod with 4 as completing // 4 steps means completing // one single round n = n % 4; // when n is 2 and // the difference // between moves is 2 if (n == 2 && Math.abs(value(a) - value(b)) == 2) document.write(\"Clockwise \" + \" or Anticlockwise\"); // anticlockwise condition else if ((value(a) + n * 3) % 4 == value(b)) document.write(\"Anticlockwise\"); // clockwise condition else if ((value(a) + n) % 4 == value(b)) document.write(\"Clockwise\"); else document.write(\"Not Possible\"); } // Driver code let a = 'D', b = 'R'; let n = 7; printMove(a, b, n); // This code is contributed by code_hunt.</script>", "e": 9679, "s": 8259, "text": null }, { "code": null, "e": 9690, "s": 9679, "text": "Output : " }, { "code": null, "e": 9700, "s": 9690, "text": "Clockwise" }, { "code": null, "e": 9779, "s": 9700, "text": " Time Complexity: O(1), as we are not using any loop or recursion to traverse." }, { "code": null, "e": 9839, "s": 9779, "text": "Auxiliary Space: O(1), as we are not using any extra space." }, { "code": null, "e": 9846, "s": 9839, "text": "Sam007" }, { "code": null, "e": 9852, "s": 9846, "text": "jit_t" }, { "code": null, "e": 9865, "s": 9852, "text": "Akanksha_Rai" }, { "code": null, "e": 9875, "s": 9865, "text": "code_hunt" }, { "code": null, "e": 9890, "s": 9875, "text": "varshagumber28" }, { "code": null, "e": 9909, "s": 9890, "text": "rohitkumarsinghcna" }, { "code": null, "e": 9928, "s": 9909, "text": "programming-puzzle" }, { "code": null, "e": 9941, "s": 9928, "text": "Mathematical" }, { "code": null, "e": 9960, "s": 9941, "text": "School Programming" }, { "code": null, "e": 9973, "s": 9960, "text": "Mathematical" } ]
How to set default value to NULL in MySQL?
Use DEFAULT keyword in MySQL to set default value to NULL. Let us first create a − mysql> create table DemoTable1440 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20) DEFAULT NULL, -> StudentAge int DEFAULT NULL -> ); Query OK, 0 rows affected (0.55 sec) Insert some records in the table using insert command. For values left blank, the default gets inserted − mysql> insert into DemoTable1440(StudentName,StudentAge) values('Chris',21); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1440 values(); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1440(StudentName) values('David'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1440(StudentAge) values(24); Query OK, 1 row affected (0.09 sec) Display all records from the table using select − mysql> select * from DemoTable1440; This will produce the following output − +-----------+-------------+------------+ | StudentId | StudentName | StudentAge | +-----------+-------------+------------+ | 1 | Chris | 21 | | 2 | NULL | NULL | | 3 | David | NULL | | 4 | NULL | 24 | +-----------+-------------+------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1270, "s": 1187, "text": "Use DEFAULT keyword in MySQL to set default value to NULL. Let us first create a −" }, { "code": null, "e": 1493, "s": 1270, "text": "mysql> create table DemoTable1440\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentName varchar(20) DEFAULT NULL,\n -> StudentAge int DEFAULT NULL\n -> );\nQuery OK, 0 rows affected (0.55 sec)" }, { "code": null, "e": 1599, "s": 1493, "text": "Insert some records in the table using insert command. For values left blank, the default gets inserted −" }, { "code": null, "e": 1983, "s": 1599, "text": "mysql> insert into DemoTable1440(StudentName,StudentAge) values('Chris',21);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable1440 values();\nQuery OK, 1 row affected (0.10 sec)\nmysql> insert into DemoTable1440(StudentName) values('David');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1440(StudentAge) values(24);\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 2033, "s": 1983, "text": "Display all records from the table using select −" }, { "code": null, "e": 2069, "s": 2033, "text": "mysql> select * from DemoTable1440;" }, { "code": null, "e": 2110, "s": 2069, "text": "This will produce the following output −" }, { "code": null, "e": 2463, "s": 2110, "text": "+-----------+-------------+------------+\n| StudentId | StudentName | StudentAge |\n+-----------+-------------+------------+\n| 1 | Chris | 21 |\n| 2 | NULL | NULL |\n| 3 | David | NULL |\n| 4 | NULL | 24 |\n+-----------+-------------+------------+\n4 rows in set (0.00 sec)" } ]
How to Change ActionBar Title Programmatically in Android?
11 Aug, 2021 Whenever we develop an Android application and run it, we often observe that the application comes with an ActionBar with the name of the application in it. This happens by default unless explicitly changed. This text is called the title in the application. One can change the title of the application by making changes to the app_name string present in the values. But, if an application has more than one activity, all of these activities will have the same title. Suppose we have MainActivity, SecondActivity, and ThirdActivity. While navigating, one can observe that all of them will have the same title, i.e. name of the application. So through this article, we will show how you can dynamically change the title of the application at runtime. You can apply the same concept if there is more than one activity to distinguish among them. Step 1: Create a New Project in Android Studio To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project. Step 2: Working with the activity_main.xml file Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add EditText and a Button in the layout file. We shall type the desired title in the EditText and click the button which would perform the title change operation. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- Type something in this EditText to change the ActionBar text --> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true"/> <!-- Click this button to make changes --> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Change Text" android:layout_centerHorizontal="true" android:layout_below="@id/editText"/> </RelativeLayout> Step 4: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing EditText // and Button from the layout file val mEditText = findViewById<EditText>(R.id.editText) val mButtonText = findViewById<Button>(R.id.button1) // When the button is clicked mButtonText.setOnClickListener { // If the EditText field is not empty, // the ActionBar title will change // Else, the application will display a Toast message if(mEditText.text.isNotEmpty()){ title = mEditText.text.toString() } else { Toast.makeText(applicationContext, "No input", Toast.LENGTH_SHORT).show() } } }} Output: You can see that we are able to change the title at runtime. Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Aug, 2021" }, { "code": null, "e": 394, "s": 28, "text": "Whenever we develop an Android application and run it, we often observe that the application comes with an ActionBar with the name of the application in it. This happens by default unless explicitly changed. This text is called the title in the application. One can change the title of the application by making changes to the app_name string present in the values." }, { "code": null, "e": 870, "s": 394, "text": "But, if an application has more than one activity, all of these activities will have the same title. Suppose we have MainActivity, SecondActivity, and ThirdActivity. While navigating, one can observe that all of them will have the same title, i.e. name of the application. So through this article, we will show how you can dynamically change the title of the application at runtime. You can apply the same concept if there is more than one activity to distinguish among them." }, { "code": null, "e": 917, "s": 870, "text": "Step 1: Create a New Project in Android Studio" }, { "code": null, "e": 1156, "s": 917, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project." }, { "code": null, "e": 1204, "s": 1156, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1509, "s": 1204, "text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add EditText and a Button in the layout file. We shall type the desired title in the EditText and click the button which would perform the title change operation." }, { "code": null, "e": 1513, "s": 1509, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- Type something in this EditText to change the ActionBar text --> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\"/> <!-- Click this button to make changes --> <Button android:id=\"@+id/button1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Change Text\" android:layout_centerHorizontal=\"true\" android:layout_below=\"@id/editText\"/> </RelativeLayout>", "e": 2435, "s": 1513, "text": null }, { "code": null, "e": 2481, "s": 2435, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 2667, "s": 2481, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 2674, "s": 2667, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.EditTextimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and initializing EditText // and Button from the layout file val mEditText = findViewById<EditText>(R.id.editText) val mButtonText = findViewById<Button>(R.id.button1) // When the button is clicked mButtonText.setOnClickListener { // If the EditText field is not empty, // the ActionBar title will change // Else, the application will display a Toast message if(mEditText.text.isNotEmpty()){ title = mEditText.text.toString() } else { Toast.makeText(applicationContext, \"No input\", Toast.LENGTH_SHORT).show() } } }}", "e": 3704, "s": 2674, "text": null }, { "code": null, "e": 3712, "s": 3704, "text": "Output:" }, { "code": null, "e": 3773, "s": 3712, "text": "You can see that we are able to change the title at runtime." }, { "code": null, "e": 3781, "s": 3773, "text": "Android" }, { "code": null, "e": 3788, "s": 3781, "text": "Kotlin" }, { "code": null, "e": 3796, "s": 3788, "text": "Android" } ]
Flutter – TabView Widget
16 Aug, 2021 There are lots of apps where you often have come across tabs. Tabs are a common pattern in the apps. They are situated at top of the app below the App bar. So today we are going to create our own app with tabs. Project Setup Code Conclusion You can either create a new project or a new file in your existing project. We don’t need any other dependencies. We need a TabController to control the tabs of our app. Here in this tutorial, we are going to use DefaultTabController because it is the simplest and accessible to all the descendants. DefaultTabController is used as the home of MaterialApp. So in the main.dart file: Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TabView Tutorial GFG', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }}class HomePage extends StatelessWidget { const HomePage({ Key? key }) : super(key: key); @override Widget build(BuildContext context) { return DefaultTabController( length: length, child: child, ); }} So as you can see we need to provide two fields, one is the length and the other is a child. These are required fields. length: Number of tabschild: The widget you want to display length: Number of tabs child: The widget you want to display Now I want 3 tabs so I am providing length with 3. Also, the child will be obviously Scaffold because it is necessary. Dart DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), bottom: TabBar( tabs: [], ), ), body: TabBarView( children: [], ), ),); Here you can see two new widgets, TabBar and TabBarView. TabBar: It is used to display the top view of tabs or more specifically it displays the content of the tab. TabBarView: It is used to display the contents when a tab is pressed. So we will display Icons in the TabBar. Note: Here you should display 3 tabs or else you will get an error. Dart TabBar( tabs: [ Tab( icon: Icon(Icons.home_filled), text: "Home", ), Tab( icon: Icon(Icons.account_box_outlined), text: "Account", ), Tab( icon: Icon(Icons.alarm), text: "Alarm", ), ],), Inside the TabBarView widget, we need three children widgets, and they can be anything. So I will display just Icons for the simplicity of the tutorial. Dart TabBarView( children: [ Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ) ],), Now run the App. TabBarView app Now if you have lots of tabs, like 5 or 6 we can use the isScrollable field in the TabView. If it is false, it shrinks all the tabs within the screen and if it is true it makes scrollable Tabs. You can change the length to 6 and duplicate all the tabs under TabBar and TabBarView. Dart DefaultTabController( length: 6, child: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), bottom: TabBar( isScrollable: true, tabs: [ Tab( icon: Icon(Icons.home_filled), text: "Home", ), Tab( icon: Icon(Icons.account_box_outlined), text: "Account", ), Tab( icon: Icon(Icons.alarm), text: "Alarm", ), Tab( icon: Icon(Icons.home_filled), text: "Home", ), Tab( icon: Icon(Icons.account_box_outlined), text: "Account", ), Tab( icon: Icon(Icons.alarm), text: "Alarm", ), ], ), ), body: TabBarView( children: [ Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ), Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ) ], ), ),); Now run the app again. More tabs TabView App Now clear the duplicate code. Here is the full code. Dart import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TabView Tutorial GFG', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatelessWidget { const HomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text("GeeksForGeeks"), bottom: TabBar( tabs: [ Tab( icon: Icon(Icons.home_filled), text: "Home", ), Tab( icon: Icon(Icons.account_box_outlined), text: "Account", ), Tab( icon: Icon(Icons.alarm), text: "Alarm", ), ], ), ), body: TabBarView( children: [ Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ) ], ), ), ); }} So we learned a new widget TabView and we created a very basic app. But we can make beautiful apps with this very simple and easy widget. It comes with all the necessary animations and snapping which makes settings up very easily an app with tabs. If you have any doubts comment below. Flutter-widgets Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ListView Class in Flutter Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget Flutter Tutorial Flutter - Search Bar Flutter - Dialogs Flutter - FutureBuilder Widget Flutter - Flexible Widget
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Aug, 2021" }, { "code": null, "e": 239, "s": 28, "text": "There are lots of apps where you often have come across tabs. Tabs are a common pattern in the apps. They are situated at top of the app below the App bar. So today we are going to create our own app with tabs." }, { "code": null, "e": 253, "s": 239, "text": "Project Setup" }, { "code": null, "e": 258, "s": 253, "text": "Code" }, { "code": null, "e": 269, "s": 258, "text": "Conclusion" }, { "code": null, "e": 346, "s": 269, "text": "You can either create a new project or a new file in your existing project. " }, { "code": null, "e": 384, "s": 346, "text": "We don’t need any other dependencies." }, { "code": null, "e": 571, "s": 384, "text": "We need a TabController to control the tabs of our app. Here in this tutorial, we are going to use DefaultTabController because it is the simplest and accessible to all the descendants. " }, { "code": null, "e": 629, "s": 571, "text": "DefaultTabController is used as the home of MaterialApp. " }, { "code": null, "e": 655, "s": 629, "text": "So in the main.dart file:" }, { "code": null, "e": 660, "s": 655, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TabView Tutorial GFG', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }}class HomePage extends StatelessWidget { const HomePage({ Key? key }) : super(key: key); @override Widget build(BuildContext context) { return DefaultTabController( length: length, child: child, ); }}", "e": 1273, "s": 660, "text": null }, { "code": null, "e": 1393, "s": 1273, "text": "So as you can see we need to provide two fields, one is the length and the other is a child. These are required fields." }, { "code": null, "e": 1453, "s": 1393, "text": "length: Number of tabschild: The widget you want to display" }, { "code": null, "e": 1476, "s": 1453, "text": "length: Number of tabs" }, { "code": null, "e": 1514, "s": 1476, "text": "child: The widget you want to display" }, { "code": null, "e": 1633, "s": 1514, "text": "Now I want 3 tabs so I am providing length with 3. Also, the child will be obviously Scaffold because it is necessary." }, { "code": null, "e": 1638, "s": 1633, "text": "Dart" }, { "code": "DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), bottom: TabBar( tabs: [], ), ), body: TabBarView( children: [], ), ),);", "e": 1848, "s": 1638, "text": null }, { "code": null, "e": 1905, "s": 1848, "text": "Here you can see two new widgets, TabBar and TabBarView." }, { "code": null, "e": 2013, "s": 1905, "text": "TabBar: It is used to display the top view of tabs or more specifically it displays the content of the tab." }, { "code": null, "e": 2083, "s": 2013, "text": "TabBarView: It is used to display the contents when a tab is pressed." }, { "code": null, "e": 2124, "s": 2083, "text": "So we will display Icons in the TabBar. " }, { "code": null, "e": 2192, "s": 2124, "text": "Note: Here you should display 3 tabs or else you will get an error." }, { "code": null, "e": 2197, "s": 2192, "text": "Dart" }, { "code": "TabBar( tabs: [ Tab( icon: Icon(Icons.home_filled), text: \"Home\", ), Tab( icon: Icon(Icons.account_box_outlined), text: \"Account\", ), Tab( icon: Icon(Icons.alarm), text: \"Alarm\", ), ],),", "e": 2434, "s": 2197, "text": null }, { "code": null, "e": 2522, "s": 2434, "text": "Inside the TabBarView widget, we need three children widgets, and they can be anything." }, { "code": null, "e": 2587, "s": 2522, "text": "So I will display just Icons for the simplicity of the tutorial." }, { "code": null, "e": 2592, "s": 2587, "text": "Dart" }, { "code": "TabBarView( children: [ Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ) ],),", "e": 2774, "s": 2592, "text": null }, { "code": null, "e": 2791, "s": 2774, "text": "Now run the App." }, { "code": null, "e": 2806, "s": 2791, "text": "TabBarView app" }, { "code": null, "e": 3000, "s": 2806, "text": "Now if you have lots of tabs, like 5 or 6 we can use the isScrollable field in the TabView. If it is false, it shrinks all the tabs within the screen and if it is true it makes scrollable Tabs." }, { "code": null, "e": 3087, "s": 3000, "text": "You can change the length to 6 and duplicate all the tabs under TabBar and TabBarView." }, { "code": null, "e": 3092, "s": 3087, "text": "Dart" }, { "code": "DefaultTabController( length: 6, child: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), bottom: TabBar( isScrollable: true, tabs: [ Tab( icon: Icon(Icons.home_filled), text: \"Home\", ), Tab( icon: Icon(Icons.account_box_outlined), text: \"Account\", ), Tab( icon: Icon(Icons.alarm), text: \"Alarm\", ), Tab( icon: Icon(Icons.home_filled), text: \"Home\", ), Tab( icon: Icon(Icons.account_box_outlined), text: \"Account\", ), Tab( icon: Icon(Icons.alarm), text: \"Alarm\", ), ], ), ), body: TabBarView( children: [ Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ), Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ) ], ), ),);", "e": 4290, "s": 3092, "text": null }, { "code": null, "e": 4313, "s": 4290, "text": "Now run the app again." }, { "code": null, "e": 4335, "s": 4313, "text": "More tabs TabView App" }, { "code": null, "e": 4388, "s": 4335, "text": "Now clear the duplicate code. Here is the full code." }, { "code": null, "e": 4393, "s": 4388, "text": "Dart" }, { "code": "import 'package:flutter/material.dart'; void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'TabView Tutorial GFG', theme: ThemeData( primarySwatch: Colors.green, ), home: HomePage(), ); }} class HomePage extends StatelessWidget { const HomePage({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text(\"GeeksForGeeks\"), bottom: TabBar( tabs: [ Tab( icon: Icon(Icons.home_filled), text: \"Home\", ), Tab( icon: Icon(Icons.account_box_outlined), text: \"Account\", ), Tab( icon: Icon(Icons.alarm), text: \"Alarm\", ), ], ), ), body: TabBarView( children: [ Center( child: Icon(Icons.home), ), Center( child: Icon(Icons.account_circle), ), Center( child: Icon(Icons.alarm), ) ], ), ), ); }}", "e": 5762, "s": 4393, "text": null }, { "code": null, "e": 6048, "s": 5762, "text": "So we learned a new widget TabView and we created a very basic app. But we can make beautiful apps with this very simple and easy widget. It comes with all the necessary animations and snapping which makes settings up very easily an app with tabs. If you have any doubts comment below." }, { "code": null, "e": 6064, "s": 6048, "text": "Flutter-widgets" }, { "code": null, "e": 6069, "s": 6064, "text": "Dart" }, { "code": null, "e": 6077, "s": 6069, "text": "Flutter" }, { "code": null, "e": 6175, "s": 6077, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6201, "s": 6175, "text": "ListView Class in Flutter" }, { "code": null, "e": 6222, "s": 6201, "text": "Flutter - Search Bar" }, { "code": null, "e": 6240, "s": 6222, "text": "Flutter - Dialogs" }, { "code": null, "e": 6271, "s": 6240, "text": "Flutter - FutureBuilder Widget" }, { "code": null, "e": 6297, "s": 6271, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 6314, "s": 6297, "text": "Flutter Tutorial" }, { "code": null, "e": 6335, "s": 6314, "text": "Flutter - Search Bar" }, { "code": null, "e": 6353, "s": 6335, "text": "Flutter - Dialogs" }, { "code": null, "e": 6384, "s": 6353, "text": "Flutter - FutureBuilder Widget" } ]
Sparse Matrix Representations | Set 3 ( CSR )
07 Jul, 2022 If most of the elements in the matrix are zero then the matrix is called a sparse matrix. It is wasteful to store the zero elements in the matrix since they do not affect the results of our computation. This is why we implement these matrices in more efficient representations than the standard 2D Array. Using more efficient representations we can cut down space and time complexities of operations significantly.We have discussed at 4 different representations in following articles : Sparse Matrix Representation | Set 1 Sparse Matrix Representation | Set 2 . Sparse Matrix Representation | Set 1 Sparse Matrix Representation | Set 2 . In this article, we will discuss another representation of the Sparse Matrix which is commonly referred as the Yale Format.The CSR (Compressed Sparse Row) or the Yale Format is similar to the Array Representation (discussed in Set 1) of Sparse Matrix. We represent a matrix M (m * n), by three 1-D arrays or vectors called as A, IA, JA. Let NNZ denote the number of non-zero elements in M and note that 0-based indexing is used. The A vector is of size NNZ and it stores the values of the non-zero elements of the matrix. The values appear in the order of traversing the matrix row-by-row The IA vector is of size m+1 stores the cumulative number of non-zero elements upto ( not including) the i-th row. It is defined by the recursive relation : IA[0] = 0IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix IA[0] = 0 IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix The JA vector stores the column index of each element in the A vector. Thus it is of size NNZ as well. To find the no of non-zero elements in say row i, we perform IA[i+1] – IA[i]. Notice how this representation is different to the array based implementation where the second vector stores the row indices of non-zero elements.The following examples show how these matrixes are represented.Examples: Input : 0 0 0 0 5 8 0 0 0 0 3 0 0 6 0 0 Solution: When the matrix is read row by row, the A vector is [ 5 8 3 6] The JA vector stores column indices of elements in A hence, JA = [ 0 1 2 1]. IA[0] = 0. IA[1] = IA[0] + no of non-zero elements in row 0 i.e 0 + 0 = 0. Similarly, IA[2] = IA[1] + 2 = 2 IA[3] = IA[2] + 1 = 3 IA[4] = IA[3]+1 = 4 Therefore IA = [0 0 2 3 4] The trick is remember that IA[i] stores NNZ upto and not-including i row. Input : 10 20 0 0 0 0 0 30 0 4 0 0 0 0 50 60 70 0 0 0 0 0 0 80 Output : A = [10 20 30 4 50 60 70 80], IA = [0 2 4 7 8] JA = [0 1 1 3 2 3 4 5] Algorithm SPARSIFY (MATRIX) Step 1: Set M to number of rows in MATRIX Step 2: Set N to number of columns in MATRIX Step 3: I = 0, NNZ = 0. Declare A, JA, and IA. Set IA[0] to 0 Step 4: for I = 0 ... N-1 Step 5: for J = 0 ... N-1 Step 5: If MATRIX [I][J] is not zero Add MATRIX[I][J] to A Add J to JA NNZ = NNZ + 1 [End of IF] Step 6: [ End of J loop ] Add NNZ to IA [ End of I loop ] Step 7: Print vectors A, IA, JA Step 8: END CPP Java C# // CPP program to find sparse matrix rep-// resentation using CSR#include <algorithm>#include <iostream>#include <vector>using namespace std; typedef std::vector<int> vi; typedef vector<vector<int> > matrix; // Utility Function to print a Matrixvoid printMatrix(const matrix& M){ int m = M.size(); int n = M[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << M[i][j] << " "; cout << endl; }} // Utility Function to print A, IA, JA vectors// with some decoration.void printVector(const vi& V, char* msg){ cout << msg << "[ "; for_each(V.begin(), V.end(), [](int a) { cout << a << " "; }); cout << "]" << endl;} // Generate the three vectors A, IA, JAvoid sparesify(const matrix& M){ int m = M.size(); int n = M[0].size(), i, j; vi A; vi IA = { 0 }; // IA matrix has N+1 rows vi JA; int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i][j] != 0) { A.push_back(M[i][j]); JA.push_back(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.push_back(NNZ); } printMatrix(M); printVector(A, (char*)"A = "); printVector(IA, (char*)"IA = "); printVector(JA, (char*)"JA = ");} // Driver codeint main(){ matrix M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 }, }; sparesify(M); return 0;} import java.util.*; // Java program to find sparse matrix// resentation using CSR public class GFG { // Utility Function to print a Matrix private static void printMatrix(int[][] M) { int m = M.length; int n = (M.length == 0 ? 0 : M[0].length); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(M[i][j] + " "); } System.out.println(); } } // Utility Function to print A, IA, JA vectors // with some decoration. private static void printVector(ArrayList<Integer> V, String msg) { System.out.print(msg + "[ "); for (var a : V) { System.out.print(a + " "); } System.out.println("]"); } // Generate the three vectors A, IA, JA private static void sparesify(int[][] M) { int m = M.length; int n = (M.length == 0 ? 0 : M[0].length), i, j; ArrayList<Integer> A = new ArrayList<Integer>(); ArrayList<Integer> IA = new ArrayList<Integer>(); // IA matrix has N+1 // rows ArrayList<Integer> JA = new ArrayList<Integer>(); int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i][j] != 0) { A.add(M[i][j]); JA.add(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.add(NNZ); } printMatrix(M); printVector(A, "A = "); printVector(IA, "IA = "); printVector(JA, "JA = "); } // Driver code public static void main(String[] args) { int[][] M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 } }; // Function call sparesify(M); }} // This code is contributed by Aarti_Rathi // C# program to find sparse matrix// resentation using CSR using System;using System.Collections.Generic; class GFG { // Utility Function to print a Matrix static void printMatrix(int[, ] M) { int m = M.GetLength(0); int n = M.GetLength(1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) Console.Write(M[i, j] + " "); Console.WriteLine(); } } // Utility Function to print A, IA, JA vectors // with some decoration. static void printVector(List<int> V, string msg) { Console.Write(msg + "[ "); foreach(var a in V) { Console.Write(a + " "); } Console.WriteLine("]"); } // Generate the three vectors A, IA, JA static void sparesify(int[, ] M) { int m = M.GetLength(0); int n = M.GetLength(1), i, j; List<int> A = new List<int>(); List<int> IA = new List<int>(); // IA matrix has N+1 rows List<int> JA = new List<int>(); int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i, j] != 0) { A.Add(M[i, j]); JA.Add(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.Add(NNZ); } printMatrix(M); printVector(A, "A = "); printVector(IA, "IA = "); printVector(JA, "JA = "); } // Driver code public static void Main() { int[, ] M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 }, }; // Function call sparesify(M); }} // This code is contributed by Aarti_Rathi Output: 0 0 0 0 1 5 8 0 0 0 0 0 3 0 0 0 6 0 0 1 A = [ 1 5 8 3 6 1 ] IA = [ 0 1 3 4 6 ] JA = [ 4 0 1 2 1 4 ] Time Complexity : O(n x m) Auxiliary Space: O(n + m)Notes The sparsity of the matrix = ( Total No of Elements – Number of Non Zero Elements) / ( Total No of Elements) or (1 – NNZ/mn ) or ( 1 – size(A)/mn ) . The direct array based representation required memory 3 * NNZ while CSR requires ( 2*NNZ + m + 1) memory. CSR matrices are memory efficient as long as . Similar to CSR there exits CSC which stands for Compressed Sparse Columns. It is the column analogue for CSR. The ‘New’ Yale format further compresses the A and JA vectors into 1 vector. References https://en.wikipedia.org/wiki/Sparse_matrix This article is contributed by Aarti_Rathi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. shadabahmad11 sagar0719kumar germanshephered48 sachinvinod1904 adi1212 cpp-vector Arrays Matrix Arrays Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 542, "s": 54, "text": "If most of the elements in the matrix are zero then the matrix is called a sparse matrix. It is wasteful to store the zero elements in the matrix since they do not affect the results of our computation. This is why we implement these matrices in more efficient representations than the standard 2D Array. Using more efficient representations we can cut down space and time complexities of operations significantly.We have discussed at 4 different representations in following articles : " }, { "code": null, "e": 618, "s": 542, "text": "Sparse Matrix Representation | Set 1 Sparse Matrix Representation | Set 2 ." }, { "code": null, "e": 656, "s": 618, "text": "Sparse Matrix Representation | Set 1 " }, { "code": null, "e": 695, "s": 656, "text": "Sparse Matrix Representation | Set 2 ." }, { "code": null, "e": 1126, "s": 695, "text": "In this article, we will discuss another representation of the Sparse Matrix which is commonly referred as the Yale Format.The CSR (Compressed Sparse Row) or the Yale Format is similar to the Array Representation (discussed in Set 1) of Sparse Matrix. We represent a matrix M (m * n), by three 1-D arrays or vectors called as A, IA, JA. Let NNZ denote the number of non-zero elements in M and note that 0-based indexing is used. " }, { "code": null, "e": 1286, "s": 1126, "text": "The A vector is of size NNZ and it stores the values of the non-zero elements of the matrix. The values appear in the order of traversing the matrix row-by-row" }, { "code": null, "e": 1528, "s": 1286, "text": "The IA vector is of size m+1 stores the cumulative number of non-zero elements upto ( not including) the i-th row. It is defined by the recursive relation : IA[0] = 0IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix" }, { "code": null, "e": 1538, "s": 1528, "text": "IA[0] = 0" }, { "code": null, "e": 1614, "s": 1538, "text": "IA[i] = IA[i-1] + no of non-zero elements in the (i-1) th row of the Matrix" }, { "code": null, "e": 1717, "s": 1614, "text": "The JA vector stores the column index of each element in the A vector. Thus it is of size NNZ as well." }, { "code": null, "e": 2016, "s": 1717, "text": "To find the no of non-zero elements in say row i, we perform IA[i+1] – IA[i]. Notice how this representation is different to the array based implementation where the second vector stores the row indices of non-zero elements.The following examples show how these matrixes are represented.Examples: " }, { "code": null, "e": 2852, "s": 2016, "text": "Input : 0 0 0 0\n 5 8 0 0\n 0 0 3 0\n 0 6 0 0\n\nSolution: When the matrix is read row by \n row, the A vector is [ 5 8 3 6]\n The JA vector stores column indices\n of elements in A hence, JA = [ 0 1 2 \n 1]. IA[0] = 0. IA[1] = IA[0] + no \n of non-zero elements in row 0 \n i.e 0 + 0 = 0.\n Similarly,\n IA[2] = IA[1] + 2 = 2\n IA[3] = IA[2] + 1 = 3 \n IA[4] = IA[3]+1 = 4\n Therefore IA = [0 0 2 3 4]\n The trick is remember that IA[i]\n stores NNZ upto and not-including \n i row.\n\nInput : 10 20 0 0 0 0\n 0 30 0 4 0 0\n 0 0 50 60 70 0\n 0 0 0 0 0 80\n\nOutput : A = [10 20 30 4 50 60 70 80],\n IA = [0 2 4 7 8]\n JA = [0 1 1 3 2 3 4 5]" }, { "code": null, "e": 2864, "s": 2852, "text": "Algorithm " }, { "code": null, "e": 3348, "s": 2864, "text": "SPARSIFY (MATRIX)\nStep 1: Set M to number of rows in MATRIX\nStep 2: Set N to number of columns in MATRIX\nStep 3: I = 0, NNZ = 0. Declare A, JA, and IA. \n Set IA[0] to 0\nStep 4: for I = 0 ... N-1\nStep 5: for J = 0 ... N-1\nStep 5: If MATRIX [I][J] is not zero\n Add MATRIX[I][J] to A\n Add J to JA\n NNZ = NNZ + 1\n [End of IF]\nStep 6: [ End of J loop ]\n Add NNZ to IA\n [ End of I loop ]\nStep 7: Print vectors A, IA, JA\nStep 8: END" }, { "code": null, "e": 3354, "s": 3350, "text": "CPP" }, { "code": null, "e": 3359, "s": 3354, "text": "Java" }, { "code": null, "e": 3362, "s": 3359, "text": "C#" }, { "code": "// CPP program to find sparse matrix rep-// resentation using CSR#include <algorithm>#include <iostream>#include <vector>using namespace std; typedef std::vector<int> vi; typedef vector<vector<int> > matrix; // Utility Function to print a Matrixvoid printMatrix(const matrix& M){ int m = M.size(); int n = M[0].size(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) cout << M[i][j] << \" \"; cout << endl; }} // Utility Function to print A, IA, JA vectors// with some decoration.void printVector(const vi& V, char* msg){ cout << msg << \"[ \"; for_each(V.begin(), V.end(), [](int a) { cout << a << \" \"; }); cout << \"]\" << endl;} // Generate the three vectors A, IA, JAvoid sparesify(const matrix& M){ int m = M.size(); int n = M[0].size(), i, j; vi A; vi IA = { 0 }; // IA matrix has N+1 rows vi JA; int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i][j] != 0) { A.push_back(M[i][j]); JA.push_back(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.push_back(NNZ); } printMatrix(M); printVector(A, (char*)\"A = \"); printVector(IA, (char*)\"IA = \"); printVector(JA, (char*)\"JA = \");} // Driver codeint main(){ matrix M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 }, }; sparesify(M); return 0;}", "e": 4894, "s": 3362, "text": null }, { "code": "import java.util.*; // Java program to find sparse matrix// resentation using CSR public class GFG { // Utility Function to print a Matrix private static void printMatrix(int[][] M) { int m = M.length; int n = (M.length == 0 ? 0 : M[0].length); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { System.out.print(M[i][j] + \" \"); } System.out.println(); } } // Utility Function to print A, IA, JA vectors // with some decoration. private static void printVector(ArrayList<Integer> V, String msg) { System.out.print(msg + \"[ \"); for (var a : V) { System.out.print(a + \" \"); } System.out.println(\"]\"); } // Generate the three vectors A, IA, JA private static void sparesify(int[][] M) { int m = M.length; int n = (M.length == 0 ? 0 : M[0].length), i, j; ArrayList<Integer> A = new ArrayList<Integer>(); ArrayList<Integer> IA = new ArrayList<Integer>(); // IA matrix has N+1 // rows ArrayList<Integer> JA = new ArrayList<Integer>(); int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i][j] != 0) { A.add(M[i][j]); JA.add(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.add(NNZ); } printMatrix(M); printVector(A, \"A = \"); printVector(IA, \"IA = \"); printVector(JA, \"JA = \"); } // Driver code public static void main(String[] args) { int[][] M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 } }; // Function call sparesify(M); }} // This code is contributed by Aarti_Rathi", "e": 6923, "s": 4894, "text": null }, { "code": "// C# program to find sparse matrix// resentation using CSR using System;using System.Collections.Generic; class GFG { // Utility Function to print a Matrix static void printMatrix(int[, ] M) { int m = M.GetLength(0); int n = M.GetLength(1); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) Console.Write(M[i, j] + \" \"); Console.WriteLine(); } } // Utility Function to print A, IA, JA vectors // with some decoration. static void printVector(List<int> V, string msg) { Console.Write(msg + \"[ \"); foreach(var a in V) { Console.Write(a + \" \"); } Console.WriteLine(\"]\"); } // Generate the three vectors A, IA, JA static void sparesify(int[, ] M) { int m = M.GetLength(0); int n = M.GetLength(1), i, j; List<int> A = new List<int>(); List<int> IA = new List<int>(); // IA matrix has N+1 rows List<int> JA = new List<int>(); int NNZ = 0; for (i = 0; i < m; i++) { for (j = 0; j < n; j++) { if (M[i, j] != 0) { A.Add(M[i, j]); JA.Add(j); // Count Number of Non Zero // Elements in row i NNZ++; } } IA.Add(NNZ); } printMatrix(M); printVector(A, \"A = \"); printVector(IA, \"IA = \"); printVector(JA, \"JA = \"); } // Driver code public static void Main() { int[, ] M = { { 0, 0, 0, 0, 1 }, { 5, 8, 0, 0, 0 }, { 0, 0, 3, 0, 0 }, { 0, 6, 0, 0, 1 }, }; // Function call sparesify(M); }} // This code is contributed by Aarti_Rathi", "e": 8716, "s": 6923, "text": null }, { "code": null, "e": 8726, "s": 8716, "text": "Output: " }, { "code": null, "e": 8830, "s": 8726, "text": "0 0 0 0 1 \n5 8 0 0 0 \n0 0 3 0 0 \n0 6 0 0 1 \nA = [ 1 5 8 3 6 1 ]\nIA = [ 0 1 3 4 6 ]\nJA = [ 4 0 1 2 1 4 ]" }, { "code": null, "e": 8857, "s": 8830, "text": "Time Complexity : O(n x m)" }, { "code": null, "e": 8890, "s": 8857, "text": "Auxiliary Space: O(n + m)Notes " }, { "code": null, "e": 9040, "s": 8890, "text": "The sparsity of the matrix = ( Total No of Elements – Number of Non Zero Elements) / ( Total No of Elements) or (1 – NNZ/mn ) or ( 1 – size(A)/mn ) ." }, { "code": null, "e": 9146, "s": 9040, "text": "The direct array based representation required memory 3 * NNZ while CSR requires ( 2*NNZ + m + 1) memory." }, { "code": null, "e": 9193, "s": 9146, "text": "CSR matrices are memory efficient as long as ." }, { "code": null, "e": 9303, "s": 9193, "text": "Similar to CSR there exits CSC which stands for Compressed Sparse Columns. It is the column analogue for CSR." }, { "code": null, "e": 9380, "s": 9303, "text": "The ‘New’ Yale format further compresses the A and JA vectors into 1 vector." }, { "code": null, "e": 9435, "s": 9380, "text": "References https://en.wikipedia.org/wiki/Sparse_matrix" }, { "code": null, "e": 9855, "s": 9435, "text": " This article is contributed by Aarti_Rathi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 9869, "s": 9855, "text": "shadabahmad11" }, { "code": null, "e": 9884, "s": 9869, "text": "sagar0719kumar" }, { "code": null, "e": 9902, "s": 9884, "text": "germanshephered48" }, { "code": null, "e": 9918, "s": 9902, "text": "sachinvinod1904" }, { "code": null, "e": 9926, "s": 9918, "text": "adi1212" }, { "code": null, "e": 9937, "s": 9926, "text": "cpp-vector" }, { "code": null, "e": 9944, "s": 9937, "text": "Arrays" }, { "code": null, "e": 9951, "s": 9944, "text": "Matrix" }, { "code": null, "e": 9958, "s": 9951, "text": "Arrays" }, { "code": null, "e": 9965, "s": 9958, "text": "Matrix" } ]
How to create an unordered_map of pairs in C++?
24 Mar, 2022 Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair. unordered_map can takes upto 5 arguments: Key : Type of key values Value : Type of value to be stored against the key Hash Function : A function which is used to hash the given key. If not provided it uses default hash function. Pred : A function which is used so that no two keys can have same hash values Alloc : An object used to define the memory model for the map hash_function can be anything, given that it can hash the given key.Prerequisite : How to create an unordered_map of user defined class? CPP // CPP program to demonstrate implementation of// unordered_map for a pair.#include <bits/stdc++.h>using namespace std; // A hash function used to hash a pair of any kindstruct hash_pair { template <class T1, class T2> size_t operator()(const pair<T1, T2>& p) const { auto hash1 = hash<T1>{}(p.first); auto hash2 = hash<T2>{}(p.second); if (hash1 != hash2) { return hash1 ^ hash2; } // If hash1 == hash2, their XOR is zero. return hash1; }}; int main(){ // Sending the hash function as a third argument unordered_map<pair<int, int>, bool, hash_pair> um; // Creating some pairs to be used as keys pair<int, int> p1(1000, 2000); pair<int, int> p2(2000, 3000); pair<int, int> p3(3005, 3005); pair<int, int> p4(4000, 4000); // Inserting values in the unordered_map. um[p1] = true; um[p2] = false; um[p3] = true; um[p4] = false; cout << "Contents of the unordered_map : \n"; for (auto p : um) cout << "[" << (p.first).first << ", " << (p.first).second << "] ==> " << p.second << "\n"; return 0;} Contents of the unordered_map : [4000, 4000] ==> 0 [3005, 3005] ==> 1 [1000, 2000] ==> 1 [2000, 3000] ==> 0 Note : We can create map for a pair. Check out map of pair. The reason is, map is based on self balancing BSTs and does not require a hash function.Exercise Problem : Nikhil is a travelling salesman and today he is visiting houses in a new locality to sell encyclopedias. The new city is in the from of a grid of x*y(1<=x<=10^9, 1<=y<=10^9) and at every intersection there is a house. Now he is not very good with remembering the houses that he has already visited, so whenever he goes into a house he tells you the coordinate of the house. Your job is to remember the coordinate and at the end of the day tell him all the houses that he visited on that day.Examples: Input : Enter the number of houses that he visited today :5 Enter the coordinate of HouseNo. 1 :1000 12985 Enter the coordinate of HouseNo. 2 :12548 25621 Enter the coordinate of HouseNo. 3 :14586 26481 Enter the coordinate of HouseNo. 4 :12 63 Enter the coordinate of HouseNo. 5 :14689 36945 Output : Houses that he visited today: 12 63 14689 36945 14586 26481 1000 12985 12548 25621 joshuahernandez cpp-pair cpp-unordered_map Picked STL Technical Scripter 2018 C++ Technical Scripter STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Pair in C++ Standard Template Library (STL) Friend class and function in C++ std::string class in C++ Queue in C++ Standard Template Library (STL) std::find in C++ Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) vector insert() function in C++ STL
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Mar, 2022" }, { "code": null, "e": 298, "s": 52, "text": "Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair. unordered_map can takes upto 5 arguments: " }, { "code": null, "e": 323, "s": 298, "text": "Key : Type of key values" }, { "code": null, "e": 374, "s": 323, "text": "Value : Type of value to be stored against the key" }, { "code": null, "e": 485, "s": 374, "text": "Hash Function : A function which is used to hash the given key. If not provided it uses default hash function." }, { "code": null, "e": 563, "s": 485, "text": "Pred : A function which is used so that no two keys can have same hash values" }, { "code": null, "e": 625, "s": 563, "text": "Alloc : An object used to define the memory model for the map" }, { "code": null, "e": 763, "s": 625, "text": "hash_function can be anything, given that it can hash the given key.Prerequisite : How to create an unordered_map of user defined class? " }, { "code": null, "e": 767, "s": 763, "text": "CPP" }, { "code": "// CPP program to demonstrate implementation of// unordered_map for a pair.#include <bits/stdc++.h>using namespace std; // A hash function used to hash a pair of any kindstruct hash_pair { template <class T1, class T2> size_t operator()(const pair<T1, T2>& p) const { auto hash1 = hash<T1>{}(p.first); auto hash2 = hash<T2>{}(p.second); if (hash1 != hash2) { return hash1 ^ hash2; } // If hash1 == hash2, their XOR is zero. return hash1; }}; int main(){ // Sending the hash function as a third argument unordered_map<pair<int, int>, bool, hash_pair> um; // Creating some pairs to be used as keys pair<int, int> p1(1000, 2000); pair<int, int> p2(2000, 3000); pair<int, int> p3(3005, 3005); pair<int, int> p4(4000, 4000); // Inserting values in the unordered_map. um[p1] = true; um[p2] = false; um[p3] = true; um[p4] = false; cout << \"Contents of the unordered_map : \\n\"; for (auto p : um) cout << \"[\" << (p.first).first << \", \" << (p.first).second << \"] ==> \" << p.second << \"\\n\"; return 0;}", "e": 1928, "s": 767, "text": null }, { "code": null, "e": 2038, "s": 1928, "text": "Contents of the unordered_map : \n[4000, 4000] ==> 0\n[3005, 3005] ==> 1\n[1000, 2000] ==> 1\n[2000, 3000] ==> 0\n" }, { "code": null, "e": 2708, "s": 2038, "text": "Note : We can create map for a pair. Check out map of pair. The reason is, map is based on self balancing BSTs and does not require a hash function.Exercise Problem : Nikhil is a travelling salesman and today he is visiting houses in a new locality to sell encyclopedias. The new city is in the from of a grid of x*y(1<=x<=10^9, 1<=y<=10^9) and at every intersection there is a house. Now he is not very good with remembering the houses that he has already visited, so whenever he goes into a house he tells you the coordinate of the house. Your job is to remember the coordinate and at the end of the day tell him all the houses that he visited on that day.Examples: " }, { "code": null, "e": 3093, "s": 2708, "text": "Input : Enter the number of houses that he visited today :5 Enter the coordinate of HouseNo. 1 :1000 12985 Enter the coordinate of HouseNo. 2 :12548 25621 Enter the coordinate of HouseNo. 3 :14586 26481 Enter the coordinate of HouseNo. 4 :12 63 Enter the coordinate of HouseNo. 5 :14689 36945 Output : Houses that he visited today: 12 63 14689 36945 14586 26481 1000 12985 12548 25621" }, { "code": null, "e": 3111, "s": 3095, "text": "joshuahernandez" }, { "code": null, "e": 3120, "s": 3111, "text": "cpp-pair" }, { "code": null, "e": 3138, "s": 3120, "text": "cpp-unordered_map" }, { "code": null, "e": 3145, "s": 3138, "text": "Picked" }, { "code": null, "e": 3149, "s": 3145, "text": "STL" }, { "code": null, "e": 3173, "s": 3149, "text": "Technical Scripter 2018" }, { "code": null, "e": 3177, "s": 3173, "text": "C++" }, { "code": null, "e": 3196, "s": 3177, "text": "Technical Scripter" }, { "code": null, "e": 3200, "s": 3196, "text": "STL" }, { "code": null, "e": 3204, "s": 3200, "text": "CPP" }, { "code": null, "e": 3302, "s": 3204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3326, "s": 3302, "text": "Sorting a vector in C++" }, { "code": null, "e": 3346, "s": 3326, "text": "Polymorphism in C++" }, { "code": null, "e": 3390, "s": 3346, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3423, "s": 3390, "text": "Friend class and function in C++" }, { "code": null, "e": 3448, "s": 3423, "text": "std::string class in C++" }, { "code": null, "e": 3493, "s": 3448, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3510, "s": 3493, "text": "std::find in C++" }, { "code": null, "e": 3558, "s": 3510, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3602, "s": 3558, "text": "List in C++ Standard Template Library (STL)" } ]
Matplotlib.axes.Axes.margins() in Python
09 Jul, 2021 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.margins() function in axes module of matplotlib library is used to set or retrieve autoscaling margins. Syntax: Axes.margins(self, *margins, x=None, y=None, tight=True)Parameters: This method accepts the following parameters. *margins: This parameter is used to specify both margins of the x-axis and y-axis limits. x, y: These parameter is used to specific margin values for the x-axis and y-axis, respectively. tight : This parameter is passed to autoscale_view(), which is executed after a margin is changed. Return value: The following values are returned by this method. xmargin ymargin Below examples illustrate the matplotlib.axes.Axes.margins() function in matplotlib.axes:Example 1: Python3 # Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider, Button, RadioButtons fig, (ax, ax1) = plt.subplots(1, 2)plt.subplots_adjust(bottom = 0.25)t = np.arange(0.0, 1.0, 0.001)a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t)ax.plot(t, s, lw = 2, color = 'green') ax1.plot(t, s, lw = 2, color = 'green')ax1.margins(0.5) ax.set_title("Without margin() Function")ax1.set_title("With margin value = 0") fig.suptitle('matplotlib.axes.Axes.margins() function \Example\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: Example 2: Python3 # Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt t = np.arange(0.0, 3.0, 0.01)t1 = np.exp(-t) * np.cos(2 * np.pi * t) fig, [ax1, ax2, ax3] = plt.subplots(nrows = 3)ax1.plot(t, t1, color ="green")ax1.text(1.1, 0.65, 'Original window') ax2.margins(2, 2)ax2.plot(t, t1, color ="green")ax2.text(0, 2.0, 'Zoomed out') ax3.margins(x = 0, y =-0.25)ax3.plot(t, t1, color ="green")ax3.text(1.2, 0.35, 'Zoomed in') fig.suptitle('matplotlib.axes.Axes.margins() function\ Example\n', fontweight ="bold")fig.canvas.draw()plt.show() Output: sagartomar9927 Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Jul, 2021" }, { "code": null, "e": 329, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. " }, { "code": null, "e": 443, "s": 329, "text": "The Axes.margins() function in axes module of matplotlib library is used to set or retrieve autoscaling margins. " }, { "code": null, "e": 567, "s": 443, "text": "Syntax: Axes.margins(self, *margins, x=None, y=None, tight=True)Parameters: This method accepts the following parameters. " }, { "code": null, "e": 657, "s": 567, "text": "*margins: This parameter is used to specify both margins of the x-axis and y-axis limits." }, { "code": null, "e": 754, "s": 657, "text": "x, y: These parameter is used to specific margin values for the x-axis and y-axis, respectively." }, { "code": null, "e": 853, "s": 754, "text": "tight : This parameter is passed to autoscale_view(), which is executed after a margin is changed." }, { "code": null, "e": 919, "s": 853, "text": "Return value: The following values are returned by this method. " }, { "code": null, "e": 927, "s": 919, "text": "xmargin" }, { "code": null, "e": 935, "s": 927, "text": "ymargin" }, { "code": null, "e": 1039, "s": 937, "text": "Below examples illustrate the matplotlib.axes.Axes.margins() function in matplotlib.axes:Example 1: " }, { "code": null, "e": 1047, "s": 1039, "text": "Python3" }, { "code": "# Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider, Button, RadioButtons fig, (ax, ax1) = plt.subplots(1, 2)plt.subplots_adjust(bottom = 0.25)t = np.arange(0.0, 1.0, 0.001)a0 = 5f0 = 3delta_f = 5.0s = a0 * np.sin(2 * np.pi * f0 * t)ax.plot(t, s, lw = 2, color = 'green') ax1.plot(t, s, lw = 2, color = 'green')ax1.margins(0.5) ax.set_title(\"Without margin() Function\")ax1.set_title(\"With margin value = 0\") fig.suptitle('matplotlib.axes.Axes.margins() function \\Example\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 1644, "s": 1047, "text": null }, { "code": null, "e": 1654, "s": 1644, "text": "Output: " }, { "code": null, "e": 1667, "s": 1654, "text": "Example 2: " }, { "code": null, "e": 1675, "s": 1667, "text": "Python3" }, { "code": "# Implementation of matplotlib function import numpy as npimport matplotlib.pyplot as plt t = np.arange(0.0, 3.0, 0.01)t1 = np.exp(-t) * np.cos(2 * np.pi * t) fig, [ax1, ax2, ax3] = plt.subplots(nrows = 3)ax1.plot(t, t1, color =\"green\")ax1.text(1.1, 0.65, 'Original window') ax2.margins(2, 2)ax2.plot(t, t1, color =\"green\")ax2.text(0, 2.0, 'Zoomed out') ax3.margins(x = 0, y =-0.25)ax3.plot(t, t1, color =\"green\")ax3.text(1.2, 0.35, 'Zoomed in') fig.suptitle('matplotlib.axes.Axes.margins() function\\ Example\\n', fontweight =\"bold\")fig.canvas.draw()plt.show()", "e": 2235, "s": 1675, "text": null }, { "code": null, "e": 2245, "s": 2235, "text": "Output: " }, { "code": null, "e": 2262, "s": 2247, "text": "sagartomar9927" }, { "code": null, "e": 2280, "s": 2262, "text": "Python-matplotlib" }, { "code": null, "e": 2287, "s": 2280, "text": "Python" } ]
Concatenating CSV files using Pandas module
02 Dec, 2020 Using pandas we can perform various operations on CSV files such as appending, updating, concatenating, etc. In this article, we are going to concatenate two CSV files using pandas module. Suppose we have one .csv file named Employee.csv which contains some records and it is as below: Employee.csv There is another .csv file named Updated.csv which contains new records as well as few records from Employee.csv file but with updated information. The file is given below: Updated.csv We can see that the first five records in Updated.csv are new and the rest have updated information. For instance, the salaries of Louis and Diane are changed, email_id of Joe is different and so on. The aim of this article is to add new records and update the information of existing records from Updated.csv file into Employee.csv. Note: No two employees can have same emp_id. Approach: Whenever it comes down to manipulate data using python we make use of Dataframes. The below approach has been used. Read Employee.csv and create a dataframe, say, employee_df.. Similarly, read Updated.csv and from a dataframe, say, updated_df. Concatenate updated_df to employee_df and remove duplicates using emp_id as primary key. Create a new .csv file named Updated_Employees.csv containing all the old, new as well as updated records. Example 1: Python3 #import pandasimport pandas as pd # read Employee fileemployee_df = pd.read_csv('Employee.csv') # print employee recordsprint(employee_df) # read Updated fileupdated_df = pd.read_csv('Updated.csv') # print updated recordsprint(updated_df) # form new dataframe by combining both employee_df and updated_df# concat method appends records of updated_df to employee_df# drop_duplicates method drop rows having same emp_id keeping # only the latest insertions# resets the index to 0final_dataframe = pd.concat([employee_df, updated_df]).drop_duplicates( subset='emp_id', keep='last').reset_index(drop=True) # print old,new and updates recordsprint(final_dataframe) # export all records to a new csv filefinal_dataframe.to_csv( 'Updated_Employees.csv', index=False) Output: employee_df updated_df final_dataframe Below is the image of Updated_Employee.csv has been provided. Updated_Employees.csv Example: Below are the two CSV files which are going to be concatenated: gfg3.csv gfg2.csv Now executing the below program to concatenate the above CSV files. Python3 #import pandasimport pandas as pd # read Employee filedf1 = pd.read_csv('gfg1.csv') # print employee recordsprint('\ngfg1.csv:\n', df1) # read Updated filedf2 = pd.read_csv('gfg2.csv') # print updated recordsprint('\ngfg2.csv:\n', df2) # form new dataframe by combining both employee_df# and updated_df concat method appends records of# updated_df to employee_df drop_duplicates method # drop rows having same emp_id keeping only the# latest insertions resets the index to 0final_df = pd.concat([df1, df2]).drop_duplicates( subset='ORGANIZATION').reset_index(drop=True) # print old,new and updates recordsprint('\ngfg3.csv:\n', final_df) # export all records to a new csv filefinal_df.to_csv( 'gfg3.csv', index=False) Output: Below is the image of gfg3.csv: gfg3.csv Python pandas-io Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 217, "s": 28, "text": "Using pandas we can perform various operations on CSV files such as appending, updating, concatenating, etc. In this article, we are going to concatenate two CSV files using pandas module." }, { "code": null, "e": 314, "s": 217, "text": "Suppose we have one .csv file named Employee.csv which contains some records and it is as below:" }, { "code": null, "e": 327, "s": 314, "text": "Employee.csv" }, { "code": null, "e": 500, "s": 327, "text": "There is another .csv file named Updated.csv which contains new records as well as few records from Employee.csv file but with updated information. The file is given below:" }, { "code": null, "e": 512, "s": 500, "text": "Updated.csv" }, { "code": null, "e": 712, "s": 512, "text": "We can see that the first five records in Updated.csv are new and the rest have updated information. For instance, the salaries of Louis and Diane are changed, email_id of Joe is different and so on." }, { "code": null, "e": 847, "s": 712, "text": "The aim of this article is to add new records and update the information of existing records from Updated.csv file into Employee.csv. " }, { "code": null, "e": 892, "s": 847, "text": "Note: No two employees can have same emp_id." }, { "code": null, "e": 1019, "s": 892, "text": "Approach: Whenever it comes down to manipulate data using python we make use of Dataframes. The below approach has been used. " }, { "code": null, "e": 1080, "s": 1019, "text": "Read Employee.csv and create a dataframe, say, employee_df.." }, { "code": null, "e": 1147, "s": 1080, "text": "Similarly, read Updated.csv and from a dataframe, say, updated_df." }, { "code": null, "e": 1236, "s": 1147, "text": "Concatenate updated_df to employee_df and remove duplicates using emp_id as primary key." }, { "code": null, "e": 1343, "s": 1236, "text": "Create a new .csv file named Updated_Employees.csv containing all the old, new as well as updated records." }, { "code": null, "e": 1354, "s": 1343, "text": "Example 1:" }, { "code": null, "e": 1362, "s": 1354, "text": "Python3" }, { "code": "#import pandasimport pandas as pd # read Employee fileemployee_df = pd.read_csv('Employee.csv') # print employee recordsprint(employee_df) # read Updated fileupdated_df = pd.read_csv('Updated.csv') # print updated recordsprint(updated_df) # form new dataframe by combining both employee_df and updated_df# concat method appends records of updated_df to employee_df# drop_duplicates method drop rows having same emp_id keeping # only the latest insertions# resets the index to 0final_dataframe = pd.concat([employee_df, updated_df]).drop_duplicates( subset='emp_id', keep='last').reset_index(drop=True) # print old,new and updates recordsprint(final_dataframe) # export all records to a new csv filefinal_dataframe.to_csv( 'Updated_Employees.csv', index=False)", "e": 2135, "s": 1362, "text": null }, { "code": null, "e": 2143, "s": 2135, "text": "Output:" }, { "code": null, "e": 2155, "s": 2143, "text": "employee_df" }, { "code": null, "e": 2166, "s": 2155, "text": "updated_df" }, { "code": null, "e": 2182, "s": 2166, "text": "final_dataframe" }, { "code": null, "e": 2244, "s": 2182, "text": "Below is the image of Updated_Employee.csv has been provided." }, { "code": null, "e": 2266, "s": 2244, "text": "Updated_Employees.csv" }, { "code": null, "e": 2275, "s": 2266, "text": "Example:" }, { "code": null, "e": 2339, "s": 2275, "text": "Below are the two CSV files which are going to be concatenated:" }, { "code": null, "e": 2348, "s": 2339, "text": "gfg3.csv" }, { "code": null, "e": 2357, "s": 2348, "text": "gfg2.csv" }, { "code": null, "e": 2425, "s": 2357, "text": "Now executing the below program to concatenate the above CSV files." }, { "code": null, "e": 2433, "s": 2425, "text": "Python3" }, { "code": "#import pandasimport pandas as pd # read Employee filedf1 = pd.read_csv('gfg1.csv') # print employee recordsprint('\\ngfg1.csv:\\n', df1) # read Updated filedf2 = pd.read_csv('gfg2.csv') # print updated recordsprint('\\ngfg2.csv:\\n', df2) # form new dataframe by combining both employee_df# and updated_df concat method appends records of# updated_df to employee_df drop_duplicates method # drop rows having same emp_id keeping only the# latest insertions resets the index to 0final_df = pd.concat([df1, df2]).drop_duplicates( subset='ORGANIZATION').reset_index(drop=True) # print old,new and updates recordsprint('\\ngfg3.csv:\\n', final_df) # export all records to a new csv filefinal_df.to_csv( 'gfg3.csv', index=False)", "e": 3164, "s": 2433, "text": null }, { "code": null, "e": 3172, "s": 3164, "text": "Output:" }, { "code": null, "e": 3204, "s": 3172, "text": "Below is the image of gfg3.csv:" }, { "code": null, "e": 3213, "s": 3204, "text": "gfg3.csv" }, { "code": null, "e": 3230, "s": 3213, "text": "Python pandas-io" }, { "code": null, "e": 3244, "s": 3230, "text": "Python-pandas" }, { "code": null, "e": 3251, "s": 3244, "text": "Python" } ]
How to change font style using drop-down list in JavaScript ? - GeeksforGeeks
03 Jun, 2020 To change or set a font style for certain text, the fontFamily CSS property needs to be changed. The fontFamily property sets or returns a list of font-family names for text in an element. Syntax: object.style.fontFamily = "font" To change the font style by option dropdown: The font values can be passed in option tags using option value. Syntax: <option value="value"> The value attribute specifies the value to be sent when a form is submitted. So after the value to be sent is selected, we set the fontFamily property for the text in the element to the selected value as specified in the above syntax. In the javascript function, here changeFontStyle(), the fontFamily property value is set to the font value of the option selected. By default, it is set to Times New Roman. Example: <!DOCTYPE html><html> <head> <title> Change Font Style by Option Dropdown Javascript </title></head> <body style="text-align:center;"> <div id="output-text"> <h1 style="color:green;"> GeeksForGeeks </h1> </div> <select id="input-font" class="input" onchange="changeFontStyle (this);"> <option value="Times New Roman" selected="selected"> Times New Roman </option> <option value="Arial">Arial</option> <option value="fantasy">Fantasy</option> <option value="cursive">cursive</option> </select> <script> var changeFontStyle = function (font) { document.getElementById( "output-text").style.fontFamily = font.value; } </script></body> </html> Output: Before selecting any option (Initial value – Times New Roman): After selecting an option in dropdown: After selecting another option in dropdown: CSS-Misc HTML-Misc JavaScript-Misc Picked CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction) Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 25098, "s": 25070, "text": "\n03 Jun, 2020" }, { "code": null, "e": 25287, "s": 25098, "text": "To change or set a font style for certain text, the fontFamily CSS property needs to be changed. The fontFamily property sets or returns a list of font-family names for text in an element." }, { "code": null, "e": 25295, "s": 25287, "text": "Syntax:" }, { "code": null, "e": 25328, "s": 25295, "text": "object.style.fontFamily = \"font\"" }, { "code": null, "e": 25438, "s": 25328, "text": "To change the font style by option dropdown: The font values can be passed in option tags using option value." }, { "code": null, "e": 25446, "s": 25438, "text": "Syntax:" }, { "code": null, "e": 25469, "s": 25446, "text": "<option value=\"value\">" }, { "code": null, "e": 25877, "s": 25469, "text": "The value attribute specifies the value to be sent when a form is submitted. So after the value to be sent is selected, we set the fontFamily property for the text in the element to the selected value as specified in the above syntax. In the javascript function, here changeFontStyle(), the fontFamily property value is set to the font value of the option selected. By default, it is set to Times New Roman." }, { "code": null, "e": 25886, "s": 25877, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Change Font Style by Option Dropdown Javascript </title></head> <body style=\"text-align:center;\"> <div id=\"output-text\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> </div> <select id=\"input-font\" class=\"input\" onchange=\"changeFontStyle (this);\"> <option value=\"Times New Roman\" selected=\"selected\"> Times New Roman </option> <option value=\"Arial\">Arial</option> <option value=\"fantasy\">Fantasy</option> <option value=\"cursive\">cursive</option> </select> <script> var changeFontStyle = function (font) { document.getElementById( \"output-text\").style.fontFamily = font.value; } </script></body> </html>", "e": 26728, "s": 25886, "text": null }, { "code": null, "e": 26736, "s": 26728, "text": "Output:" }, { "code": null, "e": 26799, "s": 26736, "text": "Before selecting any option (Initial value – Times New Roman):" }, { "code": null, "e": 26838, "s": 26799, "text": "After selecting an option in dropdown:" }, { "code": null, "e": 26882, "s": 26838, "text": "After selecting another option in dropdown:" }, { "code": null, "e": 26891, "s": 26882, "text": "CSS-Misc" }, { "code": null, "e": 26901, "s": 26891, "text": "HTML-Misc" }, { "code": null, "e": 26917, "s": 26901, "text": "JavaScript-Misc" }, { "code": null, "e": 26924, "s": 26917, "text": "Picked" }, { "code": null, "e": 26928, "s": 26924, "text": "CSS" }, { "code": null, "e": 26933, "s": 26928, "text": "HTML" }, { "code": null, "e": 26944, "s": 26933, "text": "JavaScript" }, { "code": null, "e": 26961, "s": 26944, "text": "Web Technologies" }, { "code": null, "e": 26988, "s": 26961, "text": "Web technologies Questions" }, { "code": null, "e": 26993, "s": 26988, "text": "HTML" }, { "code": null, "e": 27091, "s": 26993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27149, "s": 27091, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27186, "s": 27149, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27250, "s": 27186, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27291, "s": 27250, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27328, "s": 27291, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27389, "s": 27328, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27442, "s": 27389, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27492, "s": 27442, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27516, "s": 27492, "text": "REST API (Introduction)" } ]
Difference between == and === operator in JavaScript - GeeksforGeeks
31 Jan, 2022 The ‘==’ operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison.But the ‘===’ operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false. Example 1: <script> // In R.H.S. string "9" is converted into // number 9, hence returns true. document.write(9 == "9"); // used for next line document.write('<br>') // Here no type conversion takes place, // hence returns false document.write(9 === "9"); </script> Output: true false Example 2: <script> // Here L.H.S. is a string literal whereas // R.H.S. is a string object, // due to type conversion of string object into // a string literal, it returns true. document.write("GeeksforGeeks" == new String("GeeksforGeeks")); // used for next line document.write('<br>') // No type conversion takes place document.write("GeeksforGeeks" === new String("GeeksforGeeks")); </script> Output: true false Example 3: <script> // Here number 1 is converted into true(boolean type) // as in javascript true is referred as 1 and false is // referred as 0, hence it returns true. document.write(true == '1'); // used for next line document.write('<br>') // No type conversion so it returns false document.write(true === '1'); </script> Output: true false In general “===” operator is recommended since it never does type conversion we are doing an exact comparison thus it always produces correct results. saraswatgaurang javascript-basics JavaScript-Misc javascript-operators JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Difference Between PUT and PATCH Request Node.js | fs.writeFileSync() Method Set the value of an input field in JavaScript How to read a local text file using JavaScript? How to Use the JavaScript Fetch API to Get Data? Form validation using HTML and JavaScript
[ { "code": null, "e": 24418, "s": 24390, "text": "\n31 Jan, 2022" }, { "code": null, "e": 24720, "s": 24418, "text": "The ‘==’ operator tests for abstract equality i.e. it does the necessary type conversions before doing the equality comparison.But the ‘===’ operator tests for strict equality i.e it will not do the type conversion hence if the two values are not of the same type, when compared, it will return false." }, { "code": null, "e": 24731, "s": 24720, "text": "Example 1:" }, { "code": "<script> // In R.H.S. string \"9\" is converted into // number 9, hence returns true. document.write(9 == \"9\"); // used for next line document.write('<br>') // Here no type conversion takes place, // hence returns false document.write(9 === \"9\"); </script>", "e": 25020, "s": 24731, "text": null }, { "code": null, "e": 25028, "s": 25020, "text": "Output:" }, { "code": null, "e": 25040, "s": 25028, "text": "true\nfalse\n" }, { "code": null, "e": 25051, "s": 25040, "text": "Example 2:" }, { "code": "<script> // Here L.H.S. is a string literal whereas // R.H.S. is a string object, // due to type conversion of string object into // a string literal, it returns true. document.write(\"GeeksforGeeks\" == new String(\"GeeksforGeeks\")); // used for next line document.write('<br>') // No type conversion takes place document.write(\"GeeksforGeeks\" === new String(\"GeeksforGeeks\")); </script>", "e": 25470, "s": 25051, "text": null }, { "code": null, "e": 25478, "s": 25470, "text": "Output:" }, { "code": null, "e": 25490, "s": 25478, "text": "true\nfalse\n" }, { "code": null, "e": 25501, "s": 25490, "text": "Example 3:" }, { "code": "<script> // Here number 1 is converted into true(boolean type) // as in javascript true is referred as 1 and false is // referred as 0, hence it returns true. document.write(true == '1'); // used for next line document.write('<br>') // No type conversion so it returns false document.write(true === '1'); </script>", "e": 25843, "s": 25501, "text": null }, { "code": null, "e": 25851, "s": 25843, "text": "Output:" }, { "code": null, "e": 25863, "s": 25851, "text": "true\nfalse\n" }, { "code": null, "e": 26014, "s": 25863, "text": "In general “===” operator is recommended since it never does type conversion we are doing an exact comparison thus it always produces correct results." }, { "code": null, "e": 26030, "s": 26014, "text": "saraswatgaurang" }, { "code": null, "e": 26048, "s": 26030, "text": "javascript-basics" }, { "code": null, "e": 26064, "s": 26048, "text": "JavaScript-Misc" }, { "code": null, "e": 26085, "s": 26064, "text": "javascript-operators" }, { "code": null, "e": 26096, "s": 26085, "text": "JavaScript" }, { "code": null, "e": 26194, "s": 26096, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26239, "s": 26194, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26300, "s": 26239, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26372, "s": 26300, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26418, "s": 26372, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 26459, "s": 26418, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 26495, "s": 26459, "text": "Node.js | fs.writeFileSync() Method" }, { "code": null, "e": 26541, "s": 26495, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 26589, "s": 26541, "text": "How to read a local text file using JavaScript?" }, { "code": null, "e": 26638, "s": 26589, "text": "How to Use the JavaScript Fetch API to Get Data?" } ]
Altering a database view in SAP HANA
You can alter the view, then we can use the Alter View command to alter the view. Alter view View_EmpInfo as Select Emp_Details.Id, Emp_Details.EmplName, EmpProj.Projname from Emp_Details inner join EmpProjInfo on Emp_Details.Id=EmpProjInfo.Id; We have applied ALTER command to update an existing view with name- View_EmpInfo which is applying Inner Join on two tables on Id column to create a database view.
[ { "code": null, "e": 1144, "s": 1062, "text": "You can alter the view, then we can use the Alter View command to alter the view." }, { "code": null, "e": 1308, "s": 1144, "text": "Alter view View_EmpInfo as Select Emp_Details.Id, Emp_Details.EmplName,\nEmpProj.Projname from Emp_Details inner join EmpProjInfo\non Emp_Details.Id=EmpProjInfo.Id;" }, { "code": null, "e": 1472, "s": 1308, "text": "We have applied ALTER command to update an existing view with name- View_EmpInfo which is applying Inner Join on two tables on Id column to create a database view." } ]
Create, modify, and delete columns using dplyr package in R - GeeksforGeeks
24 Oct, 2021 In this article, we will discuss mutate function present in dplyr package in R Programming Language to create, modify, and delete columns of a dataframe. Columns can be inserted either by appending a new column or using existing columns to evaluate a new column. By default, columns are added to the far right. Although columns can be added to any desired position using .before and .after arguments Syntax: mutate(dataframe , columns) Parameters: dataframe is the input dataframe columns are the new columns that are added to the dataframe .before(by default = NULL) .after(by default = NULL) Example: R library(dplyr) # create a data framed <- data.frame(FirstName=c("Suresh", "Ramesh", "Tanya", "Sujata"), Salary=c(50000, 60000, 70000, 80000), Expenses=c(20000, 15000, 30000, 25000)) print(d) # adding new columnsd <- mutate(d, Age=c(25, 28, 22, 27), Savings=Salary - Expenses) print(d) # adding a new column before FirstNamed <- mutate(d, Title=c("Mr", "Mr", "Ms", "Ms"), .before=FirstName)print(d) # adding a new column after FirstNamed <- mutate(d, LastName=c("Singh", "Pande", "Sinha", "Roy"), .after=FirstName) print(d) Output: FirstName Salary Expenses Suresh 50000 20000 Ramesh 60000 15000 Tanya 70000 30000 Sujata 80000 25000 FirstName Salary Expenses Age Savings Suresh 50000 20000 25 30000 Ramesh 60000 15000 28 45000 Tanya 70000 30000 22 40000 Sujata 80000 25000 27 55000 Title FirstName Salary Expenses Age Savings Mr Suresh 50000 20000 25 30000 Mr Ramesh 60000 15000 28 45000 Ms Tanya 70000 30000 22 40000 Ms Sujata 80000 25000 27 55000 Title FirstName LastName Salary Expenses Age Savings Mr Suresh Singh 50000 20000 25 30000 Mr Ramesh Pande 60000 15000 28 45000 Ms Tanya Sinha 70000 30000 22 40000 Ms Sujata Roy 80000 25000 27 55000 Columns can be deleted from the existing data frame by setting the value of the desired column to NULL. Syntax: mutate(dataframe,columns = NULL) Parameter: It takes only one parameter that is column name to be deleted Example: R library(dplyr) # Create a data framed <- data.frame( FirstName = c("Suresh","Ramesh","Tanya","Sujata"), Salary = c(50000,60000,70000,80000), Expenses = c(20000,15000,30000,25000)) print(d) # Delete Expenses columnd <- mutate(d,Expenses = NULL) print(d) Output: FirstName Salary Expenses Suresh 50000 20000 Ramesh 60000 15000 Tanya 70000 30000 Sujata 80000 25000 FirstName Salary Suresh 50000 Ramesh 60000 Tanya 70000 Sujata 80000 Existing columns can be modified by assigning new values to desired columns. Syntax: mutate(dataframe,column_name=new_values) Parameters: It will take two parameters dataframe is the input dataframe column_name is the name of the column to modify the values Example: R library(dplyr) # Create a data framed < - data.frame(FirstName=c("Suresh", "Ramesh", "Tanya", "Sujata"), Salary=c(50000, 60000, 70000, 80000), Expenses=c(20000, 15000, 30000, 25000)) print(d) # Modify FirstName, Salary columnd < - mutate(d, FirstName=c("Mahesh", "Jignesh", "Ria", "Tanya"), Salary=c(60000, 30000, 50000, 75000)) print(d) FirstName Salary Expenses Suresh 50000 20000 Ramesh 60000 15000 Tanya 70000 30000 Sujata 80000 25000 FirstName Salary Expenses Mahesh 60000 20000 Jignesh 30000 15000 Ria 50000 30000 Tanya 75000 25000 Picked R Dplyr R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? How to import an Excel File into R ? How to filter R dataframe by multiple conditions? Replace Specific Characters in String in R Time Series Analysis in R R - if statement
[ { "code": null, "e": 25267, "s": 25239, "text": "\n24 Oct, 2021" }, { "code": null, "e": 25421, "s": 25267, "text": "In this article, we will discuss mutate function present in dplyr package in R Programming Language to create, modify, and delete columns of a dataframe." }, { "code": null, "e": 25667, "s": 25421, "text": "Columns can be inserted either by appending a new column or using existing columns to evaluate a new column. By default, columns are added to the far right. Although columns can be added to any desired position using .before and .after arguments" }, { "code": null, "e": 25675, "s": 25667, "text": "Syntax:" }, { "code": null, "e": 25703, "s": 25675, "text": "mutate(dataframe , columns)" }, { "code": null, "e": 25715, "s": 25703, "text": "Parameters:" }, { "code": null, "e": 25748, "s": 25715, "text": "dataframe is the input dataframe" }, { "code": null, "e": 25808, "s": 25748, "text": "columns are the new columns that are added to the dataframe" }, { "code": null, "e": 25835, "s": 25808, "text": ".before(by default = NULL)" }, { "code": null, "e": 25861, "s": 25835, "text": ".after(by default = NULL)" }, { "code": null, "e": 25870, "s": 25861, "text": "Example:" }, { "code": null, "e": 25872, "s": 25870, "text": "R" }, { "code": "library(dplyr) # create a data framed <- data.frame(FirstName=c(\"Suresh\", \"Ramesh\", \"Tanya\", \"Sujata\"), Salary=c(50000, 60000, 70000, 80000), Expenses=c(20000, 15000, 30000, 25000)) print(d) # adding new columnsd <- mutate(d, Age=c(25, 28, 22, 27), Savings=Salary - Expenses) print(d) # adding a new column before FirstNamed <- mutate(d, Title=c(\"Mr\", \"Mr\", \"Ms\", \"Ms\"), .before=FirstName)print(d) # adding a new column after FirstNamed <- mutate(d, LastName=c(\"Singh\", \"Pande\", \"Sinha\", \"Roy\"), .after=FirstName) print(d)", "e": 26446, "s": 25872, "text": null }, { "code": null, "e": 26454, "s": 26446, "text": "Output:" }, { "code": null, "e": 27305, "s": 26454, "text": "FirstName Salary Expenses\n\nSuresh 50000 20000\nRamesh 60000 15000\nTanya 70000 30000\nSujata 80000 25000\n\nFirstName Salary Expenses Age Savings\n\nSuresh 50000 20000 25 30000\nRamesh 60000 15000 28 45000\nTanya 70000 30000 22 40000\nSujata 80000 25000 27 55000\n\nTitle FirstName Salary Expenses Age Savings\n\nMr Suresh 50000 20000 25 30000\nMr Ramesh 60000 15000 28 45000\nMs Tanya 70000 30000 22 40000\nMs Sujata 80000 25000 27 55000\n\nTitle FirstName LastName Salary Expenses Age Savings\n\nMr Suresh Singh 50000 20000 25 30000\nMr Ramesh Pande 60000 15000 28 45000\nMs Tanya Sinha 70000 30000 22 40000\nMs Sujata Roy 80000 25000 27 55000 " }, { "code": null, "e": 27409, "s": 27305, "text": "Columns can be deleted from the existing data frame by setting the value of the desired column to NULL." }, { "code": null, "e": 27417, "s": 27409, "text": "Syntax:" }, { "code": null, "e": 27450, "s": 27417, "text": "mutate(dataframe,columns = NULL)" }, { "code": null, "e": 27461, "s": 27450, "text": "Parameter:" }, { "code": null, "e": 27523, "s": 27461, "text": "It takes only one parameter that is column name to be deleted" }, { "code": null, "e": 27532, "s": 27523, "text": "Example:" }, { "code": null, "e": 27534, "s": 27532, "text": "R" }, { "code": "library(dplyr) # Create a data framed <- data.frame( FirstName = c(\"Suresh\",\"Ramesh\",\"Tanya\",\"Sujata\"), Salary = c(50000,60000,70000,80000), Expenses = c(20000,15000,30000,25000)) print(d) # Delete Expenses columnd <- mutate(d,Expenses = NULL) print(d)", "e": 27823, "s": 27534, "text": null }, { "code": null, "e": 27831, "s": 27823, "text": "Output:" }, { "code": null, "e": 28051, "s": 27831, "text": "FirstName Salary Expenses\n\nSuresh 50000 20000\nRamesh 60000 15000\nTanya 70000 30000\nSujata 80000 25000\n\nFirstName Salary \n\nSuresh 50000 \nRamesh 60000 \nTanya 70000\nSujata 80000 \n " }, { "code": null, "e": 28128, "s": 28051, "text": "Existing columns can be modified by assigning new values to desired columns." }, { "code": null, "e": 28136, "s": 28128, "text": "Syntax:" }, { "code": null, "e": 28178, "s": 28136, "text": " mutate(dataframe,column_name=new_values)" }, { "code": null, "e": 28218, "s": 28178, "text": "Parameters: It will take two parameters" }, { "code": null, "e": 28251, "s": 28218, "text": "dataframe is the input dataframe" }, { "code": null, "e": 28310, "s": 28251, "text": "column_name is the name of the column to modify the values" }, { "code": null, "e": 28319, "s": 28310, "text": "Example:" }, { "code": null, "e": 28321, "s": 28319, "text": "R" }, { "code": "library(dplyr) # Create a data framed < - data.frame(FirstName=c(\"Suresh\", \"Ramesh\", \"Tanya\", \"Sujata\"), Salary=c(50000, 60000, 70000, 80000), Expenses=c(20000, 15000, 30000, 25000)) print(d) # Modify FirstName, Salary columnd < - mutate(d, FirstName=c(\"Mahesh\", \"Jignesh\", \"Ria\", \"Tanya\"), Salary=c(60000, 30000, 50000, 75000)) print(d)", "e": 28708, "s": 28321, "text": null }, { "code": null, "e": 28981, "s": 28708, "text": "FirstName Salary Expenses\n\nSuresh 50000 20000\nRamesh 60000 15000\nTanya 70000 30000\nSujata 80000 25000\n\nFirstName Salary Expenses \n\nMahesh 60000 20000 \nJignesh 30000 15000 \nRia 50000 30000 \nTanya 75000 25000" }, { "code": null, "e": 28988, "s": 28981, "text": "Picked" }, { "code": null, "e": 28996, "s": 28988, "text": "R Dplyr" }, { "code": null, "e": 29007, "s": 28996, "text": "R Language" }, { "code": null, "e": 29105, "s": 29007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29157, "s": 29105, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29195, "s": 29157, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29230, "s": 29195, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29288, "s": 29230, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 29337, "s": 29288, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 29374, "s": 29337, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 29424, "s": 29374, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 29467, "s": 29424, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 29493, "s": 29467, "text": "Time Series Analysis in R" } ]
PHP - Function opendir()
resource opendir ( string $path [, resource $context] ); It opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls. path(Required) The directory path that is to be opened context(Optional) Specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream. It returns a directory handle resource on success, or FALSE on failure. Following is the usage of this function − <?php $dir = opendir("/var/www/images"); while (($file = readdir($dir)) !== false) { echo "filename: " . $file . "<br />"; } closedir($dir); ?> This will produce the following result − filename: . filename: .. filename: logo.gif filename: mohd.gif 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2815, "s": 2757, "text": "resource opendir ( string $path [, resource $context] );\n" }, { "code": null, "e": 2917, "s": 2815, "text": "It opens up a directory handle to be used in subsequent closedir(), readdir(), and rewinddir() calls." }, { "code": null, "e": 2932, "s": 2917, "text": "path(Required)" }, { "code": null, "e": 2972, "s": 2932, "text": "The directory path that is to be opened" }, { "code": null, "e": 2990, "s": 2972, "text": "context(Optional)" }, { "code": null, "e": 3107, "s": 2990, "text": "Specifies the context of the directory handle. Context is a set of options that can modify the behavior of a stream." }, { "code": null, "e": 3179, "s": 3107, "text": "It returns a directory handle resource on success, or FALSE on failure." }, { "code": null, "e": 3221, "s": 3179, "text": "Following is the usage of this function −" }, { "code": null, "e": 3384, "s": 3221, "text": "<?php\n $dir = opendir(\"/var/www/images\");\n while (($file = readdir($dir)) !== false) {\n echo \"filename: \" . $file . \"<br />\";\n }\n closedir($dir);\n?> " }, { "code": null, "e": 3425, "s": 3384, "text": "This will produce the following result −" }, { "code": null, "e": 3489, "s": 3425, "text": "filename: .\nfilename: ..\nfilename: logo.gif\nfilename: mohd.gif\n" }, { "code": null, "e": 3522, "s": 3489, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3538, "s": 3522, "text": " Malhar Lathkar" }, { "code": null, "e": 3571, "s": 3538, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3582, "s": 3571, "text": " Syed Raza" }, { "code": null, "e": 3617, "s": 3582, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3634, "s": 3617, "text": " Frahaan Hussain" }, { "code": null, "e": 3667, "s": 3634, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3682, "s": 3667, "text": " Nivedita Jain" }, { "code": null, "e": 3717, "s": 3682, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 3729, "s": 3717, "text": " Azaz Patel" }, { "code": null, "e": 3764, "s": 3729, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3792, "s": 3764, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3799, "s": 3792, "text": " Print" }, { "code": null, "e": 3810, "s": 3799, "text": " Add Notes" } ]
Breaking Spotify’s Algorithm of Music Genre Classification! | by Rajat Keshri | Towards Data Science
There are many different types of genres present in the industry. But the basic genres will have a few principle aspects that make it easier to identify them. Genres are used to tag and define different kinds of music based on the way they are composed or based on their musical form and musical style. In this article, you will learn to build your own model which will take in a song as an input and predict or classify that particular song in one of the genres. We will be classifying among the following basic genres — blues. classical, country, disco, hip hop, jazz, metal, pop, reggae and rock. The model will be build using LSTM networks. Don’t worry if you do not know what LSTM is. This article will give you a brief understanding of LSTM and its working. Here is the GitHub link to the entire project — https://github.com/rajatkeshri/Music-Genre-Prediction-Using-RNN-LSTM The entire article is divided into 4segments — PrerequisitesTheoryData PreprocessingTraining the modelPredicting on new data Prerequisites Theory Data Preprocessing Training the model Predicting on new data There are a few prerequisites you will need to have before you start this project. The first thing you would require is the dataset. The music data which I have used for this project can be downloaded from kaggle — https://www.kaggle.com/andradaolteanu/gtzan-dataset-music-genre-classification. Note that this dataset contains 10 classes with 100 songs withing each class. This might sound to be very less for a machine learning project, that is why in the next section I will show you how to increase the number of training data for each class of genre. There are a few modules which will be required for you to install in your PC/laptop in order to get started. We will be building the entire LSTM model using Tensorflow, coded in python. We will be working with python 3.6 or higher (If you are using python 2.7, it is required for you to use python 3.6 or higher for full support and functionality). The following are the required python packages to be installed — Tensorflow — Machine learning librarylibrosa — Speech processing library to extract features from songsnumpy — Mathematical model for scientific computingsklrean — Another machine learning model (We will use this library to split training and testing data)json — To jsonify the dataset (Explained in the next section)pytdub — To convert mp3 to wav files Tensorflow — Machine learning library librosa — Speech processing library to extract features from songs numpy — Mathematical model for scientific computing sklrean — Another machine learning model (We will use this library to split training and testing data) json — To jsonify the dataset (Explained in the next section) pytdub — To convert mp3 to wav files These modules can be installed using pip or conda. You can find many online sources and youtube videos on getting started with pip or conda. Once the above modules are installed, let's get coding! For any machine learning project, there are two main things in it—Feature extraction from the data and training the model. For audio and music feature extraction for machine learning purposes, usually mel-frequency cepstral coefficients (MFCCs) are extracted from the song or audio and these features are used to train the model. MFCC feature extraction is a way to extract only relevant information from audio. To explain this better, when we represent an audio file in digital format, the computer looks at it as a wave with X axis as Time and Y axis as Amplitude. This is shown in figure 1. This format of representation does not give us much information about the audio or song, hence we represent the audio in frequency domain, by using something called Fast Fourier Transform (FFT). FFT is a mathematical algorithm found its major use in signal processing, which is used to convert time domain into frequency domain. You can refer to this link or watch some youtube video on what is FFT and how exactly does it work — https://www.nti-audio.com/en/support/know-how/fast-fourier-transform-fft#:~:text=Fast%20Fourier%20Transformation%20FFT%20%2D%20Basics,frequency%20information%20about%20the%20signal. Using this FFT, we convert our input audio file and represent it in frequency and time domain. The graph which displays the audio data in frequency and time domain is called a spectogram, represented in the figure 2. A spectrogram is a bunch of FFTs stacked on top of each other. It is a way to visually represent a signal’s loudness, or amplitude, as it varies over time at different frequencies. Here, the y-axis is converted to a log scale, and the color dimension is converted to decibels (you can think of this as the log scale of the amplitude). This is done as humans can only perceive a very small and concentrated range of frequencies and amplitudes and the human ear works on the principle of a logarithmic scale. The normal spectogram can be used for extracting features, but this still contains some amount of additional information which is not required. As the human ear works on logarithmic scale and not linear scale, we use mel spectograms, which convert this spectogram into a logarithmic representation to get the features more accurately by removing or eliminating unwanted features. A mel spectrogram is a spectrogram where the frequencies are converted to the mel scale. Figure 3 shows the mel spectogram — Coming back to the main topic, the MFCCs uses a mel scale, which is used to extract the features from an audio signal, which when represented as a graph, turns out to be a mel specotgram. So in a nutshell, what we see on a mel spectorgram is the exact features we need for training our model. I have found this brilliant article which explains everything about mfccs in dept — http://practicalcryptography.com/miscellaneous/machine-learning/guide-mel-frequency-cepstral-coefficients-mfccs/. Once we have our dataset ready, we would like to train our model. Music is a time series data. That means music is linear to time. LSTM’s are pretty good at extracting patterns in input feature space, where the input data spans over long sequences. Given the gated architecture of LSTM’s that has this ability to manipulate its memory state, they are ideal for such problems. For more information, you can refer to this blog. The data set which we are going to use here is downloaded from Kaggle and has about 100 songs under each of the 10 labels or genres. Each of the songs is 30 seconds long. As mentioned earlier, this amount of data is significantly less for training an LSTM model. To encounter this problem, I split every audio file into 10 segments, each segment being 3 seconds long. Hence the number of songs under each label is now 1000, which is a decent number to train the model to achieve good accuracy. Now that we have our data ready, we need to extract the features which will be suitable to feed into our network. The feature extraction will be done by using MFCCs. Librosa is used to extract the features from each of the audio segment. We create a dictionary, with the label or category of the genre as the key and all the extracted features from all the 1000 segments as an array of features under that label. Once we do this in a loop for all 10 categories, we dump the dictionary into a JSON file. This JSON file thus becomes our dataset on which the model will be trained. Moving into the coding for dataset preprocessing, we first define the number of segments and sample rate of each segment. The sample rate is required in order to know the playback speed of the song. Here we keep it constant for every segment. dataset_path = "genres"jsonpath = "data_json"sample_rate = 22050samples_per_track = sample_rate * 30num_segment=10 We then create a loop in which we open up every song file from each genre folder and split it into 10 segments. We then extract the MFCC features for each of that segment and append it to the dictionary under the genre name (which is also the folder name). def preprocess(dataset_path,json_path, num_mfcc=13,n_fft=2048,hop_length=512, num_segment=5): data = { "mapping": [], "labels": [], "mfcc": [] } samples_per_segment = int(samples_per_track / num_segment) num_mfcc_vectors_per_segment = math.ceil(samples_per_segment / hop_length) for i, (dirpath,dirnames,filenames) in enumerate(os.walk(dataset_path)): if dirpath != dataset_path: #Adding all the labels label = str(dirpath).split('\\')[-1] data["mapping"].append(label) #Going through each song within a label for f in filenames: file_path = dataset_path +"/" + str(label) + "/" + str(f) y, sr = librosa.load(file_path, sr = sample_rate) #Cutting each song into 10 segments for n in range(num_segment): start = samples_per_segment * n finish = start + samples_per_segment #print(start,finish) mfcc = librosa.feature.mfcc(y[start:finish], sample_rate, n_mfcc = num_mfcc, n_fft = n_fft, hop_length = hop_length) mfcc = mfcc.T #259 x 13 #Making sure if if len(mfcc) == num_mfcc_vectors_per_segment: data["mfcc"].append(mfcc.tolist()) data["labels"].append(i-1) print("Track Name ", file_path, n+1) with open(json_path, "w") as fp: json.dump(data, fp, indent = 4) The above script will create segments and extract features and dump the features into data_json.json file. LSTM is used for training the model. But before we build the model, we have to load the model into our program and split it into training and testing. This is done by opening the JSON file which we created in the last section and converting it into numpy arrays for easy computation. This method is shown in the below snippet. def load_data(data_path): print("Data loading\n") with open(data_path, "r") as fp: data = json.load(fp) x = np.array(data["mfcc"]) y = np.array(data["labels"]) print("Loaded Data") return x, y After loading the data, we prepare the data and split into train and test sets, as mentioned earlier. This is done by using sklearn’s train_test_split function. The function is shown below. def prepare_datasets(test_size,val_size): #load the data x, y = load_data(data_path) x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = test_size) x_train, x_val, y_train, y_val = train_test_split(x_train,y_train,test_size = val_size) return x_train, x_val, x_test, y_train, y_val, y_test Next, the LSTM network is created using tensorflow. Here, we have created an LSTM network of 4 layers, including two hidden layers. The following code snippet shows the network creation. def build_model(input_shape): model = tf.keras.Sequential() model.add(tf.keras.layers.LSTM(64, input_shape = input_shape) model.add(tf.keras.layers.LSTM(64)) model.add(tf.keras.layers.Dense(64, activation="relu")) model.add(tf.keras.layers.Dense(10,activation = "softmax")) return model We initialize the model as sequential and add one input layer with 64 as the number of neurons in that layer, one hidden layer, one dense LSTM layer and an output layer with 10 neurons as there are 10 genres. The size of the input layer depends on the size of the MFCC coefficient which we are passing as an argument “input_shape”. You can experiment with more hidden layers and test the accuracy. Once all the methods and functions have been defined, its time to call them and train our classification model! if __name__ == "__main__": x_train, x_val, x_test, y_train, y_val, y_test = prepare_datasets(0.25, 0.2) input_shape = (x_train.shape[1],x_train.shape[2]) model = build_model(input_shape) # compile model optimiser = tf.keras.optimizers.Adam(lr=0.001) model.compile(optimizer=optimiser, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=32, epochs=50) model.save("model_RNN_LSTM.h5") print("Saved model to disk") First, we call the “prepare_datasets” function and pass the test date percentage and validation data percentage. Validation data is some part of the training data, with which the model is not trained and is used to validate the model. Validation set tells us, whether the data is performing well or not after the training is done. Next, we call the “build_model” function to build are LSTM network and compile it. Compiling is used to add the optimizer (which defines the learning rate) and the loss calculating function. Here, we have used categorical cross entropy mathematical function. You can read more about this on this link here. After compiling, model.fit() is used to train the model on our data. The training can take about 1 hour to 1.5 hours depending on your hardware. We do not want to keep training our model in order to test it, hence after training, we save the model so we can use the saved file to predict on our new data. At the end of the training, you can see the accuracy achieved. Congratulations! Our model has been trained! Now its time to check how well it predicts different songs and classifies it into different genres. Before we start with the testing and prediction of new songs, we must define the constants. ###########################################################################just_path = "genres/blues/"song_path = "genres/blues/1.wav"song_name = "1"###########################################################################Constants which depend on the model. If you train the model with different values,#need to change those values here toonum_mfcc = 13n_fft=2048hop_length = 512sample_rate = 22050samples_per_track = sample_rate * 30num_segment = 10############################################################################ If you remember, we had trained our model with songs of length 30 seconds. Hence, the model will accept song segments of 30 seconds at a time. So for this, we split the input song to be predicted into multiple segments of 30 seconds long. There are three different scenarios for this — Song length less than 30 secs, song length equal 30 secs and song length greater than 30 secs. For song length less than 30 seconds, we show an error message as minimum is not achieved and for a song of length greater than 30 seconds, we split the entire song into multiple segments of 30 seconds each and feed each segment into the model. The following snippets are for the above mentioned scenarios. #load the songx, sr = librosa.load(song_path, sr = sample_rate)song_length = int(librosa.get_duration(filename=song_path))flag = 0if song_length > 30: print("Song is greater than 30 seconds") samples_per_track_30 = sample_rate * song_length parts = int(song_length/30) samples_per_segment_30 = int(samples_per_track_30 / (parts)) flag = 1 print("Song sliced into "+str(parts)+" parts")elif song_length == 30: parts = 1 flag = 0else: print("Too short, enter a song of length minimum 30 seconds") flag = 2for i in range(0,parts): if flag == 1: print("Song snippet ",i+1) start30 = samples_per_segment_30 * i finish30 = start30 + samples_per_segment_30 y = x[start30:finish30] #print(len(y))elif flag == 0: print("Song is 30 seconds, no slicing") Next, we load the saved model and define the different classes or genres. The model will predict a number from 0 to 9, and each number will be representing a genre as defined during training. model = tf.keras.models.load_model("model_RNN_LSTM.h5") classes = ["Blues","Classical","Country","Disco","Hiphop", "Jazz","Metal","Pop","Reggae","Rock"] The model predicts some genre for each and every segment of the input song. The most predicted genres combining all the predictions of all the sliced segments of a particular input song, gives the final prediction. For example, if a song of length 120 seconds is given as input, it is first split into 3 segments of 30 seconds each and each of the segment is given as input to the model which predicts a particular genre. The genre which is predicted most number of times on average is the genre of the entire song. For prediction, we again extract the MFCC features of each segment and then call “model.predict()” to get a prediction. for n in range(num_segment): start = samples_per_segment * n finish = start + samples_per_segment #print(len(y[start:finish])) mfcc = librosa.feature.mfcc(y[start:finish], sample_rate, n_mfcc = num_mfcc, n_fft = n_fft, hop_length = hop_length) mfcc = mfcc.T mfcc = mfcc.reshape(1, mfcc.shape[0], mfcc.shape[1]) array = model.predict(mfcc)*100 array = array.tolist()#find maximum percentage class predictedclass_predictions.append(array[0].index(max(array[0])))occurence_dict = {}for i in class_predictions: if i not in occurence_dict: occurence_dict[i] = 1 else: occurence_dict[i] +=1max_key = max(occurence_dict, key=occurence_dict.get) prediction_per_part.append(classes[max_key])prediction = max(set(prediction_per_part), key = prediction_per_part.count)print(prediction) And now you know how Spotify classifies your music for you! Hope you liked reading this article. Thank you for reading.
[ { "code": null, "e": 475, "s": 172, "text": "There are many different types of genres present in the industry. But the basic genres will have a few principle aspects that make it easier to identify them. Genres are used to tag and define different kinds of music based on the way they are composed or based on their musical form and musical style." }, { "code": null, "e": 936, "s": 475, "text": "In this article, you will learn to build your own model which will take in a song as an input and predict or classify that particular song in one of the genres. We will be classifying among the following basic genres — blues. classical, country, disco, hip hop, jazz, metal, pop, reggae and rock. The model will be build using LSTM networks. Don’t worry if you do not know what LSTM is. This article will give you a brief understanding of LSTM and its working." }, { "code": null, "e": 1053, "s": 936, "text": "Here is the GitHub link to the entire project — https://github.com/rajatkeshri/Music-Genre-Prediction-Using-RNN-LSTM" }, { "code": null, "e": 1100, "s": 1053, "text": "The entire article is divided into 4segments —" }, { "code": null, "e": 1178, "s": 1100, "text": "PrerequisitesTheoryData PreprocessingTraining the modelPredicting on new data" }, { "code": null, "e": 1192, "s": 1178, "text": "Prerequisites" }, { "code": null, "e": 1199, "s": 1192, "text": "Theory" }, { "code": null, "e": 1218, "s": 1199, "text": "Data Preprocessing" }, { "code": null, "e": 1237, "s": 1218, "text": "Training the model" }, { "code": null, "e": 1260, "s": 1237, "text": "Predicting on new data" }, { "code": null, "e": 1555, "s": 1260, "text": "There are a few prerequisites you will need to have before you start this project. The first thing you would require is the dataset. The music data which I have used for this project can be downloaded from kaggle — https://www.kaggle.com/andradaolteanu/gtzan-dataset-music-genre-classification." }, { "code": null, "e": 1815, "s": 1555, "text": "Note that this dataset contains 10 classes with 100 songs withing each class. This might sound to be very less for a machine learning project, that is why in the next section I will show you how to increase the number of training data for each class of genre." }, { "code": null, "e": 2229, "s": 1815, "text": "There are a few modules which will be required for you to install in your PC/laptop in order to get started. We will be building the entire LSTM model using Tensorflow, coded in python. We will be working with python 3.6 or higher (If you are using python 2.7, it is required for you to use python 3.6 or higher for full support and functionality). The following are the required python packages to be installed —" }, { "code": null, "e": 2583, "s": 2229, "text": "Tensorflow — Machine learning librarylibrosa — Speech processing library to extract features from songsnumpy — Mathematical model for scientific computingsklrean — Another machine learning model (We will use this library to split training and testing data)json — To jsonify the dataset (Explained in the next section)pytdub — To convert mp3 to wav files" }, { "code": null, "e": 2621, "s": 2583, "text": "Tensorflow — Machine learning library" }, { "code": null, "e": 2688, "s": 2621, "text": "librosa — Speech processing library to extract features from songs" }, { "code": null, "e": 2740, "s": 2688, "text": "numpy — Mathematical model for scientific computing" }, { "code": null, "e": 2843, "s": 2740, "text": "sklrean — Another machine learning model (We will use this library to split training and testing data)" }, { "code": null, "e": 2905, "s": 2843, "text": "json — To jsonify the dataset (Explained in the next section)" }, { "code": null, "e": 2942, "s": 2905, "text": "pytdub — To convert mp3 to wav files" }, { "code": null, "e": 3139, "s": 2942, "text": "These modules can be installed using pip or conda. You can find many online sources and youtube videos on getting started with pip or conda. Once the above modules are installed, let's get coding!" }, { "code": null, "e": 3262, "s": 3139, "text": "For any machine learning project, there are two main things in it—Feature extraction from the data and training the model." }, { "code": null, "e": 3551, "s": 3262, "text": "For audio and music feature extraction for machine learning purposes, usually mel-frequency cepstral coefficients (MFCCs) are extracted from the song or audio and these features are used to train the model. MFCC feature extraction is a way to extract only relevant information from audio." }, { "code": null, "e": 3733, "s": 3551, "text": "To explain this better, when we represent an audio file in digital format, the computer looks at it as a wave with X axis as Time and Y axis as Amplitude. This is shown in figure 1." }, { "code": null, "e": 4345, "s": 3733, "text": "This format of representation does not give us much information about the audio or song, hence we represent the audio in frequency domain, by using something called Fast Fourier Transform (FFT). FFT is a mathematical algorithm found its major use in signal processing, which is used to convert time domain into frequency domain. You can refer to this link or watch some youtube video on what is FFT and how exactly does it work — https://www.nti-audio.com/en/support/know-how/fast-fourier-transform-fft#:~:text=Fast%20Fourier%20Transformation%20FFT%20%2D%20Basics,frequency%20information%20about%20the%20signal." }, { "code": null, "e": 4562, "s": 4345, "text": "Using this FFT, we convert our input audio file and represent it in frequency and time domain. The graph which displays the audio data in frequency and time domain is called a spectogram, represented in the figure 2." }, { "code": null, "e": 5069, "s": 4562, "text": "A spectrogram is a bunch of FFTs stacked on top of each other. It is a way to visually represent a signal’s loudness, or amplitude, as it varies over time at different frequencies. Here, the y-axis is converted to a log scale, and the color dimension is converted to decibels (you can think of this as the log scale of the amplitude). This is done as humans can only perceive a very small and concentrated range of frequencies and amplitudes and the human ear works on the principle of a logarithmic scale." }, { "code": null, "e": 5574, "s": 5069, "text": "The normal spectogram can be used for extracting features, but this still contains some amount of additional information which is not required. As the human ear works on logarithmic scale and not linear scale, we use mel spectograms, which convert this spectogram into a logarithmic representation to get the features more accurately by removing or eliminating unwanted features. A mel spectrogram is a spectrogram where the frequencies are converted to the mel scale. Figure 3 shows the mel spectogram —" }, { "code": null, "e": 6065, "s": 5574, "text": "Coming back to the main topic, the MFCCs uses a mel scale, which is used to extract the features from an audio signal, which when represented as a graph, turns out to be a mel specotgram. So in a nutshell, what we see on a mel spectorgram is the exact features we need for training our model. I have found this brilliant article which explains everything about mfccs in dept — http://practicalcryptography.com/miscellaneous/machine-learning/guide-mel-frequency-cepstral-coefficients-mfccs/." }, { "code": null, "e": 6491, "s": 6065, "text": "Once we have our dataset ready, we would like to train our model. Music is a time series data. That means music is linear to time. LSTM’s are pretty good at extracting patterns in input feature space, where the input data spans over long sequences. Given the gated architecture of LSTM’s that has this ability to manipulate its memory state, they are ideal for such problems. For more information, you can refer to this blog." }, { "code": null, "e": 6985, "s": 6491, "text": "The data set which we are going to use here is downloaded from Kaggle and has about 100 songs under each of the 10 labels or genres. Each of the songs is 30 seconds long. As mentioned earlier, this amount of data is significantly less for training an LSTM model. To encounter this problem, I split every audio file into 10 segments, each segment being 3 seconds long. Hence the number of songs under each label is now 1000, which is a decent number to train the model to achieve good accuracy." }, { "code": null, "e": 7564, "s": 6985, "text": "Now that we have our data ready, we need to extract the features which will be suitable to feed into our network. The feature extraction will be done by using MFCCs. Librosa is used to extract the features from each of the audio segment. We create a dictionary, with the label or category of the genre as the key and all the extracted features from all the 1000 segments as an array of features under that label. Once we do this in a loop for all 10 categories, we dump the dictionary into a JSON file. This JSON file thus becomes our dataset on which the model will be trained." }, { "code": null, "e": 7807, "s": 7564, "text": "Moving into the coding for dataset preprocessing, we first define the number of segments and sample rate of each segment. The sample rate is required in order to know the playback speed of the song. Here we keep it constant for every segment." }, { "code": null, "e": 7922, "s": 7807, "text": "dataset_path = \"genres\"jsonpath = \"data_json\"sample_rate = 22050samples_per_track = sample_rate * 30num_segment=10" }, { "code": null, "e": 8179, "s": 7922, "text": "We then create a loop in which we open up every song file from each genre folder and split it into 10 segments. We then extract the MFCC features for each of that segment and append it to the dictionary under the genre name (which is also the folder name)." }, { "code": null, "e": 9890, "s": 8179, "text": "def preprocess(dataset_path,json_path, num_mfcc=13,n_fft=2048,hop_length=512, num_segment=5): data = { \"mapping\": [], \"labels\": [], \"mfcc\": [] } samples_per_segment = int(samples_per_track / num_segment) num_mfcc_vectors_per_segment = math.ceil(samples_per_segment / hop_length) for i, (dirpath,dirnames,filenames) in enumerate(os.walk(dataset_path)): if dirpath != dataset_path: #Adding all the labels label = str(dirpath).split('\\\\')[-1] data[\"mapping\"].append(label) #Going through each song within a label for f in filenames: file_path = dataset_path +\"/\" + str(label) + \"/\" + str(f) y, sr = librosa.load(file_path, sr = sample_rate) #Cutting each song into 10 segments for n in range(num_segment): start = samples_per_segment * n finish = start + samples_per_segment #print(start,finish) mfcc = librosa.feature.mfcc(y[start:finish], sample_rate, n_mfcc = num_mfcc, n_fft = n_fft, hop_length = hop_length) mfcc = mfcc.T #259 x 13 #Making sure if if len(mfcc) == num_mfcc_vectors_per_segment: data[\"mfcc\"].append(mfcc.tolist()) data[\"labels\"].append(i-1) print(\"Track Name \", file_path, n+1) with open(json_path, \"w\") as fp: json.dump(data, fp, indent = 4)" }, { "code": null, "e": 9997, "s": 9890, "text": "The above script will create segments and extract features and dump the features into data_json.json file." }, { "code": null, "e": 10324, "s": 9997, "text": "LSTM is used for training the model. But before we build the model, we have to load the model into our program and split it into training and testing. This is done by opening the JSON file which we created in the last section and converting it into numpy arrays for easy computation. This method is shown in the below snippet." }, { "code": null, "e": 10542, "s": 10324, "text": "def load_data(data_path): print(\"Data loading\\n\") with open(data_path, \"r\") as fp: data = json.load(fp) x = np.array(data[\"mfcc\"]) y = np.array(data[\"labels\"]) print(\"Loaded Data\") return x, y" }, { "code": null, "e": 10732, "s": 10542, "text": "After loading the data, we prepare the data and split into train and test sets, as mentioned earlier. This is done by using sklearn’s train_test_split function. The function is shown below." }, { "code": null, "e": 11062, "s": 10732, "text": "def prepare_datasets(test_size,val_size): #load the data x, y = load_data(data_path) x_train, x_test, y_train, y_test = train_test_split(x,y,test_size = test_size) x_train, x_val, y_train, y_val = train_test_split(x_train,y_train,test_size = val_size) return x_train, x_val, x_test, y_train, y_val, y_test" }, { "code": null, "e": 11249, "s": 11062, "text": "Next, the LSTM network is created using tensorflow. Here, we have created an LSTM network of 4 layers, including two hidden layers. The following code snippet shows the network creation." }, { "code": null, "e": 11554, "s": 11249, "text": "def build_model(input_shape): model = tf.keras.Sequential() model.add(tf.keras.layers.LSTM(64, input_shape = input_shape) model.add(tf.keras.layers.LSTM(64)) model.add(tf.keras.layers.Dense(64, activation=\"relu\")) model.add(tf.keras.layers.Dense(10,activation = \"softmax\")) return model" }, { "code": null, "e": 11952, "s": 11554, "text": "We initialize the model as sequential and add one input layer with 64 as the number of neurons in that layer, one hidden layer, one dense LSTM layer and an output layer with 10 neurons as there are 10 genres. The size of the input layer depends on the size of the MFCC coefficient which we are passing as an argument “input_shape”. You can experiment with more hidden layers and test the accuracy." }, { "code": null, "e": 12064, "s": 11952, "text": "Once all the methods and functions have been defined, its time to call them and train our classification model!" }, { "code": null, "e": 12683, "s": 12064, "text": "if __name__ == \"__main__\": x_train, x_val, x_test, y_train, y_val, y_test = prepare_datasets(0.25, 0.2) input_shape = (x_train.shape[1],x_train.shape[2]) model = build_model(input_shape) # compile model optimiser = tf.keras.optimizers.Adam(lr=0.001) model.compile(optimizer=optimiser, loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.summary() model.fit(x_train, y_train, validation_data=(x_val, y_val), batch_size=32, epochs=50) model.save(\"model_RNN_LSTM.h5\") print(\"Saved model to disk\")" }, { "code": null, "e": 13014, "s": 12683, "text": "First, we call the “prepare_datasets” function and pass the test date percentage and validation data percentage. Validation data is some part of the training data, with which the model is not trained and is used to validate the model. Validation set tells us, whether the data is performing well or not after the training is done." }, { "code": null, "e": 13321, "s": 13014, "text": "Next, we call the “build_model” function to build are LSTM network and compile it. Compiling is used to add the optimizer (which defines the learning rate) and the loss calculating function. Here, we have used categorical cross entropy mathematical function. You can read more about this on this link here." }, { "code": null, "e": 13689, "s": 13321, "text": "After compiling, model.fit() is used to train the model on our data. The training can take about 1 hour to 1.5 hours depending on your hardware. We do not want to keep training our model in order to test it, hence after training, we save the model so we can use the saved file to predict on our new data. At the end of the training, you can see the accuracy achieved." }, { "code": null, "e": 13834, "s": 13689, "text": "Congratulations! Our model has been trained! Now its time to check how well it predicts different songs and classifies it into different genres." }, { "code": null, "e": 13926, "s": 13834, "text": "Before we start with the testing and prediction of new songs, we must define the constants." }, { "code": null, "e": 14456, "s": 13926, "text": "###########################################################################just_path = \"genres/blues/\"song_path = \"genres/blues/1.wav\"song_name = \"1\"###########################################################################Constants which depend on the model. If you train the model with different values,#need to change those values here toonum_mfcc = 13n_fft=2048hop_length = 512sample_rate = 22050samples_per_track = sample_rate * 30num_segment = 10############################################################################" }, { "code": null, "e": 15144, "s": 14456, "text": "If you remember, we had trained our model with songs of length 30 seconds. Hence, the model will accept song segments of 30 seconds at a time. So for this, we split the input song to be predicted into multiple segments of 30 seconds long. There are three different scenarios for this — Song length less than 30 secs, song length equal 30 secs and song length greater than 30 secs. For song length less than 30 seconds, we show an error message as minimum is not achieved and for a song of length greater than 30 seconds, we split the entire song into multiple segments of 30 seconds each and feed each segment into the model. The following snippets are for the above mentioned scenarios." }, { "code": null, "e": 16039, "s": 15144, "text": "#load the songx, sr = librosa.load(song_path, sr = sample_rate)song_length = int(librosa.get_duration(filename=song_path))flag = 0if song_length > 30: print(\"Song is greater than 30 seconds\") samples_per_track_30 = sample_rate * song_length parts = int(song_length/30) samples_per_segment_30 = int(samples_per_track_30 / (parts)) flag = 1 print(\"Song sliced into \"+str(parts)+\" parts\")elif song_length == 30: parts = 1 flag = 0else: print(\"Too short, enter a song of length minimum 30 seconds\") flag = 2for i in range(0,parts): if flag == 1: print(\"Song snippet \",i+1) start30 = samples_per_segment_30 * i finish30 = start30 + samples_per_segment_30 y = x[start30:finish30] #print(len(y))elif flag == 0: print(\"Song is 30 seconds, no slicing\")" }, { "code": null, "e": 16231, "s": 16039, "text": "Next, we load the saved model and define the different classes or genres. The model will predict a number from 0 to 9, and each number will be representing a genre as defined during training." }, { "code": null, "e": 16401, "s": 16231, "text": "model = tf.keras.models.load_model(\"model_RNN_LSTM.h5\") classes = [\"Blues\",\"Classical\",\"Country\",\"Disco\",\"Hiphop\", \"Jazz\",\"Metal\",\"Pop\",\"Reggae\",\"Rock\"]" }, { "code": null, "e": 17037, "s": 16401, "text": "The model predicts some genre for each and every segment of the input song. The most predicted genres combining all the predictions of all the sliced segments of a particular input song, gives the final prediction. For example, if a song of length 120 seconds is given as input, it is first split into 3 segments of 30 seconds each and each of the segment is given as input to the model which predicts a particular genre. The genre which is predicted most number of times on average is the genre of the entire song. For prediction, we again extract the MFCC features of each segment and then call “model.predict()” to get a prediction." }, { "code": null, "e": 17994, "s": 17037, "text": "for n in range(num_segment): start = samples_per_segment * n finish = start + samples_per_segment #print(len(y[start:finish])) mfcc = librosa.feature.mfcc(y[start:finish], sample_rate, n_mfcc = num_mfcc, n_fft = n_fft, hop_length = hop_length) mfcc = mfcc.T mfcc = mfcc.reshape(1, mfcc.shape[0], mfcc.shape[1]) array = model.predict(mfcc)*100 array = array.tolist()#find maximum percentage class predictedclass_predictions.append(array[0].index(max(array[0])))occurence_dict = {}for i in class_predictions: if i not in occurence_dict: occurence_dict[i] = 1 else: occurence_dict[i] +=1max_key = max(occurence_dict, key=occurence_dict.get) prediction_per_part.append(classes[max_key])prediction = max(set(prediction_per_part), key = prediction_per_part.count)print(prediction)" } ]
Check if two given Circles are Orthogonal or not - GeeksforGeeks
19 Mar, 2022 Given are two circles with their centres C1(x1, y1) and C2(x2, y2) and radius r1 and r2, the task is to check if both the circles are orthogonal or not. Two curves are said to be orthogonal if their angle of intersection is a right angle i.e the tangents at their point of intersection are perpendicular. The above two circles are orthogonal Examples: Input: C1(4, 3), C2(0, 1), r1 = 2, r2 = 4 Output: Yes Input: C1(4, 3), C2(1, 2), r1 = 2, r2 = 2 Output: No Approach: Find the distance between the centres of two circles ‘d’ with distance formula. For the circles to be orthogonal we need to check if r1 * r1 + r2 * r2 = d * d If it is true, then both the circles are orthagonal. Else not. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to check if two// circles are orthogonal or not #include <bits/stdc++.h>using namespace std; // Function to Check if the given// circles are orthogonalbool orthogonality(int x1, int y1, int x2, int y2, int r1, int r2){ // calculating the square // of the distance between C1 and C2 int dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false;} // Driver codeint main(){ int x1 = 4, y1 = 3; int x2 = 0, y2 = 1; int r1 = 2, r2 = 4; bool f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) cout << "Given circles are" << " orthogonal."; else cout << "Given circles are" << " not orthogonal."; return 0;} // Java program to check if two// circimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to Check if the given // circles are orthogonal public static boolean orthogonality(int x1, int y1, int x2, int y2, int r1, int r2) { // calculating the square // of the distance between C1 and C2 int dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false; } // Driver Code public static void main(String[] args) throws java.lang.Exception { int x1 = 4, y1 = 3; int x2 = 0, y2 = 1; int r1 = 2, r2 = 4; boolean f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) System.out.println("Given circles are orthogonal."); else System.out.println("Given circles are not orthogonal."); }} // This code is contributed by ashutosh450 # Python3 program to check if two# circles are orthogonal or not # Function to Check if the given# circles are orthogonaldef orthogonality(x1, y1, x2, y2, r1, r2): # calculating the square # of the distance between C1 and C2 dsquare = (x1 - x2) * (x1 - x2) + \ (y1 - y2) * (y1 - y2); # Check if the given # circles are orthogonal if (dsquare == r1 * r1 + r2 * r2): return True else: return False # Driver codex1, y1 = 4, 3x2, y2 = 0, 1r1, r2 = 2, 4 f = orthogonality(x1, y1, x2, y2, r1, r2) if (f): print("Given circles are orthogonal.")else: print("Given circles are not orthogonal.") # This code is contributed by Mohit Kumar // C# implementation for above programusing System; class GFG{ // Function to Check if the given // circles are orthogonal public static bool orthogonality(int x1, int y1, int x2, int y2, int r1, int r2) { // calculating the square // of the distance between C1 and C2 int dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false; } // Driver Code public static void Main() { int x1 = 4, y1 = 3; int x2 = 0, y2 = 1; int r1 = 2, r2 = 4; bool f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) Console.WriteLine("Given circles are orthogonal."); else Console.WriteLine("Given circles are not orthogonal."); }} // This code is contributed by AnkitRai01 <script> // Javascript program to check if two // circles are orthogonal or not // Function to Check if the given // circles are orthogonal function orthogonality(x1, y1, x2, y2, r1, r2) { // calculating the square // of the distance between C1 and C2 let dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false; } // Driver code let x1 = 4, y1 = 3; let x2 = 0, y2 = 1; let r1 = 2, r2 = 4; let f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) document.write("Given circles are orthogonal."); else document.write("Given circles are not orthogonal."); // This code is contributed by divyesh072019.</script> Given circles are orthogonal. Time Complexity: O(1) Auxiliary Space: O(1) mohit kumar 29 ashutosh450 ankthon divyesh072019 subham348 C++ Programs Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Closest Pair of Points using Divide and Conquer algorithm How to check if two given line segments intersect? Program for distance between two points on earth How to check if a given point lies inside or outside a polygon? Find if two rectangles overlap
[ { "code": null, "e": 24631, "s": 24603, "text": "\n19 Mar, 2022" }, { "code": null, "e": 24937, "s": 24631, "text": "Given are two circles with their centres C1(x1, y1) and C2(x2, y2) and radius r1 and r2, the task is to check if both the circles are orthogonal or not. Two curves are said to be orthogonal if their angle of intersection is a right angle i.e the tangents at their point of intersection are perpendicular. " }, { "code": null, "e": 24974, "s": 24937, "text": "The above two circles are orthogonal" }, { "code": null, "e": 24986, "s": 24974, "text": "Examples: " }, { "code": null, "e": 25096, "s": 24986, "text": "Input: C1(4, 3), C2(0, 1), r1 = 2, r2 = 4 \nOutput: Yes\n\nInput: C1(4, 3), C2(1, 2), r1 = 2, r2 = 2 \nOutput: No" }, { "code": null, "e": 25110, "s": 25098, "text": "Approach: " }, { "code": null, "e": 25190, "s": 25110, "text": "Find the distance between the centres of two circles ‘d’ with distance formula." }, { "code": null, "e": 25243, "s": 25190, "text": "For the circles to be orthogonal we need to check if" }, { "code": null, "e": 25269, "s": 25243, "text": "r1 * r1 + r2 * r2 = d * d" }, { "code": null, "e": 25332, "s": 25269, "text": "If it is true, then both the circles are orthagonal. Else not." }, { "code": null, "e": 25384, "s": 25332, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25388, "s": 25384, "text": "C++" }, { "code": null, "e": 25393, "s": 25388, "text": "Java" }, { "code": null, "e": 25401, "s": 25393, "text": "Python3" }, { "code": null, "e": 25404, "s": 25401, "text": "C#" }, { "code": null, "e": 25415, "s": 25404, "text": "Javascript" }, { "code": "// C++ program to check if two// circles are orthogonal or not #include <bits/stdc++.h>using namespace std; // Function to Check if the given// circles are orthogonalbool orthogonality(int x1, int y1, int x2, int y2, int r1, int r2){ // calculating the square // of the distance between C1 and C2 int dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false;} // Driver codeint main(){ int x1 = 4, y1 = 3; int x2 = 0, y2 = 1; int r1 = 2, r2 = 4; bool f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) cout << \"Given circles are\" << \" orthogonal.\"; else cout << \"Given circles are\" << \" not orthogonal.\"; return 0;}", "e": 26302, "s": 25415, "text": null }, { "code": "// Java program to check if two// circimport java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to Check if the given // circles are orthogonal public static boolean orthogonality(int x1, int y1, int x2, int y2, int r1, int r2) { // calculating the square // of the distance between C1 and C2 int dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false; } // Driver Code public static void main(String[] args) throws java.lang.Exception { int x1 = 4, y1 = 3; int x2 = 0, y2 = 1; int r1 = 2, r2 = 4; boolean f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) System.out.println(\"Given circles are orthogonal.\"); else System.out.println(\"Given circles are not orthogonal.\"); }} // This code is contributed by ashutosh450", "e": 27382, "s": 26302, "text": null }, { "code": "# Python3 program to check if two# circles are orthogonal or not # Function to Check if the given# circles are orthogonaldef orthogonality(x1, y1, x2, y2, r1, r2): # calculating the square # of the distance between C1 and C2 dsquare = (x1 - x2) * (x1 - x2) + \\ (y1 - y2) * (y1 - y2); # Check if the given # circles are orthogonal if (dsquare == r1 * r1 + r2 * r2): return True else: return False # Driver codex1, y1 = 4, 3x2, y2 = 0, 1r1, r2 = 2, 4 f = orthogonality(x1, y1, x2, y2, r1, r2) if (f): print(\"Given circles are orthogonal.\")else: print(\"Given circles are not orthogonal.\") # This code is contributed by Mohit Kumar", "e": 28066, "s": 27382, "text": null }, { "code": "// C# implementation for above programusing System; class GFG{ // Function to Check if the given // circles are orthogonal public static bool orthogonality(int x1, int y1, int x2, int y2, int r1, int r2) { // calculating the square // of the distance between C1 and C2 int dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false; } // Driver Code public static void Main() { int x1 = 4, y1 = 3; int x2 = 0, y2 = 1; int r1 = 2, r2 = 4; bool f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) Console.WriteLine(\"Given circles are orthogonal.\"); else Console.WriteLine(\"Given circles are not orthogonal.\"); }} // This code is contributed by AnkitRai01", "e": 29052, "s": 28066, "text": null }, { "code": "<script> // Javascript program to check if two // circles are orthogonal or not // Function to Check if the given // circles are orthogonal function orthogonality(x1, y1, x2, y2, r1, r2) { // calculating the square // of the distance between C1 and C2 let dsquare = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); // Check if the given // circles are orthogonal if (dsquare == r1 * r1 + r2 * r2) return true; else return false; } // Driver code let x1 = 4, y1 = 3; let x2 = 0, y2 = 1; let r1 = 2, r2 = 4; let f = orthogonality(x1, y1, x2, y2, r1, r2); if (f) document.write(\"Given circles are orthogonal.\"); else document.write(\"Given circles are not orthogonal.\"); // This code is contributed by divyesh072019.</script>", "e": 29967, "s": 29052, "text": null }, { "code": null, "e": 29997, "s": 29967, "text": "Given circles are orthogonal." }, { "code": null, "e": 30021, "s": 29999, "text": "Time Complexity: O(1)" }, { "code": null, "e": 30043, "s": 30021, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 30058, "s": 30043, "text": "mohit kumar 29" }, { "code": null, "e": 30070, "s": 30058, "text": "ashutosh450" }, { "code": null, "e": 30078, "s": 30070, "text": "ankthon" }, { "code": null, "e": 30092, "s": 30078, "text": "divyesh072019" }, { "code": null, "e": 30102, "s": 30092, "text": "subham348" }, { "code": null, "e": 30115, "s": 30102, "text": "C++ Programs" }, { "code": null, "e": 30125, "s": 30115, "text": "Geometric" }, { "code": null, "e": 30138, "s": 30125, "text": "Mathematical" }, { "code": null, "e": 30151, "s": 30138, "text": "Mathematical" }, { "code": null, "e": 30161, "s": 30151, "text": "Geometric" }, { "code": null, "e": 30259, "s": 30161, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30300, "s": 30259, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 30359, "s": 30300, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 30380, "s": 30359, "text": "Const keyword in C++" }, { "code": null, "e": 30392, "s": 30380, "text": "cout in C++" }, { "code": null, "e": 30413, "s": 30392, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 30471, "s": 30413, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 30522, "s": 30471, "text": "How to check if two given line segments intersect?" }, { "code": null, "e": 30571, "s": 30522, "text": "Program for distance between two points on earth" }, { "code": null, "e": 30635, "s": 30571, "text": "How to check if a given point lies inside or outside a polygon?" } ]
Python: Difference between Lock and Rlock objects
18 May, 2022 A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other codes. For simplicity, you can assume that a thread is simply a subset of a process! Refer to the below article the get the idea about threads. Multithreading in Python These are the simplest primitive for synchronization in Python. There are two states of a lock i.e locked and unlocked. A lock is a class in the threading module whose object generated in the unlocked state and has two primary methods i.e acquire() and release(). When the acquire() method is called, it locks the execution of the Lock and blocks it’s execution until the release() method is called in some other thread which sets it to unlock state. Locks help us in efficiently accessing a shared resource in a program in order to prevent corruption of data, it follows mutual exclusion as only one thread can access a particular resource at a time. Let us look at the below example to understand the use of Locks: Python3 # program to illustrate the use of Locks import threading # creating a Lock objectlock = threading.Lock() # initializing the shared resourcegeek = 0 def sumOne(): global geek # locking the shared resource lock.acquire() geek = geek + 1 # unlocking the shared resource lock.release() def sumTwo(): global geek # locking the shared resource lock.acquire() geek = geek + 2 # unlocking the shared resource lock.release() # calling the functionssumOne()sumTwo() # displaying the value of shared resourceprint(geek) Output: 3 In the above program, lock is a Lock object, the global variable geek is a shared resource and sumOne() and sumTwo() functions act as threads, in sumOne() function the shared resource geek is first locked and then incremented by 1 and then geek is released and in sumTwo() function the variable geek is first locked and then incremented by 2 and then geek is released.The two functions sumOne() and sumTwo() can not access the shared resource geek simultaneously, only one of them can access the shared resource geek at a time. The default Lock doesn’t recognize which thread the lock currently holds. If the shared resource is being accessed by any thread then other threads trying to access the shared resource will get blocked even if it is the same thread that locked the shared resource. The Re-entrant lock or RLock is used in these situations to prevent undesired blocking from accessing the shared resource. If a shared resource is in RLock then it can be called again safely. The RLocked resource can be accessed repeatedly by various threads, though it still works correctly when called by different threads. Let us look at the below example to understand the use of RLocks: Python3 import threading # initializing the shared resourcegeek = 0 # creating a Lock objectlock = threading.Lock() # the below thread is accessing the# shared resourcelock.acquire()geek = geek + 1 # This thread will be blockedlock.acquire()geek = geek + 2lock.release() # displaying the value of shared resourceprint(geek) In the above program, two threads are trying to access the shared resource geek simultaneously, here when a thread is currently accessing shared resource geek the other thread will be prevented from accessing it. When two or more threads try to access the same resource effectively prevent each other from accessing the resource this is known as deadlock due to which the above program generates no output. However, the above problem in the program can be solved by using RLock. Python3 # program to illustrate the use of RLocks # importing the moduleimport threading # initializing the shared resourcegeek = 0 # creating an RLock object instead# of Lock objectlock = threading.RLock() # the below thread is trying to access# the shared resourcelock.acquire()geek = geek + 1 # the below thread is trying to access# the shared resourcelock.acquire()geek = geek + 2lock.release()lock.release() # displaying the value of shared resourceprint(geek) Output: 3 Here, there is no unwanted prevention of accessing the shared resource geek by the threads in the program. We need to call release() once for each acquire() of RLock object lock. From the numerous programs and explanations mentioned above there are many differences between a Lock object and an RLock object in Python: sweetyty Python-multithreading Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Introduction To PYTHON Python OOPs Concepts
[ { "code": null, "e": 54, "s": 26, "text": "\n18 May, 2022" }, { "code": null, "e": 432, "s": 54, "text": "A thread is an entity within a process that can be scheduled for execution. Also, it is the smallest unit of processing that can be performed in an OS (Operating System). In simple words, a thread is a sequence of such instructions within a program that can be executed independently of other codes. For simplicity, you can assume that a thread is simply a subset of a process!" }, { "code": null, "e": 491, "s": 432, "text": "Refer to the below article the get the idea about threads." }, { "code": null, "e": 517, "s": 491, "text": "Multithreading in Python " }, { "code": null, "e": 1235, "s": 517, "text": "These are the simplest primitive for synchronization in Python. There are two states of a lock i.e locked and unlocked. A lock is a class in the threading module whose object generated in the unlocked state and has two primary methods i.e acquire() and release(). When the acquire() method is called, it locks the execution of the Lock and blocks it’s execution until the release() method is called in some other thread which sets it to unlock state. Locks help us in efficiently accessing a shared resource in a program in order to prevent corruption of data, it follows mutual exclusion as only one thread can access a particular resource at a time. Let us look at the below example to understand the use of Locks: " }, { "code": null, "e": 1243, "s": 1235, "text": "Python3" }, { "code": "# program to illustrate the use of Locks import threading # creating a Lock objectlock = threading.Lock() # initializing the shared resourcegeek = 0 def sumOne(): global geek # locking the shared resource lock.acquire() geek = geek + 1 # unlocking the shared resource lock.release() def sumTwo(): global geek # locking the shared resource lock.acquire() geek = geek + 2 # unlocking the shared resource lock.release() # calling the functionssumOne()sumTwo() # displaying the value of shared resourceprint(geek)", "e": 1844, "s": 1243, "text": null }, { "code": null, "e": 1852, "s": 1844, "text": "Output:" }, { "code": null, "e": 1854, "s": 1852, "text": "3" }, { "code": null, "e": 2382, "s": 1854, "text": "In the above program, lock is a Lock object, the global variable geek is a shared resource and sumOne() and sumTwo() functions act as threads, in sumOne() function the shared resource geek is first locked and then incremented by 1 and then geek is released and in sumTwo() function the variable geek is first locked and then incremented by 2 and then geek is released.The two functions sumOne() and sumTwo() can not access the shared resource geek simultaneously, only one of them can access the shared resource geek at a time." }, { "code": null, "e": 3040, "s": 2382, "text": "The default Lock doesn’t recognize which thread the lock currently holds. If the shared resource is being accessed by any thread then other threads trying to access the shared resource will get blocked even if it is the same thread that locked the shared resource. The Re-entrant lock or RLock is used in these situations to prevent undesired blocking from accessing the shared resource. If a shared resource is in RLock then it can be called again safely. The RLocked resource can be accessed repeatedly by various threads, though it still works correctly when called by different threads. Let us look at the below example to understand the use of RLocks: " }, { "code": null, "e": 3048, "s": 3040, "text": "Python3" }, { "code": "import threading # initializing the shared resourcegeek = 0 # creating a Lock objectlock = threading.Lock() # the below thread is accessing the# shared resourcelock.acquire()geek = geek + 1 # This thread will be blockedlock.acquire()geek = geek + 2lock.release() # displaying the value of shared resourceprint(geek)", "e": 3365, "s": 3048, "text": null }, { "code": null, "e": 3845, "s": 3365, "text": "In the above program, two threads are trying to access the shared resource geek simultaneously, here when a thread is currently accessing shared resource geek the other thread will be prevented from accessing it. When two or more threads try to access the same resource effectively prevent each other from accessing the resource this is known as deadlock due to which the above program generates no output. However, the above problem in the program can be solved by using RLock. " }, { "code": null, "e": 3853, "s": 3845, "text": "Python3" }, { "code": "# program to illustrate the use of RLocks # importing the moduleimport threading # initializing the shared resourcegeek = 0 # creating an RLock object instead# of Lock objectlock = threading.RLock() # the below thread is trying to access# the shared resourcelock.acquire()geek = geek + 1 # the below thread is trying to access# the shared resourcelock.acquire()geek = geek + 2lock.release()lock.release() # displaying the value of shared resourceprint(geek)", "e": 4311, "s": 3853, "text": null }, { "code": null, "e": 4319, "s": 4311, "text": "Output:" }, { "code": null, "e": 4321, "s": 4319, "text": "3" }, { "code": null, "e": 4640, "s": 4321, "text": "Here, there is no unwanted prevention of accessing the shared resource geek by the threads in the program. We need to call release() once for each acquire() of RLock object lock. From the numerous programs and explanations mentioned above there are many differences between a Lock object and an RLock object in Python:" }, { "code": null, "e": 4649, "s": 4640, "text": "sweetyty" }, { "code": null, "e": 4671, "s": 4649, "text": "Python-multithreading" }, { "code": null, "e": 4678, "s": 4671, "text": "Python" }, { "code": null, "e": 4776, "s": 4678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4794, "s": 4776, "text": "Python Dictionary" }, { "code": null, "e": 4836, "s": 4794, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4858, "s": 4836, "text": "Enumerate() in Python" }, { "code": null, "e": 4884, "s": 4858, "text": "Python String | replace()" }, { "code": null, "e": 4916, "s": 4884, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4945, "s": 4916, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4972, "s": 4945, "text": "Python Classes and Objects" }, { "code": null, "e": 5002, "s": 4972, "text": "Iterate over a list in Python" }, { "code": null, "e": 5025, "s": 5002, "text": "Introduction To PYTHON" } ]
bool Keyword in C#
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. bool is a keyword that is used to declare a variable which can store Boolean values true or false. It is an alias of System.Boolean. Bool Keyword occupies 1 byte (8 bits) in the memory. There are only two possible values of bool i.e. true or false. Syntax: bool variable_name = value; Example: Input: true Output: answer: False Size of a byte variable: 1 Input: false Output: Type of answer: System.Boolean answer: True Size of a bool variable: 1 Example 1: // C# program for bool keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // bool variable declaration bool answer = false; // to print value Console.WriteLine("answer: " + answer); // to print size of a bool Console.WriteLine("Size of a bool variable: " + sizeof(bool)); } } Output: answer: False Size of a bool variable: 1 Example 2: // C# program for bool keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // bool variable declaration bool answer = true; // to print type of variable Console.WriteLine("Type of answer: " + answer.GetType()); // to print value Console.WriteLine("answer: " + answer); // to print size of a bool Console.WriteLine("Size of a bool variable: " + sizeof(bool)); // hit ENTER to exit Console.ReadLine(); }}} Output: Type of answer: System.Boolean answer: True Size of a bool variable: 1 CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class C# | .NET Framework (Basic Architecture and Component Stack) HashSet in C# with Examples Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 276, "s": 28, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. bool is a keyword that is used to declare a variable which can store Boolean values true or false. It is an alias of System.Boolean." }, { "code": null, "e": 392, "s": 276, "text": "Bool Keyword occupies 1 byte (8 bits) in the memory. There are only two possible values of bool i.e. true or false." }, { "code": null, "e": 400, "s": 392, "text": "Syntax:" }, { "code": null, "e": 428, "s": 400, "text": "bool variable_name = value;" }, { "code": null, "e": 437, "s": 428, "text": "Example:" }, { "code": null, "e": 618, "s": 437, "text": "Input: true\n\nOutput: answer: False\n Size of a byte variable: 1\n\nInput: false\n\nOutput: Type of answer: System.Boolean\n answer: True\n Size of a bool variable: 1\n" }, { "code": null, "e": 629, "s": 618, "text": "Example 1:" }, { "code": "// C# program for bool keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // bool variable declaration bool answer = false; // to print value Console.WriteLine(\"answer: \" + answer); // to print size of a bool Console.WriteLine(\"Size of a bool variable: \" + sizeof(bool)); } }", "e": 1048, "s": 629, "text": null }, { "code": null, "e": 1056, "s": 1048, "text": "Output:" }, { "code": null, "e": 1098, "s": 1056, "text": "answer: False\nSize of a bool variable: 1\n" }, { "code": null, "e": 1109, "s": 1098, "text": "Example 2:" }, { "code": "// C# program for bool keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // bool variable declaration bool answer = true; // to print type of variable Console.WriteLine(\"Type of answer: \" + answer.GetType()); // to print value Console.WriteLine(\"answer: \" + answer); // to print size of a bool Console.WriteLine(\"Size of a bool variable: \" + sizeof(bool)); // hit ENTER to exit Console.ReadLine(); }}}", "e": 1655, "s": 1109, "text": null }, { "code": null, "e": 1663, "s": 1655, "text": "Output:" }, { "code": null, "e": 1735, "s": 1663, "text": "Type of answer: System.Boolean\nanswer: True\nSize of a bool variable: 1\n" }, { "code": null, "e": 1750, "s": 1735, "text": "CSharp-keyword" }, { "code": null, "e": 1753, "s": 1750, "text": "C#" }, { "code": null, "e": 1851, "s": 1753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1894, "s": 1851, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 1943, "s": 1894, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 1966, "s": 1943, "text": "Extension Method in C#" }, { "code": null, "e": 1982, "s": 1966, "text": "C# | List Class" }, { "code": null, "e": 2043, "s": 1982, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2071, "s": 2043, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2094, "s": 2071, "text": "Switch Statement in C#" }, { "code": null, "e": 2119, "s": 2094, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2141, "s": 2119, "text": "Partial Classes in C#" } ]
The build() method in Java Stream.Builder
The build() method in Stream.Builder class is used to build the stream. It returns the built stream. The syntax is as follows: Stream<T>l build() Import the following package for the Stream.Builder class in Java: import java.util.stream.Stream; Declare a Stream.Builder: Stream.Builder<String> builder = Stream.builder(); Add some elements in the stream: builder.add("One"); builder.add("Two"); builder.add("Three"); Now, use the build() method: Stream<String> str = builder.build(); The following is an example displaying how to implement build() method of Stream.Builder in Java: Live Demo import java.util.stream.Stream; public class Demo { public static void main(String[] args) { Stream.Builder<String> builder = Stream.builder(); builder.add("One"); builder.add("Two"); builder.add("Three"); builder.add("Four"); builder.add("Five"); builder.add("Six"); builder.add("Seven"); builder.add("Eight"); Stream<String> str = builder.build(); str.forEach(System.out::println); } } One Two Three Four Five Six Seven Eigh
[ { "code": null, "e": 1288, "s": 1187, "text": "The build() method in Stream.Builder class is used to build the stream. It returns the built stream." }, { "code": null, "e": 1314, "s": 1288, "text": "The syntax is as follows:" }, { "code": null, "e": 1333, "s": 1314, "text": "Stream<T>l build()" }, { "code": null, "e": 1400, "s": 1333, "text": "Import the following package for the Stream.Builder class in Java:" }, { "code": null, "e": 1432, "s": 1400, "text": "import java.util.stream.Stream;" }, { "code": null, "e": 1458, "s": 1432, "text": "Declare a Stream.Builder:" }, { "code": null, "e": 1509, "s": 1458, "text": "Stream.Builder<String> builder = Stream.builder();" }, { "code": null, "e": 1542, "s": 1509, "text": "Add some elements in the stream:" }, { "code": null, "e": 1604, "s": 1542, "text": "builder.add(\"One\");\nbuilder.add(\"Two\");\nbuilder.add(\"Three\");" }, { "code": null, "e": 1633, "s": 1604, "text": "Now, use the build() method:" }, { "code": null, "e": 1671, "s": 1633, "text": "Stream<String> str = builder.build();" }, { "code": null, "e": 1769, "s": 1671, "text": "The following is an example displaying how to implement build() method of Stream.Builder in Java:" }, { "code": null, "e": 1780, "s": 1769, "text": " Live Demo" }, { "code": null, "e": 2240, "s": 1780, "text": "import java.util.stream.Stream;\npublic class Demo {\n public static void main(String[] args) {\n Stream.Builder<String> builder = Stream.builder();\n builder.add(\"One\");\n builder.add(\"Two\");\n builder.add(\"Three\");\n builder.add(\"Four\");\n builder.add(\"Five\");\n builder.add(\"Six\");\n builder.add(\"Seven\");\n builder.add(\"Eight\");\n Stream<String> str = builder.build();\n str.forEach(System.out::println);\n }\n}" }, { "code": null, "e": 2279, "s": 2240, "text": "One\nTwo\nThree\nFour\nFive\nSix\nSeven\nEigh" } ]
PyQt5 – How to add action to a button ?
22 Apr, 2020 In this article we will see how to set action to a push button. QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used. When the button is pressed it should perform some action, in order to add action to a button we will use clicked.connect method. Syntax : button.clicked.connect(function) Argument : It takes function as a argument. Action performed: When button will be clicked it will call the passes function. Code : # importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton("CLICK", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print("pressed") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output :When we tap on the button. pressed Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Create a Pandas DataFrame from Lists Python | os.path.join() method
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2020" }, { "code": null, "e": 290, "s": 52, "text": "In this article we will see how to set action to a push button. QPushButton is a simple button in PyQt, when clicked by a user some associated action gets performed. For adding this button into the application, QPushButton class is used." }, { "code": null, "e": 419, "s": 290, "text": "When the button is pressed it should perform some action, in order to add action to a button we will use clicked.connect method." }, { "code": null, "e": 461, "s": 419, "text": "Syntax : button.clicked.connect(function)" }, { "code": null, "e": 505, "s": 461, "text": "Argument : It takes function as a argument." }, { "code": null, "e": 585, "s": 505, "text": "Action performed: When button will be clicked it will call the passes function." }, { "code": null, "e": 592, "s": 585, "text": "Code :" }, { "code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating a push button button = QPushButton(\"CLICK\", self) # setting geometry of button button.setGeometry(200, 150, 100, 30) # adding action to a button button.clicked.connect(self.clickme) # action method def clickme(self): # printing pressed print(\"pressed\") # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1556, "s": 592, "text": null }, { "code": null, "e": 1591, "s": 1556, "text": "Output :When we tap on the button." }, { "code": null, "e": 1599, "s": 1591, "text": "pressed" }, { "code": null, "e": 1610, "s": 1599, "text": "Python-gui" }, { "code": null, "e": 1622, "s": 1610, "text": "Python-PyQt" }, { "code": null, "e": 1629, "s": 1622, "text": "Python" }, { "code": null, "e": 1727, "s": 1629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1769, "s": 1727, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1801, "s": 1769, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1830, "s": 1801, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1857, "s": 1830, "text": "Python Classes and Objects" }, { "code": null, "e": 1878, "s": 1857, "text": "Python OOPs Concepts" }, { "code": null, "e": 1914, "s": 1878, "text": "Convert integer to string in Python" }, { "code": null, "e": 1937, "s": 1914, "text": "Introduction To PYTHON" }, { "code": null, "e": 1993, "s": 1937, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2030, "s": 1993, "text": "Create a Pandas DataFrame from Lists" } ]
Elias Gamma Decoding in Python
28 Nov, 2021 The Elias gamma code is a universal code that is used to encode a sequence of positive integers. It is developed by Peter Elias. It is most useful when the upper-bound of integers cannot be determined beforehand. Formula: Elias Gamma Coding=Unary(1+floor(log2(x)))+Binary representation of ‘x’ without MSB Example: Let’s consider an example where we want to decode 0001001, Apply Step 1: Count the number of '0's from MSB until you reach the first '1' and store the count in K. In our example(0001001) K=3 Apply Step 2: Read 3 more bits including the first '1'=1001 Apply Step 3: Convert the final binary into integer which gives us the original number. Decimal(1001)=9 Step 1: Count the number of ‘0’s from MSB until you reach the first ‘1’ and store the count in K. Python3 # define the functiondef Elias_Gamma_Decoding(x): # convert to list x = list(x) # initialize k to 0 K = 0 while True: # check if k is not 0 in through # list index if not x[K] == '0': break # increment k value K = K + 1 Step 2: Consider that ‘1’ as the first digit and read ‘K’ more bits from the current ‘1’ Python3 x = x[K:2*K+1] # Reading K more bits from '1' Step 3: Convert the final binary into an integer which gives us the original number. Python3 # Converting binary to integerfor i in range(len(x)): if x[i] == '1': n = n+math.pow(2, i)return int(n) Below is the complete implementation of the above approach. Python3 # import the math moduleimport math # functiondef Elias_Gamma_Decoding(x): x = list(x) K = 0 while True: if not x[K] == '0': break K = K + 1 # Reading K more bits from '1' x = x[K:2*K+1] n = 0 x.reverse() # Converting binary to integer for i in range(len(x)): if x[i] == '1': n = n+math.pow(2, i) return int(n) # value inputx = '0001001' # call the functionprint(Elias_Gamma_Decoding(x)) Output: 9 Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Nov, 2021" }, { "code": null, "e": 267, "s": 54, "text": "The Elias gamma code is a universal code that is used to encode a sequence of positive integers. It is developed by Peter Elias. It is most useful when the upper-bound of integers cannot be determined beforehand." }, { "code": null, "e": 276, "s": 267, "text": "Formula:" }, { "code": null, "e": 360, "s": 276, "text": "Elias Gamma Coding=Unary(1+floor(log2(x)))+Binary representation of ‘x’ without MSB" }, { "code": null, "e": 428, "s": 360, "text": "Example: Let’s consider an example where we want to decode 0001001," }, { "code": null, "e": 727, "s": 428, "text": "Apply Step 1:\nCount the number of '0's from MSB until you reach the first '1' and store the count in K.\nIn our example(0001001) K=3 \n\nApply Step 2:\nRead 3 more bits including the first '1'=1001\n\nApply Step 3:\nConvert the final binary into integer which gives us the original number.\nDecimal(1001)=9" }, { "code": null, "e": 825, "s": 727, "text": "Step 1: Count the number of ‘0’s from MSB until you reach the first ‘1’ and store the count in K." }, { "code": null, "e": 833, "s": 825, "text": "Python3" }, { "code": "# define the functiondef Elias_Gamma_Decoding(x): # convert to list x = list(x) # initialize k to 0 K = 0 while True: # check if k is not 0 in through # list index if not x[K] == '0': break # increment k value K = K + 1", "e": 1142, "s": 833, "text": null }, { "code": null, "e": 1231, "s": 1142, "text": "Step 2: Consider that ‘1’ as the first digit and read ‘K’ more bits from the current ‘1’" }, { "code": null, "e": 1239, "s": 1231, "text": "Python3" }, { "code": "x = x[K:2*K+1] # Reading K more bits from '1'", "e": 1286, "s": 1239, "text": null }, { "code": null, "e": 1371, "s": 1286, "text": "Step 3: Convert the final binary into an integer which gives us the original number." }, { "code": null, "e": 1379, "s": 1371, "text": "Python3" }, { "code": "# Converting binary to integerfor i in range(len(x)): if x[i] == '1': n = n+math.pow(2, i)return int(n)", "e": 1493, "s": 1379, "text": null }, { "code": null, "e": 1553, "s": 1493, "text": "Below is the complete implementation of the above approach." }, { "code": null, "e": 1561, "s": 1553, "text": "Python3" }, { "code": "# import the math moduleimport math # functiondef Elias_Gamma_Decoding(x): x = list(x) K = 0 while True: if not x[K] == '0': break K = K + 1 # Reading K more bits from '1' x = x[K:2*K+1] n = 0 x.reverse() # Converting binary to integer for i in range(len(x)): if x[i] == '1': n = n+math.pow(2, i) return int(n) # value inputx = '0001001' # call the functionprint(Elias_Gamma_Decoding(x))", "e": 2041, "s": 1561, "text": null }, { "code": null, "e": 2049, "s": 2041, "text": "Output:" }, { "code": null, "e": 2051, "s": 2049, "text": "9" }, { "code": null, "e": 2058, "s": 2051, "text": "Picked" }, { "code": null, "e": 2073, "s": 2058, "text": "python-utility" }, { "code": null, "e": 2080, "s": 2073, "text": "Python" }, { "code": null, "e": 2178, "s": 2080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2210, "s": 2178, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2237, "s": 2210, "text": "Python Classes and Objects" }, { "code": null, "e": 2258, "s": 2237, "text": "Python OOPs Concepts" }, { "code": null, "e": 2281, "s": 2258, "text": "Introduction To PYTHON" }, { "code": null, "e": 2337, "s": 2281, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2368, "s": 2337, "text": "Python | os.path.join() method" }, { "code": null, "e": 2410, "s": 2368, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2452, "s": 2410, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2491, "s": 2452, "text": "Python | Get unique values from a list" } ]
Java Program to Open Input URL in System Default Browser in Windows
19 Jan, 2021 URL is the URL you want to display in the default Web browser. For example, wire http://www.site.com/report.html to this input to display the HTML file report.html on the Web Server www.site.com in the browser. Our problem is to write a java program to open Input URL in System Default Browser in Windows. To open any URL we use different predefine files of java to operate with our Desktop. java.awt.Desktop: We use java.awt.Desktop class because java.awt.Desktop allow us to interact with different capability of our Desktop. For Example Launching User default Browser, Launching user default mail Client etc.java.net.URI: java.net.URI is used to Represent User Resource Identifier reference. java.awt.Desktop: We use java.awt.Desktop class because java.awt.Desktop allow us to interact with different capability of our Desktop. For Example Launching User default Browser, Launching user default mail Client etc. java.net.URI: java.net.URI is used to Represent User Resource Identifier reference. Algorithm: Firstly, we create an Object of our-defined class that we import by java.awt.Desktop. During the creation of an object, we use getDesktop() method that returns the Desktop instance of the current desktop context. On some platforms the Desktop API may not be supported, in that case we use isDesktopSupported() method to determine if the current desktop is supported. Desktop desk=Desktop.getDesktop(); Then we use browse() method where we enter our URL that we want to open on our desktop by new URI(). desk.browse(new URI("http://xyz.com")); Java // Java Program to Open Input URL in // System Default Browser in Windows import java.awt.Desktop;import java.io.*;import java.net.URI; class GFG { public static void main(String[] args) throws Exception { Desktop desk = Desktop.getDesktop(); // now we enter our URL that we want to open in our // default browser desk.browse(new URI("http://xyz.com")); }} Output (Our URL "http://xyz.com" will open in our desktop default browser) 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.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jan, 2021" }, { "code": null, "e": 239, "s": 28, "text": "URL is the URL you want to display in the default Web browser. For example, wire http://www.site.com/report.html to this input to display the HTML file report.html on the Web Server www.site.com in the browser." }, { "code": null, "e": 334, "s": 239, "text": "Our problem is to write a java program to open Input URL in System Default Browser in Windows." }, { "code": null, "e": 420, "s": 334, "text": "To open any URL we use different predefine files of java to operate with our Desktop." }, { "code": null, "e": 723, "s": 420, "text": "java.awt.Desktop: We use java.awt.Desktop class because java.awt.Desktop allow us to interact with different capability of our Desktop. For Example Launching User default Browser, Launching user default mail Client etc.java.net.URI: java.net.URI is used to Represent User Resource Identifier reference." }, { "code": null, "e": 943, "s": 723, "text": "java.awt.Desktop: We use java.awt.Desktop class because java.awt.Desktop allow us to interact with different capability of our Desktop. For Example Launching User default Browser, Launching user default mail Client etc." }, { "code": null, "e": 1027, "s": 943, "text": "java.net.URI: java.net.URI is used to Represent User Resource Identifier reference." }, { "code": null, "e": 1038, "s": 1027, "text": "Algorithm:" }, { "code": null, "e": 1124, "s": 1038, "text": "Firstly, we create an Object of our-defined class that we import by java.awt.Desktop." }, { "code": null, "e": 1405, "s": 1124, "text": "During the creation of an object, we use getDesktop() method that returns the Desktop instance of the current desktop context. On some platforms the Desktop API may not be supported, in that case we use isDesktopSupported() method to determine if the current desktop is supported." }, { "code": null, "e": 1442, "s": 1405, "text": " Desktop desk=Desktop.getDesktop();" }, { "code": null, "e": 1543, "s": 1442, "text": "Then we use browse() method where we enter our URL that we want to open on our desktop by new URI()." }, { "code": null, "e": 1585, "s": 1543, "text": " desk.browse(new URI(\"http://xyz.com\"));" }, { "code": null, "e": 1590, "s": 1585, "text": "Java" }, { "code": "// Java Program to Open Input URL in // System Default Browser in Windows import java.awt.Desktop;import java.io.*;import java.net.URI; class GFG { public static void main(String[] args) throws Exception { Desktop desk = Desktop.getDesktop(); // now we enter our URL that we want to open in our // default browser desk.browse(new URI(\"http://xyz.com\")); }}", "e": 2006, "s": 1590, "text": null }, { "code": null, "e": 2013, "s": 2006, "text": "Output" }, { "code": null, "e": 2081, "s": 2013, "text": "(Our URL \"http://xyz.com\" will open in our desktop default browser)" }, { "code": null, "e": 2088, "s": 2081, "text": "Picked" }, { "code": null, "e": 2112, "s": 2088, "text": "Technical Scripter 2020" }, { "code": null, "e": 2117, "s": 2112, "text": "Java" }, { "code": null, "e": 2131, "s": 2117, "text": "Java Programs" }, { "code": null, "e": 2150, "s": 2131, "text": "Technical Scripter" }, { "code": null, "e": 2155, "s": 2150, "text": "Java" } ]
ES6 - Promises
The Syntax related to promise is mentioned below where, p is the promise object, resolve is the function that should be called when the promise executes successfully and reject is the function that should be called when the promise encounters an error. let p = new Promise(function(resolve,reject){ let workDone = true; // some time consuming work if(workDone){ //invoke resolve function passed resolve('success promise completed') } else{ reject('ERROR , work could not be completed') } }) The example given below shows a function add_positivenos_async() which adds two numbers asynchronously. The promise is resolved if positive values are passed. The promise is rejected if negative values are passed. <script> function add_positivenos_async(n1, n2) { let p = new Promise(function (resolve, reject) { if (n1 >= 0 && n2 >= 0) { //do some complex time consuming work resolve(n1 + n2) } else reject('NOT_Postive_Number_Passed') }) return p; } add_positivenos_async(10, 20) .then(successHandler) // if promise resolved .catch(errorHandler);// if promise rejected add_positivenos_async(-10, -20) .then(successHandler) // if promise resolved .catch(errorHandler);// if promise rejected function errorHandler(err) { console.log('Handling error', err) } function successHandler(result) { console.log('Handling success', result) } console.log('end') </script> The output of the above code will be as mentioned below − end Handling success 30 Handling error NOT_Postive_Number_Passed Promises chaining can be used when we have a sequence of asynchronous tasks to be done one after another. Promises are chained when a promise depends on the result of another promise. This is shown in the example below In the below example, add_positivenos_async() function adds two numbers asynchronously and rejects if negative values are passed. The result from the current asynchronous function call is passed as parameter to the subsequent function calls. Note each then() method has a return statement. <script> function add_positivenos_async(n1, n2) { let p = new Promise(function (resolve, reject) { if (n1 >= 0 && n2 >= 0) { //do some complex time consuming work resolve(n1 + n2) } else reject('NOT_Postive_Number_Passed') }) return p; } add_positivenos_async(10,20) .then(function(result){ console.log("first result",result) return add_positivenos_async(result,result) }).then(function(result){ console.log("second result",result) return add_positivenos_async(result,result) }).then(function(result){ console.log("third result",result) }) console.log('end') </script> The output of the above code will be as stated below − end first result 30 second result 60 third result 120 Some common used methods of the promise object are discussed below in detail − This method can be useful for aggregating the results of multiple promises. The syntax for the promise.all() method is mentioned below, where, iterable is an iterable object. E.g. Array. Promise.all(iterable); The example given below executes an array of asynchronous operations [add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)]. When all the operations are completed, the promise is fully resolved. <script> function add_positivenos_async(n1, n2) { let p = new Promise(function (resolve, reject) { if (n1 >= 0 && n2 >= 0) { //do some complex time consuming work resolve(n1 + n2) } else reject('NOT_Postive_Number_Passed') }) return p; } //Promise.all(iterable) Promise.all([add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)]) .then(function(resolveValue){ console.log(resolveValue[0]) console.log(resolveValue[1]) console.log(resolveValue[2]) console.log('all add operations done') }) .catch(function(err){ console.log('Error',err) }) console.log('end') </script> The output of the above code will be as follows − end 30 70 110 all add operations done This function takes an array of promises and returns the first promise that is settled. The syntax for the promise.race() function is mentioned below, where, iterable is an iterable object. E.g. Array. Promise.race(iterable) The example given below takes an array [add_positivenos_async(10,20),add_positivenos_async(30,40)] of asynchronous operations. The promise is resolved whenever any one of the add operation completes. The promise will not wait for other asynchronous operations to complete. <script> function add_positivenos_async(n1, n2) { let p = new Promise(function (resolve, reject) { if (n1 >= 0 && n2 >= 0) { //do some complex time consuming work resolve(n1 + n2) } else reject('NOT_Postive_Number_Passed') }) return p; } //Promise.race(iterable) Promise.race([add_positivenos_async(10,20),add_positivenos_async(30,40)]) .then(function(resolveValue){ console.log('one of them is done') console.log(resolveValue) }).catch(function(err){ console.log("Error",err) }) console.log('end') </script> The output of the above code will be as follows − end one of them is done 30 Promises are a clean way to implement async programming in JavaScript (ES6 new feature). Prior to promises, Callbacks were used to implement async programming. Let’s begin by understanding what async programming is and its implementation, using Callbacks. A function may be passed as a parameter to another function. This mechanism is termed as a Callback. A Callback would be helpful in events. The following example will help us better understand this concept. <script> function notifyAll(fnSms, fnEmail) { console.log('starting notification process'); fnSms(); fnEmail(); } notifyAll(function() { console.log("Sms send .."); }, function() { console.log("email send .."); }); console.log("End of script"); //executes last or blocked by other methods </script> In the notifyAll() method shown above, the notification happens by sending SMS and by sending an e-mail. Hence, the invoker of the notifyAll method has to pass two functions as parameters. Each function takes up a single responsibility like sending SMS and sending an e-mail. The following output is displayed on successful execution of the above code. starting notification process Sms send .. Email send .. End of script In the code mentioned above, the function calls are synchronous. It means the UI thread would be waiting to complete the entire notification process. Synchronous calls become blocking calls. Let's understand non-blocking or async calls now. Consider the above example. To enable the script, execute an asynchronous or a non-blocking call to notifyAll() method. We shall use the setTimeout() method of JavaScript. This method is async by default. The setTimeout() method takes two parameters − A callback function. A callback function. The number of seconds after which the method will be called. The number of seconds after which the method will be called. In this case, the notification process has been wrapped with timeout. Hence, it will take a two seconds delay, set by the code. The notifyAll() will be invoked and the main thread goes ahead like executing other methods. Hence, the notification process will not block the main JavaScript thread. <script> function notifyAll(fnSms, fnEmail) { setTimeout(function() { console.log('starting notification process'); fnSms(); fnEmail(); }, 2000); } notifyAll(function() { console.log("Sms send .."); }, function() { console.log("email send .."); }); console.log("End of script"); //executes first or not blocked by others </script> The following output is displayed on successful execution of the above code. End of script starting notification process Sms send .. Email send .. In case of multiple callbacks, the code will look scary. <script> setTimeout(function() { console.log("one"); setTimeout(function() { console.log("two"); setTimeout(function() { console.log("three"); }, 1000); }, 1000); }, 1000); </script> ES6 comes to your rescue by introducing the concept of promises. Promises are "Continuation events" and they help you execute the multiple async operations together in a much cleaner code style. Let's understand this with an example. Following is the syntax for the same. var promise = new Promise(function(resolve , reject) { // do a thing, possibly async , then.. if(/*everthing turned out fine */) resolve("stuff worked"); else reject(Error("It broke")); }); return promise; // Give this to someone The first step towards implementing the promises is to create a method which will use the promise. Let’s say in this example, the getSum() method is asynchronous i.e., its operation should not block other methods’ execution. As soon as this operation completes, it will later notify the caller. The following example (Step 1) declares a Promise object ‘var promise’. The Promise Constructor takes to the functions first for the successful completion of the work and another in case an error happens. The promise returns the result of the calculation by using the resolve callback and passing in the result, i.e., n1+n2 Step 1 − resolve(n1 + n2); If the getSum() encounters an error or an unexpected condition, it will invoke the reject callback method in the Promise and pass the error information to the caller. Step 2 − reject(Error("Negatives not supported")); The method implementation is given in the following code (STEP 1). function getSum(n1, n2) { varisAnyNegative = function() { return n1 < 0 || n2 < 0; } var promise = new Promise(function(resolve, reject) { if (isAnyNegative()) { reject(Error("Negatives not supported")); } resolve(n1 + n2) }); return promise; } The second step details the implementation of the caller (STEP 2). The caller should use the ‘then’ method, which takes two callback methods - first for success and second for failure. Each method takes one parameter, as shown in the following code. getSum(5, 6) .then(function (result) { console.log(result); }, function (error) { console.log(error); }); The following output is displayed on successful execution of the above code. 11 Since the return type of the getSum() is a Promise, we can actually have multiple ‘then’ statements. The first 'then' will have a return statement. getSum(5, 6) .then(function(result) { console.log(result); returngetSum(10, 20); // this returns another promise }, function(error) { console.log(error); }) .then(function(result) { console.log(result); }, function(error) { console.log(error); }); The following output is displayed on successful execution of the above code. 11 30 The following example issues three then() calls with getSum() method. <script> function getSum(n1, n2) { varisAnyNegative = function() { return n1 < 0 || n2 < 0; } var promise = new Promise(function(resolve, reject) { if (isAnyNegative()) { reject(Error("Negatives not supported")); } resolve(n1 + n2); }); return promise; } getSum(5, 6) .then(function(result) { console.log(result); returngetSum(10, 20); //this returns another Promise }, function(error) { console.log(error); }) .then(function(result) { console.log(result); returngetSum(30, 40); //this returns another Promise }, function(error) { console.log(error); }) .then(function(result) { console.log(result); }, function(error) { console.log(error); }); console.log("End of script "); </script> The following output is displayed on successful execution of the above code. The program displays ‘end of script’ first and then results from calling getSum() method, one by one. End of script 11 30 70 This shows getSum() is called in async style or non-blocking style. Promise gives a nice and clean way to deal with the Callbacks.
[ { "code": null, "e": 2664, "s": 2411, "text": "The Syntax related to promise is mentioned below where, p is the promise object, resolve is the function that should be called when the promise executes successfully and reject is the function that should be called when the promise encounters an error." }, { "code": null, "e": 2943, "s": 2664, "text": "let p = new Promise(function(resolve,reject){\n let workDone = true; // some time consuming work\n if(workDone){\n //invoke resolve function passed\n \n\t resolve('success promise completed')\n }\n else{\n reject('ERROR , work could not be completed')\n }\n})\n" }, { "code": null, "e": 3157, "s": 2943, "text": "The example given below shows a function add_positivenos_async() which adds two numbers asynchronously. The promise is resolved if positive values are passed. The promise is rejected if negative values are passed." }, { "code": null, "e": 3965, "s": 3157, "text": "<script> \n function add_positivenos_async(n1, n2) {\n let p = new Promise(function (resolve, reject) {\n if (n1 >= 0 && n2 >= 0) {\n //do some complex time consuming work\n resolve(n1 + n2)\n }\n else\n reject('NOT_Postive_Number_Passed') \n })\n return p;\n }\n\n add_positivenos_async(10, 20)\n .then(successHandler) // if promise resolved\n .catch(errorHandler);// if promise rejected\n\n add_positivenos_async(-10, -20)\n .then(successHandler) // if promise resolved\n .catch(errorHandler);// if promise rejected\n\n function errorHandler(err) {\n console.log('Handling error', err)\n }\n function successHandler(result) {\n console.log('Handling success', result)\n }\n\n console.log('end')\n</script> " }, { "code": null, "e": 4023, "s": 3965, "text": "The output of the above code will be as mentioned below −" }, { "code": null, "e": 4089, "s": 4023, "text": "end\nHandling success 30\nHandling error NOT_Postive_Number_Passed\n" }, { "code": null, "e": 4308, "s": 4089, "text": "Promises chaining can be used when we have a sequence of asynchronous tasks to be done one after another. Promises are chained when a promise depends on the result of another promise. This is shown in the example below" }, { "code": null, "e": 4598, "s": 4308, "text": "In the below example, add_positivenos_async() function adds two numbers asynchronously and rejects if negative values are passed. The result from the current asynchronous function call is passed as parameter to the subsequent function calls. Note each then() method has a return statement." }, { "code": null, "e": 5305, "s": 4598, "text": "<script> \n function add_positivenos_async(n1, n2) {\n let p = new Promise(function (resolve, reject) {\n if (n1 >= 0 && n2 >= 0) {\n //do some complex time consuming work\n resolve(n1 + n2)\n }\n else\n reject('NOT_Postive_Number_Passed')\n })\n return p;\n }\n\n add_positivenos_async(10,20)\n .then(function(result){\n console.log(\"first result\",result)\n return add_positivenos_async(result,result)\n }).then(function(result){\n console.log(\"second result\",result)\n return add_positivenos_async(result,result)\n }).then(function(result){\n console.log(\"third result\",result)\n })\n\n console.log('end')\n</script> " }, { "code": null, "e": 5360, "s": 5305, "text": "The output of the above code will be as stated below −" }, { "code": null, "e": 5415, "s": 5360, "text": "end\nfirst result 30\nsecond result 60\nthird result 120\n" }, { "code": null, "e": 5494, "s": 5415, "text": "Some common used methods of the promise object are discussed below in detail −" }, { "code": null, "e": 5570, "s": 5494, "text": "This method can be useful for aggregating the results of multiple promises." }, { "code": null, "e": 5681, "s": 5570, "text": "The syntax for the promise.all() method is mentioned below, where, iterable is an iterable object. E.g. Array." }, { "code": null, "e": 5705, "s": 5681, "text": "Promise.all(iterable);\n" }, { "code": null, "e": 5934, "s": 5705, "text": "The example given below executes an array of asynchronous operations [add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)]. When all the operations are completed, the promise is fully resolved." }, { "code": null, "e": 6677, "s": 5934, "text": "<script> \n function add_positivenos_async(n1, n2) {\n let p = new Promise(function (resolve, reject) {\n if (n1 >= 0 && n2 >= 0) {\n //do some complex time consuming work\n resolve(n1 + n2)\n }\n else\n reject('NOT_Postive_Number_Passed')\n })\n\n return p;\n }\n //Promise.all(iterable)\n\nPromise.all([add_positivenos_async(10,20),add_positivenos_async(30,40),add_positivenos_async(50,60)])\n .then(function(resolveValue){\n console.log(resolveValue[0])\n console.log(resolveValue[1])\n console.log(resolveValue[2])\n console.log('all add operations done')\n })\n .catch(function(err){\n console.log('Error',err)\n })\n console.log('end')\n</script> " }, { "code": null, "e": 6727, "s": 6677, "text": "The output of the above code will be as follows −" }, { "code": null, "e": 6766, "s": 6727, "text": "end\n30\n70\n110\nall add operations done\n" }, { "code": null, "e": 6854, "s": 6766, "text": "This function takes an array of promises and returns the first promise that is settled." }, { "code": null, "e": 6968, "s": 6854, "text": "The syntax for the promise.race() function is mentioned below, where, iterable is an iterable object. E.g. Array." }, { "code": null, "e": 6992, "s": 6968, "text": "Promise.race(iterable)\n" }, { "code": null, "e": 7119, "s": 6992, "text": "The example given below takes an array [add_positivenos_async(10,20),add_positivenos_async(30,40)] of asynchronous operations." }, { "code": null, "e": 7265, "s": 7119, "text": "The promise is resolved whenever any one of the add operation completes. The promise will not wait for other asynchronous operations to complete." }, { "code": null, "e": 7895, "s": 7265, "text": "<script> \n function add_positivenos_async(n1, n2) {\n let p = new Promise(function (resolve, reject) {\n if (n1 >= 0 && n2 >= 0) {\n //do some complex time consuming work\n resolve(n1 + n2)\n } else\n reject('NOT_Postive_Number_Passed')\n })\n\n return p;\n }\n\n //Promise.race(iterable)\n Promise.race([add_positivenos_async(10,20),add_positivenos_async(30,40)])\n .then(function(resolveValue){\n console.log('one of them is done')\n console.log(resolveValue)\n }).catch(function(err){\n console.log(\"Error\",err)\n })\n\n console.log('end')\n</script> " }, { "code": null, "e": 7945, "s": 7895, "text": "The output of the above code will be as follows −" }, { "code": null, "e": 7973, "s": 7945, "text": "end\none of them is done\n30\n" }, { "code": null, "e": 8229, "s": 7973, "text": "Promises are a clean way to implement async programming in JavaScript (ES6 new feature). Prior to promises, Callbacks were used to implement async programming. Let’s begin by understanding what async programming is and its implementation, using Callbacks." }, { "code": null, "e": 8369, "s": 8229, "text": "A function may be passed as a parameter to another function. This mechanism is termed as a Callback. A Callback would be helpful in events." }, { "code": null, "e": 8436, "s": 8369, "text": "The following example will help us better understand this concept." }, { "code": null, "e": 8828, "s": 8436, "text": "<script> \n function notifyAll(fnSms, fnEmail) { \n console.log('starting notification process'); \n fnSms(); \n fnEmail(); \n } \n notifyAll(function() { \n console.log(\"Sms send ..\"); \n }, \n function() { \n console.log(\"email send ..\"); \n }); \n console.log(\"End of script\"); \n //executes last or blocked by other methods \n</script> " }, { "code": null, "e": 9104, "s": 8828, "text": "In the notifyAll() method shown above, the notification happens by sending SMS and by sending an e-mail. Hence, the invoker of the notifyAll method has to pass two functions as parameters. Each function takes up a single responsibility like sending SMS and sending an e-mail." }, { "code": null, "e": 9181, "s": 9104, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 9256, "s": 9181, "text": "starting notification process \nSms send .. \nEmail send .. \nEnd of script \n" }, { "code": null, "e": 9497, "s": 9256, "text": "In the code mentioned above, the function calls are synchronous. It means the UI thread would be waiting to complete the entire notification process. Synchronous calls become blocking calls. Let's understand non-blocking or async calls now." }, { "code": null, "e": 9525, "s": 9497, "text": "Consider the above example." }, { "code": null, "e": 9702, "s": 9525, "text": "To enable the script, execute an asynchronous or a non-blocking call to notifyAll() method. We shall use the setTimeout() method of JavaScript. This method is async by default." }, { "code": null, "e": 9749, "s": 9702, "text": "The setTimeout() method takes two parameters −" }, { "code": null, "e": 9770, "s": 9749, "text": "A callback function." }, { "code": null, "e": 9791, "s": 9770, "text": "A callback function." }, { "code": null, "e": 9852, "s": 9791, "text": "The number of seconds after which the method will be called." }, { "code": null, "e": 9913, "s": 9852, "text": "The number of seconds after which the method will be called." }, { "code": null, "e": 10209, "s": 9913, "text": "In this case, the notification process has been wrapped with timeout. Hence, it will take a two seconds delay, set by the code. The notifyAll() will be invoked and the main thread goes ahead like executing other methods. Hence, the notification process will not block the main JavaScript thread." }, { "code": null, "e": 10656, "s": 10209, "text": "<script> \n function notifyAll(fnSms, fnEmail) { \n setTimeout(function() { \n console.log('starting notification process'); \n fnSms(); \n fnEmail(); \n }, 2000); \n } \n notifyAll(function() { \n console.log(\"Sms send ..\"); \n }, \n function() { \n console.log(\"email send ..\"); \n }); \n console.log(\"End of script\"); //executes first or not blocked by others \n</script>" }, { "code": null, "e": 10733, "s": 10656, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 10808, "s": 10733, "text": "End of script \nstarting notification process \nSms send .. \nEmail send .. \n" }, { "code": null, "e": 10865, "s": 10808, "text": "In case of multiple callbacks, the code will look scary." }, { "code": null, "e": 11141, "s": 10865, "text": "<script> \n setTimeout(function() { \n console.log(\"one\"); \n setTimeout(function() { \n console.log(\"two\"); \n setTimeout(function() { \n console.log(\"three\"); \n }, 1000); \n }, 1000); \n }, 1000); \n</script>" }, { "code": null, "e": 11336, "s": 11141, "text": "ES6 comes to your rescue by introducing the concept of promises. Promises are \"Continuation events\" and they help you execute the multiple async operations together in a much cleaner code style." }, { "code": null, "e": 11413, "s": 11336, "text": "Let's understand this with an example. Following is the syntax for the same." }, { "code": null, "e": 11676, "s": 11413, "text": "var promise = new Promise(function(resolve , reject) { \n // do a thing, possibly async , then.. \n if(/*everthing turned out fine */) resolve(\"stuff worked\"); \n else \n reject(Error(\"It broke\")); \n}); \nreturn promise;\n// Give this to someone\n" }, { "code": null, "e": 11971, "s": 11676, "text": "The first step towards implementing the promises is to create a method which will use the promise. Let’s say in this example, the getSum() method is asynchronous i.e., its operation should not block other methods’ execution. As soon as this operation completes, it will later notify the caller." }, { "code": null, "e": 12176, "s": 11971, "text": "The following example (Step 1) declares a Promise object ‘var promise’. The Promise Constructor takes to the functions first for the successful completion of the work and another in case an error happens." }, { "code": null, "e": 12295, "s": 12176, "text": "The promise returns the result of the calculation by using the resolve callback and passing in the result, i.e., n1+n2" }, { "code": null, "e": 12322, "s": 12295, "text": "Step 1 − resolve(n1 + n2);" }, { "code": null, "e": 12489, "s": 12322, "text": "If the getSum() encounters an error or an unexpected condition, it will invoke the reject callback method in the Promise and pass the error information to the caller." }, { "code": null, "e": 12540, "s": 12489, "text": "Step 2 − reject(Error(\"Negatives not supported\"));" }, { "code": null, "e": 12607, "s": 12540, "text": "The method implementation is given in the following code (STEP 1)." }, { "code": null, "e": 12931, "s": 12607, "text": "function getSum(n1, n2) { \n varisAnyNegative = function() { \n return n1 < 0 || n2 < 0; \n } \n var promise = new Promise(function(resolve, reject) { \n if (isAnyNegative()) { \n reject(Error(\"Negatives not supported\")); \n } \n resolve(n1 + n2)\n }); \n return promise; \n} " }, { "code": null, "e": 12998, "s": 12931, "text": "The second step details the implementation of the caller (STEP 2)." }, { "code": null, "e": 13181, "s": 12998, "text": "The caller should use the ‘then’ method, which takes two callback methods - first for success and second for failure. Each method takes one parameter, as shown in the following code." }, { "code": null, "e": 13311, "s": 13181, "text": "getSum(5, 6) \n.then(function (result) { \n console.log(result); \n}, \nfunction (error) { \n console.log(error); \n});" }, { "code": null, "e": 13388, "s": 13311, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 13393, "s": 13388, "text": "11 \n" }, { "code": null, "e": 13541, "s": 13393, "text": "Since the return type of the getSum() is a Promise, we can actually have multiple ‘then’ statements. The first 'then' will have a return statement." }, { "code": null, "e": 13846, "s": 13541, "text": "getSum(5, 6) \n.then(function(result) { \n console.log(result); \n returngetSum(10, 20); \n // this returns another promise \n}, \nfunction(error) { \n console.log(error); \n}) \n.then(function(result) { \n console.log(result); \n}, \nfunction(error) { \n console.log(error);\n}); " }, { "code": null, "e": 13923, "s": 13846, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 13930, "s": 13923, "text": "11\n30\n" }, { "code": null, "e": 14000, "s": 13930, "text": "The following example issues three then() calls with getSum() method." }, { "code": null, "e": 14979, "s": 14000, "text": "<script> \n function getSum(n1, n2) { \n varisAnyNegative = function() { \n return n1 < 0 || n2 < 0; \n } \n var promise = new Promise(function(resolve, reject) { \n if (isAnyNegative()) { \n reject(Error(\"Negatives not supported\")); \n } \n resolve(n1 + n2); \n }); \n return promise; \n } \n getSum(5, 6) \n .then(function(result) { \n console.log(result); \n returngetSum(10, 20); \n //this returns another Promise \n }, \n function(error) { \n console.log(error); \n })\n .then(function(result) { \n console.log(result); \n returngetSum(30, 40); \n //this returns another Promise \n }, \n function(error) { \n console.log(error); \n }) \n .then(function(result) { \n console.log(result); \n }, \n function(error) { \n console.log(error); \n }); \n console.log(\"End of script \"); \n</script> " }, { "code": null, "e": 15056, "s": 14979, "text": "The following output is displayed on successful execution of the above code." }, { "code": null, "e": 15158, "s": 15056, "text": "The program displays ‘end of script’ first and then results from calling getSum() method, one by one." }, { "code": null, "e": 15186, "s": 15158, "text": "End of script \n11 \n30 \n70\n" } ]
Python | os.path.exists() method
21 May, 2019 OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in python used for common path name manipulation. os.path.exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not. Syntax: os.path.exists(path) Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path. Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False. # Python program to explain os.path.exists() method # importing os module import os # Specify pathpath = '/usr/local/bin/' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist) # Specify pathpath = '/home/User/Desktop/file.txt' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist) True False Note: os.path.exists() function may return False, if permission is not granted to execute os.stat() on the requested file, even if the path exists. Reference: https://docs.python.org/3/library/os.path.html python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n21 May, 2019" }, { "code": null, "e": 365, "s": 54, "text": "OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in python used for common path name manipulation." }, { "code": null, "e": 561, "s": 365, "text": "os.path.exists() method in Python is used to check whether the specified path exists or not. This method can be also used to check whether the given path refers to an open file descriptor or not." }, { "code": null, "e": 590, "s": 561, "text": "Syntax: os.path.exists(path)" }, { "code": null, "e": 733, "s": 590, "text": "Parameter:path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path." }, { "code": null, "e": 862, "s": 733, "text": "Return Type: This method returns a Boolean value of class bool. This method returns True if path exists otherwise returns False." }, { "code": "# Python program to explain os.path.exists() method # importing os module import os # Specify pathpath = '/usr/local/bin/' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist) # Specify pathpath = '/home/User/Desktop/file.txt' # Check whether the specified# path exists or notisExist = os.path.exists(path)print(isExist)", "e": 1234, "s": 862, "text": null }, { "code": null, "e": 1246, "s": 1234, "text": "True\nFalse\n" }, { "code": null, "e": 1394, "s": 1246, "text": "Note: os.path.exists() function may return False, if permission is not granted to execute os.stat() on the requested file, even if the path exists." }, { "code": null, "e": 1452, "s": 1394, "text": "Reference: https://docs.python.org/3/library/os.path.html" }, { "code": null, "e": 1469, "s": 1452, "text": "python-os-module" }, { "code": null, "e": 1476, "s": 1469, "text": "Python" } ]
How to limit character input in textarea including count in jQuery ?
18 Jan, 2021 In this article, we will set the limit character input in the textarea including count in the jQuery. To set the limit character in the input textarea, we use length property. Approach: We create an input text area with a given maxlength and then use jQuery code to limit the characters. First, we set the max limit and then use keyup() method to reduce the textarea character limit by 1 when we click the button and display the count on the screen. Syntax: var max_length = 25; $('textarea').keyup(function () { var len = max_length - $(this).val().length; $('.GFG').text(len); }); Example: HTML <!DOCTYPE html><html lang="en"> <head> <title> How to limit character input in the textarea including count in jQuery? </title> <!-- Import jQuery cdn library --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function () { var max_length = 25; $('textarea').keyup(function () { var len = max_length - $(this).val().length; $('.GFG').text(len); }); }); </script></head> <body style="text-align: center;"> <h1 style="color: green;"> GeeksforGeeks </h1> <h3> How to limit character input in the textarea <br>including count in jQuery? </h3> <form> <p>Maximum input characters: 25</p> <textarea maxlength="25"></textarea> <p> <span class="GFG">25</span> Characters Remaining </p> </form></body> </html> Output: CSS-Misc HTML-Misc jQuery-Misc CSS HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2021" }, { "code": null, "e": 204, "s": 28, "text": "In this article, we will set the limit character input in the textarea including count in the jQuery. To set the limit character in the input textarea, we use length property." }, { "code": null, "e": 214, "s": 204, "text": "Approach:" }, { "code": null, "e": 478, "s": 214, "text": "We create an input text area with a given maxlength and then use jQuery code to limit the characters. First, we set the max limit and then use keyup() method to reduce the textarea character limit by 1 when we click the button and display the count on the screen." }, { "code": null, "e": 486, "s": 478, "text": "Syntax:" }, { "code": null, "e": 619, "s": 486, "text": "var max_length = 25;\n$('textarea').keyup(function () {\n var len = max_length - $(this).val().length;\n $('.GFG').text(len);\n});" }, { "code": null, "e": 628, "s": 619, "text": "Example:" }, { "code": null, "e": 633, "s": 628, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to limit character input in the textarea including count in jQuery? </title> <!-- Import jQuery cdn library --> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function () { var max_length = 25; $('textarea').keyup(function () { var len = max_length - $(this).val().length; $('.GFG').text(len); }); }); </script></head> <body style=\"text-align: center;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h3> How to limit character input in the textarea <br>including count in jQuery? </h3> <form> <p>Maximum input characters: 25</p> <textarea maxlength=\"25\"></textarea> <p> <span class=\"GFG\">25</span> Characters Remaining </p> </form></body> </html>", "e": 1644, "s": 633, "text": null }, { "code": null, "e": 1652, "s": 1644, "text": "Output:" }, { "code": null, "e": 1661, "s": 1652, "text": "CSS-Misc" }, { "code": null, "e": 1671, "s": 1661, "text": "HTML-Misc" }, { "code": null, "e": 1683, "s": 1671, "text": "jQuery-Misc" }, { "code": null, "e": 1687, "s": 1683, "text": "CSS" }, { "code": null, "e": 1692, "s": 1687, "text": "HTML" }, { "code": null, "e": 1699, "s": 1692, "text": "JQuery" }, { "code": null, "e": 1716, "s": 1699, "text": "Web Technologies" }, { "code": null, "e": 1721, "s": 1716, "text": "HTML" }, { "code": null, "e": 1819, "s": 1721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1858, "s": 1819, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 1897, "s": 1858, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 1936, "s": 1897, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 1965, "s": 1936, "text": "Form validation using jQuery" }, { "code": null, "e": 2002, "s": 1965, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2026, "s": 2002, "text": "REST API (Introduction)" }, { "code": null, "e": 2079, "s": 2026, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2139, "s": 2079, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2200, "s": 2139, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Bypassing Pandas Memory Limitations | by Michael Beale | Towards Data Science
When you encounter a new set of data, you need to spend some time getting to know it. The process is not unlike meeting a new person for the first time. Instead of asking questions like “What’s your name?”, “Where are you from?”, and “Katy Perry or Taylor Swift?” you ask “What does your distribution look like?”, “Do you contain any missing or unexpected data?”, and “How do you correlate to other pieces of data?”. A typical Data Scientist spends 80% of their day on preparing data for processing1. Tools like Pandas have made the process more efficient by adding a powerful set of features to explore and munge data. Pandas can turn a vanilla CSV file into insightful aggregations and charts. Plus Pandas’ number one feature is that it keeps me out of Excel. Pandas is not all roses and sunshine however. Since the DataFrames (the foundation of Pandas) are kept in memory, there are limits to how much data can be processed at a time. Analyzing datasets the size of the New York Taxi data (1+ Billion rows and 10 years of information) can cause out of memory exceptions while trying to pack those rows into Pandas. Most Pandas related tutorials only work with 6 months of data to avoid that scenario. Processing large amounts of data (too big to fit in memory) in Pandas requires one of the below approaches: Break up the data into manageable pieces (Chunking).Use services outside of Pandas to handle filtering and aggregating of data.A combination of the above 2 methods. Break up the data into manageable pieces (Chunking). Use services outside of Pandas to handle filtering and aggregating of data. A combination of the above 2 methods. Apache projects Spark and Arrow were built to offer solutions to work with big data but I find installing and using databases to be a painless alternative to the complexity that Arrow and Spark come with. Recently I came across the open-source project QuestDB which claims high performance in the time-series database realm so I decided to give it a try. QuestDB’s REST API accepts requests using a query language I’m already familiar with: SQL. The results can be paginated through if needed, but they can also be filtered to a more Pandas memory friendly size. Although performance analysis is not the primary goal of this post, with QuestDB’s SIMD instructions and high-performance design, there is also a boost in processing speed. Incorporating a database like QuestDB in the data pipeline provides a few advantages over the common ETL approach (outlined in the image below): A dynamic way to query the dataset. A reduction in the complexity of filtering and aggregating. Shortening the path from raw data to Pandas. For all the below examples, I’m using a simple function to query QuestDB and convert those results into a Pandas DataFrame. import pandas as pdimport requests defread_questdb(query, host, per_page = 10000, max_records = None):""" Sends a SQL query to a specified host. Parameters ---------------- query : string A SQL query host : string A host location in the form of a URL. http://host:port per_page : int The limit of results to return per page. max_records : int The maximum amount of records to return (soft limit). """data = [] offset = 1 page = 1 get_more = True columns = None params = {"query": query, "limit": f"{offset},{per_page * page}","count": "true"} while get_more: r = requests.get(f"{host}exec", params=params) jsond = r.json() if r.status_code != 200: raise ValueError(jsond['error']) if not columns: columns = [x['name'] for x in jsond['columns']] if jsond['dataset'] != []: data = data + jsond['dataset'] if jsond["count"] < (per_page * page) or (max_records != None and (per_page*page) >= max_records): get_more = False else: offset = (per_page * page) + 1 page += 1 params['limit'] = f"{offset},{per_page * page}" params['nm'] = 'true' return pd.DataFrame(data=data, columns=columns) For the data, I have preloaded the New York Taxi dataset which has 1,636,055,518 rows of data from 2009 through 2019. The column definitions are available on the nyc.gov website. There is more information about installing QuestDB as well as how to load data in the documentation. Let’s start by analyzing fare_amount. Ingesting 1.6 billion rows into Pandas is not possible on my Macbook Pro so I need to use QuestDB to help me shrink the data in a more manageable size. What is the average fare_amount? query = "SELECT avg(fare_amount) FROM trips"avg_df = read_questdb(query, hostname)avg_df['avg'][0]>>>11.771664413356518 I’m also curious about how the fare_amount relates to passenger_count. Do larger groups tend to travel long distances? Below is the plot of the average fare by passenger count. query = "SELECT passenger_count, avg(fare_amount) FROM trips"df = read_questdb(query, hostname)ax = df.plot.bar(x='passenger_count', y='avg', title='Average Fare by Passenger Count', label='Passenger Count')ax.legend(["Avg Fare Amount ($)"])#add a horizontal line for the averageax.axhline(y=avg_df['avg'][0], color='red') The passenger_count of 0 looks out of place to me and although there may be a good reason for this, I’m going to remove that data from the DataFrame for now as well as sort and reindex the data. #drop zero passenger count data and set index and sort valuesdf = df.drop([6]).set_index('passenger_count').sort_values('passenger_count')#change to integersdf.index = df.index.astype('int64')#don't need to specify x axisax = df.plot.bar(y='avg', title='Average Fare by Passenger Count', label='Passenger Count')ax.legend(["Avg Fare Amount ($)"])ax.axhline(y=avg_df['avg'][0], color='red')>>>avg1 11.5484582 12.1195143 11.8922984 12.0913685 11.4661986 12.2769637 31.622068 Now that the passenger counts are in ascending order and the 0 passenger count column has been dropped, I can see that the averages for the different passenger counts are in line with the dataset average with the exception of a passenger count of 7. Since I’ve narrowed down my target dataset to the rows with a passenger_count of 7, I can bring the target rows into a Pandas DataFrame and use the `describe` function to get an overview of the fare_amount distribution. query = "select * from trips where passenger_count = 7"df7 = read_questdb(query, hostname)df7['fare_amount'].describe()>>>count 1494.000000mean 31.622068std 31.708050min 0.01000025% 7.00000050% 12.00000075% 70.000000max 373.000000Name: fare_amount, dtype: float64 Three initial observations from that output: The standard deviation is larger than the mean. Since there can’t be negative fare amounts, that must mean the data is heavily skewed.The min value is 0.01. I’m not a frequent user of Taxi Cabs but I’m pretty sure once the meter is turned on, it starts above $0.01.The max value is 373. Outliers could be applying pressure to the mean. The standard deviation is larger than the mean. Since there can’t be negative fare amounts, that must mean the data is heavily skewed. The min value is 0.01. I’m not a frequent user of Taxi Cabs but I’m pretty sure once the meter is turned on, it starts above $0.01. The max value is 373. Outliers could be applying pressure to the mean. I can plot the distribution of the data. ax = df7['fare_amount'].plot.hist() As expected the distribution is heavily skewed with a few larger outliers dragging the mean higher. But what does this tell us? Are all the other passenger_counts skewed similarly? Instead of mean, should I switch to using the median value? What other questions can be asked of this data? Switching gears here, I’m interested in knowing how the average fare per hour driven has changed over time. I can use sampling in QuestDB to help organize fare_amount averages in the monthly buckets. query = """SELECT pickup_datetime, avg(fare_amount) / (avg(cast((dropoff_datetime-pickup_datetime) as long)) / 1000000 / 60 / 60) fare_hr FROM trips SAMPLE BY 1M;""" fare_change_df = read_questdb(query,hostname)fare_change_df['pickup_datetime'] = pd.to_datetime(fare_change_df['pickup_datetime'])ax = fare_change_df[:125].plot(x='pickup_datetime',y='fare_hr') This chart creates new questions. Why did the fare_amount spike in 2012? What caused a dip in 2015? The average hourly rate is on a steady decline; what factors would cause that? There is still a long way to go before I can feel comfortable with the taxi data. I only touched the surface on a single column and there are infinite amounts of additional questions about the other columns and what relationships the columns have with each other. Each question answered leads to more questions. Pandas is one of the more important libraries in the Python data science stack but as the data size grows, working completely within Pandas requires help from additional tools. I like to look to QuestDB to perform high volume filtering, aggregation, and grouping operations to extend the utility of Pandas. [1] Gil Press, Cleaning Big Data: Most Time-Consuming, Least Enjoyable Data Science Task, Survey Says (2016), Forbes
[ { "code": null, "e": 589, "s": 172, "text": "When you encounter a new set of data, you need to spend some time getting to know it. The process is not unlike meeting a new person for the first time. Instead of asking questions like “What’s your name?”, “Where are you from?”, and “Katy Perry or Taylor Swift?” you ask “What does your distribution look like?”, “Do you contain any missing or unexpected data?”, and “How do you correlate to other pieces of data?”." }, { "code": null, "e": 934, "s": 589, "text": "A typical Data Scientist spends 80% of their day on preparing data for processing1. Tools like Pandas have made the process more efficient by adding a powerful set of features to explore and munge data. Pandas can turn a vanilla CSV file into insightful aggregations and charts. Plus Pandas’ number one feature is that it keeps me out of Excel." }, { "code": null, "e": 1376, "s": 934, "text": "Pandas is not all roses and sunshine however. Since the DataFrames (the foundation of Pandas) are kept in memory, there are limits to how much data can be processed at a time. Analyzing datasets the size of the New York Taxi data (1+ Billion rows and 10 years of information) can cause out of memory exceptions while trying to pack those rows into Pandas. Most Pandas related tutorials only work with 6 months of data to avoid that scenario." }, { "code": null, "e": 1484, "s": 1376, "text": "Processing large amounts of data (too big to fit in memory) in Pandas requires one of the below approaches:" }, { "code": null, "e": 1649, "s": 1484, "text": "Break up the data into manageable pieces (Chunking).Use services outside of Pandas to handle filtering and aggregating of data.A combination of the above 2 methods." }, { "code": null, "e": 1702, "s": 1649, "text": "Break up the data into manageable pieces (Chunking)." }, { "code": null, "e": 1778, "s": 1702, "text": "Use services outside of Pandas to handle filtering and aggregating of data." }, { "code": null, "e": 1816, "s": 1778, "text": "A combination of the above 2 methods." }, { "code": null, "e": 2171, "s": 1816, "text": "Apache projects Spark and Arrow were built to offer solutions to work with big data but I find installing and using databases to be a painless alternative to the complexity that Arrow and Spark come with. Recently I came across the open-source project QuestDB which claims high performance in the time-series database realm so I decided to give it a try." }, { "code": null, "e": 2552, "s": 2171, "text": "QuestDB’s REST API accepts requests using a query language I’m already familiar with: SQL. The results can be paginated through if needed, but they can also be filtered to a more Pandas memory friendly size. Although performance analysis is not the primary goal of this post, with QuestDB’s SIMD instructions and high-performance design, there is also a boost in processing speed." }, { "code": null, "e": 2697, "s": 2552, "text": "Incorporating a database like QuestDB in the data pipeline provides a few advantages over the common ETL approach (outlined in the image below):" }, { "code": null, "e": 2733, "s": 2697, "text": "A dynamic way to query the dataset." }, { "code": null, "e": 2793, "s": 2733, "text": "A reduction in the complexity of filtering and aggregating." }, { "code": null, "e": 2838, "s": 2793, "text": "Shortening the path from raw data to Pandas." }, { "code": null, "e": 2962, "s": 2838, "text": "For all the below examples, I’m using a simple function to query QuestDB and convert those results into a Pandas DataFrame." }, { "code": null, "e": 4253, "s": 2962, "text": "import pandas as pdimport requests defread_questdb(query, host, per_page = 10000, max_records = None):\"\"\" Sends a SQL query to a specified host. Parameters ---------------- query : string A SQL query host : string A host location in the form of a URL. http://host:port per_page : int The limit of results to return per page. max_records : int The maximum amount of records to return (soft limit). \"\"\"data = [] offset = 1 page = 1 get_more = True columns = None params = {\"query\": query, \"limit\": f\"{offset},{per_page * page}\",\"count\": \"true\"} while get_more: r = requests.get(f\"{host}exec\", params=params) jsond = r.json() if r.status_code != 200: raise ValueError(jsond['error']) if not columns: columns = [x['name'] for x in jsond['columns']] if jsond['dataset'] != []: data = data + jsond['dataset'] if jsond[\"count\"] < (per_page * page) or (max_records != None and (per_page*page) >= max_records): get_more = False else: offset = (per_page * page) + 1 page += 1 params['limit'] = f\"{offset},{per_page * page}\" params['nm'] = 'true' return pd.DataFrame(data=data, columns=columns)" }, { "code": null, "e": 4432, "s": 4253, "text": "For the data, I have preloaded the New York Taxi dataset which has 1,636,055,518 rows of data from 2009 through 2019. The column definitions are available on the nyc.gov website." }, { "code": null, "e": 4533, "s": 4432, "text": "There is more information about installing QuestDB as well as how to load data in the documentation." }, { "code": null, "e": 4723, "s": 4533, "text": "Let’s start by analyzing fare_amount. Ingesting 1.6 billion rows into Pandas is not possible on my Macbook Pro so I need to use QuestDB to help me shrink the data in a more manageable size." }, { "code": null, "e": 4756, "s": 4723, "text": "What is the average fare_amount?" }, { "code": null, "e": 4876, "s": 4756, "text": "query = \"SELECT avg(fare_amount) FROM trips\"avg_df = read_questdb(query, hostname)avg_df['avg'][0]>>>11.771664413356518" }, { "code": null, "e": 5053, "s": 4876, "text": "I’m also curious about how the fare_amount relates to passenger_count. Do larger groups tend to travel long distances? Below is the plot of the average fare by passenger count." }, { "code": null, "e": 5376, "s": 5053, "text": "query = \"SELECT passenger_count, avg(fare_amount) FROM trips\"df = read_questdb(query, hostname)ax = df.plot.bar(x='passenger_count', y='avg', title='Average Fare by Passenger Count', label='Passenger Count')ax.legend([\"Avg Fare Amount ($)\"])#add a horizontal line for the averageax.axhline(y=avg_df['avg'][0], color='red')" }, { "code": null, "e": 5571, "s": 5376, "text": "The passenger_count of 0 looks out of place to me and although there may be a good reason for this, I’m going to remove that data from the DataFrame for now as well as sort and reindex the data." }, { "code": null, "e": 6044, "s": 5571, "text": "#drop zero passenger count data and set index and sort valuesdf = df.drop([6]).set_index('passenger_count').sort_values('passenger_count')#change to integersdf.index = df.index.astype('int64')#don't need to specify x axisax = df.plot.bar(y='avg', title='Average Fare by Passenger Count', label='Passenger Count')ax.legend([\"Avg Fare Amount ($)\"])ax.axhline(y=avg_df['avg'][0], color='red')>>>avg1 11.5484582 12.1195143 11.8922984 12.0913685 11.4661986 12.2769637 31.622068" }, { "code": null, "e": 6294, "s": 6044, "text": "Now that the passenger counts are in ascending order and the 0 passenger count column has been dropped, I can see that the averages for the different passenger counts are in line with the dataset average with the exception of a passenger count of 7." }, { "code": null, "e": 6514, "s": 6294, "text": "Since I’ve narrowed down my target dataset to the rows with a passenger_count of 7, I can bring the target rows into a Pandas DataFrame and use the `describe` function to get an overview of the fare_amount distribution." }, { "code": null, "e": 6815, "s": 6514, "text": "query = \"select * from trips where passenger_count = 7\"df7 = read_questdb(query, hostname)df7['fare_amount'].describe()>>>count 1494.000000mean 31.622068std 31.708050min 0.01000025% 7.00000050% 12.00000075% 70.000000max 373.000000Name: fare_amount, dtype: float64" }, { "code": null, "e": 6860, "s": 6815, "text": "Three initial observations from that output:" }, { "code": null, "e": 7196, "s": 6860, "text": "The standard deviation is larger than the mean. Since there can’t be negative fare amounts, that must mean the data is heavily skewed.The min value is 0.01. I’m not a frequent user of Taxi Cabs but I’m pretty sure once the meter is turned on, it starts above $0.01.The max value is 373. Outliers could be applying pressure to the mean." }, { "code": null, "e": 7331, "s": 7196, "text": "The standard deviation is larger than the mean. Since there can’t be negative fare amounts, that must mean the data is heavily skewed." }, { "code": null, "e": 7463, "s": 7331, "text": "The min value is 0.01. I’m not a frequent user of Taxi Cabs but I’m pretty sure once the meter is turned on, it starts above $0.01." }, { "code": null, "e": 7534, "s": 7463, "text": "The max value is 373. Outliers could be applying pressure to the mean." }, { "code": null, "e": 7575, "s": 7534, "text": "I can plot the distribution of the data." }, { "code": null, "e": 7611, "s": 7575, "text": "ax = df7['fare_amount'].plot.hist()" }, { "code": null, "e": 7900, "s": 7611, "text": "As expected the distribution is heavily skewed with a few larger outliers dragging the mean higher. But what does this tell us? Are all the other passenger_counts skewed similarly? Instead of mean, should I switch to using the median value? What other questions can be asked of this data?" }, { "code": null, "e": 8100, "s": 7900, "text": "Switching gears here, I’m interested in knowing how the average fare per hour driven has changed over time. I can use sampling in QuestDB to help organize fare_amount averages in the monthly buckets." }, { "code": null, "e": 8460, "s": 8100, "text": "query = \"\"\"SELECT pickup_datetime, avg(fare_amount) / (avg(cast((dropoff_datetime-pickup_datetime) as long)) / 1000000 / 60 / 60) fare_hr FROM trips SAMPLE BY 1M;\"\"\" fare_change_df = read_questdb(query,hostname)fare_change_df['pickup_datetime'] = pd.to_datetime(fare_change_df['pickup_datetime'])ax = fare_change_df[:125].plot(x='pickup_datetime',y='fare_hr')" }, { "code": null, "e": 8639, "s": 8460, "text": "This chart creates new questions. Why did the fare_amount spike in 2012? What caused a dip in 2015? The average hourly rate is on a steady decline; what factors would cause that?" }, { "code": null, "e": 8951, "s": 8639, "text": "There is still a long way to go before I can feel comfortable with the taxi data. I only touched the surface on a single column and there are infinite amounts of additional questions about the other columns and what relationships the columns have with each other. Each question answered leads to more questions." }, { "code": null, "e": 9258, "s": 8951, "text": "Pandas is one of the more important libraries in the Python data science stack but as the data size grows, working completely within Pandas requires help from additional tools. I like to look to QuestDB to perform high volume filtering, aggregation, and grouping operations to extend the utility of Pandas." } ]
Creating a view of parent array in Julia - view(), @view and @views Methods - GeeksforGeeks
21 Apr, 2020 The view() is an inbuilt function in julia which is used to return a view into the given parent array A with the given indices instead of making a copy. Syntax: view(A, inds...) Parameters: A: Specified parent array. inds: Specified indices. Returns: It returns a view into the given parent array A with the given indices instead of making a copy. Example: # Julia program to illustrate # the use of view() method # Getting a view into the given parent# array A with the given indices # instead of making a copy.A = [5, 10, 15, 20];println(view(A, 2)) B = [5 10; 15 20];println(view(B, :, 1)) C = cat([1 2; 3 4], [5 6; 7 8], dims = 3);println(view(C, :, :, 1)) Output: The @view() is an inbuilt function in julia which is used to create a sub array from the given indexing expression. Syntax:@view A[inds...] Parameters: A: Specified parent array. inds: Specified indices. Returns: It returns the created sub array from the given indexing expression. Example: # Julia program to illustrate # the use of @view() method # Getting the created sub array # from the given indexing expression.A = [5, 10, 15, 20];println(@view A[3]) B = [5 10; 15 20];println(@view B[:, 1]) C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3);println(@view(C[:, :, 2])) Output: The @views() is an inbuilt function in julia which is used to convert every given array-slicing operation in the given expression. Syntax:@views expression Parameters: expression: Specified expression. Returns: It returns the desired view. Example: # Julia program to illustrate # the use of @views() method # Getting the created sub array # from the given indexing expression.A = zeros(4, 4);@views for row in 2:4 b = A[row, :] b[:] .= rowendprintln(A) Output: Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Searching in Array for a given element in Julia Get array dimensions and size of a dimension in Julia - size() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Get number of elements of array in Julia - length() Method Find maximum element along with its index in Julia - findmax() Method Getting the maximum value from a list in Julia - max() Method Exception handling in Julia Getting the absolute value of a number in Julia - abs() Method Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods Working with Date and Time in Julia
[ { "code": null, "e": 24544, "s": 24516, "text": "\n21 Apr, 2020" }, { "code": null, "e": 24697, "s": 24544, "text": "The view() is an inbuilt function in julia which is used to return a view into the given parent array A with the given indices instead of making a copy." }, { "code": null, "e": 24722, "s": 24697, "text": "Syntax: view(A, inds...)" }, { "code": null, "e": 24734, "s": 24722, "text": "Parameters:" }, { "code": null, "e": 24761, "s": 24734, "text": "A: Specified parent array." }, { "code": null, "e": 24786, "s": 24761, "text": "inds: Specified indices." }, { "code": null, "e": 24892, "s": 24786, "text": "Returns: It returns a view into the given parent array A with the given indices instead of making a copy." }, { "code": null, "e": 24901, "s": 24892, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of view() method # Getting a view into the given parent# array A with the given indices # instead of making a copy.A = [5, 10, 15, 20];println(view(A, 2)) B = [5 10; 15 20];println(view(B, :, 1)) C = cat([1 2; 3 4], [5 6; 7 8], dims = 3);println(view(C, :, :, 1))", "e": 25209, "s": 24901, "text": null }, { "code": null, "e": 25217, "s": 25209, "text": "Output:" }, { "code": null, "e": 25333, "s": 25217, "text": "The @view() is an inbuilt function in julia which is used to create a sub array from the given indexing expression." }, { "code": null, "e": 25357, "s": 25333, "text": "Syntax:@view A[inds...]" }, { "code": null, "e": 25369, "s": 25357, "text": "Parameters:" }, { "code": null, "e": 25396, "s": 25369, "text": "A: Specified parent array." }, { "code": null, "e": 25421, "s": 25396, "text": "inds: Specified indices." }, { "code": null, "e": 25499, "s": 25421, "text": "Returns: It returns the created sub array from the given indexing expression." }, { "code": null, "e": 25508, "s": 25499, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of @view() method # Getting the created sub array # from the given indexing expression.A = [5, 10, 15, 20];println(@view A[3]) B = [5 10; 15 20];println(@view B[:, 1]) C = cat([1 2; 3 4], [5 6; 7 8], [2 2; 3 4], dims = 3);println(@view(C[:, :, 2]))", "e": 25801, "s": 25508, "text": null }, { "code": null, "e": 25809, "s": 25801, "text": "Output:" }, { "code": null, "e": 25940, "s": 25809, "text": "The @views() is an inbuilt function in julia which is used to convert every given array-slicing operation in the given expression." }, { "code": null, "e": 25965, "s": 25940, "text": "Syntax:@views expression" }, { "code": null, "e": 25977, "s": 25965, "text": "Parameters:" }, { "code": null, "e": 26011, "s": 25977, "text": "expression: Specified expression." }, { "code": null, "e": 26049, "s": 26011, "text": "Returns: It returns the desired view." }, { "code": null, "e": 26058, "s": 26049, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of @views() method # Getting the created sub array # from the given indexing expression.A = zeros(4, 4);@views for row in 2:4 b = A[row, :] b[:] .= rowendprintln(A)", "e": 26271, "s": 26058, "text": null }, { "code": null, "e": 26279, "s": 26271, "text": "Output:" }, { "code": null, "e": 26285, "s": 26279, "text": "Julia" }, { "code": null, "e": 26383, "s": 26285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26431, "s": 26383, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 26501, "s": 26431, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 26574, "s": 26501, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 26633, "s": 26574, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 26703, "s": 26633, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 26765, "s": 26703, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 26793, "s": 26765, "text": "Exception handling in Julia" }, { "code": null, "e": 26856, "s": 26793, "text": "Getting the absolute value of a number in Julia - abs() Method" }, { "code": null, "e": 26937, "s": 26856, "text": "Reverse array elements in Julia - reverse(), reverse!() and reverseind() Methods" } ]
Python 3 - String rjust() Method
The rjust() method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). Following is the syntax for rjust() method − str.rjust(width[, fillchar]) width − This is the string length in total after padding. width − This is the string length in total after padding. fillchar − This is the filler character, default is a space. fillchar − This is the filler character, default is a space. This method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s). The following example shows the usage of rjust() method. #!/usr/bin/python3 str = "this is string example....wow!!!" print (str.rjust(50, '*')) When we run above program, it produces the following result − ******************this is string example....wow!!! 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2552, "s": 2340, "text": "The rjust() method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)." }, { "code": null, "e": 2597, "s": 2552, "text": "Following is the syntax for rjust() method −" }, { "code": null, "e": 2627, "s": 2597, "text": "str.rjust(width[, fillchar])\n" }, { "code": null, "e": 2685, "s": 2627, "text": "width − This is the string length in total after padding." }, { "code": null, "e": 2743, "s": 2685, "text": "width − This is the string length in total after padding." }, { "code": null, "e": 2804, "s": 2743, "text": "fillchar − This is the filler character, default is a space." }, { "code": null, "e": 2865, "s": 2804, "text": "fillchar − This is the filler character, default is a space." }, { "code": null, "e": 3070, "s": 2865, "text": "This method returns the string right justified in a string of length width. Padding is done using the specified fillchar (default is a space). The original string is returned if width is less than len(s)." }, { "code": null, "e": 3127, "s": 3070, "text": "The following example shows the usage of rjust() method." }, { "code": null, "e": 3215, "s": 3127, "text": "#!/usr/bin/python3\n\nstr = \"this is string example....wow!!!\"\nprint (str.rjust(50, '*'))" }, { "code": null, "e": 3277, "s": 3215, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3329, "s": 3277, "text": "******************this is string example....wow!!!\n" }, { "code": null, "e": 3366, "s": 3329, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3382, "s": 3366, "text": " Malhar Lathkar" }, { "code": null, "e": 3415, "s": 3382, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3434, "s": 3415, "text": " Arnab Chakraborty" }, { "code": null, "e": 3469, "s": 3434, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3491, "s": 3469, "text": " In28Minutes Official" }, { "code": null, "e": 3525, "s": 3491, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3553, "s": 3525, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3588, "s": 3553, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3602, "s": 3588, "text": " Lets Kode It" }, { "code": null, "e": 3635, "s": 3602, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3652, "s": 3635, "text": " Abhilash Nelson" }, { "code": null, "e": 3659, "s": 3652, "text": " Print" }, { "code": null, "e": 3670, "s": 3659, "text": " Add Notes" } ]
Check if two arrays are permutations of each other - GeeksforGeeks
25 Aug, 2021 Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false. Examples: Input: arr1[] = {2, 1, 3, 5, 4, 3, 2} arr2[] = {3, 2, 2, 4, 5, 3, 1} Output: Yes Input: arr1[] = {2, 1, 3, 5,} arr2[] = {3, 2, 2, 4} Output: No We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to sort both arrays and compare sorted arrays. The time complexity of this solution is O(nLogn)A Better Solution is to use Hashing. Create a Hash Map for all the elements of arr1[] such that array elements are keys and their counts are values.Traverse arr2[] and search for each element of arr2[] in the Hash Map. If an element is found then decrement its count in the hash map. If not found, then return false.If all elements are found then return true. Create a Hash Map for all the elements of arr1[] such that array elements are keys and their counts are values. Traverse arr2[] and search for each element of arr2[] in the Hash Map. If an element is found then decrement its count in the hash map. If not found, then return false. If all elements are found then return true. Below is the implementation of this approach. C++ Java Python3 C# Javascript // A C++ program to find one array is permutation of other array#include <bits/stdc++.h>using namespace std; // Returns true if arr1[] and arr2[] are permutations of each otherbool arePermutations(int arr1[], int arr2[], int n, int m){ // Arrays cannot be permutations of one another unless they are // of the same length if(n != m) { return false; } // Creates an empty hashMap hM map<int, int> hm; // Traverse through the first array and add elements to hash map for (int i = 0; i < n; i++) { int x = arr1[i]; hm[x]++; } // Traverse through second array and check if every element is // present in hash map for (int i = 0; i < m; i++) { int x = arr2[i]; // If element is not present in hash map or element // is not present less number of times if(hm[x] == 0) { return false; } hm[x]--; } return true;} // Driver function to test above functionint main() { int arr1[] = {2, 1, 3, 5, 4, 3, 2}; int arr2[] = {3, 2, 2, 4, 5, 3, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); int m = sizeof(arr2)/sizeof(arr2[0]); if (arePermutations(arr1, arr2, n, m)) cout << "Arrays are permutations of each other" << endl; else cout << "Arrays are NOT permutations of each other" << endl; return 0;} // This code is contributed by avanitrachhadiya2155 // A Java program to find one array is permutation of other arrayimport java.util.HashMap; class Permutations{ // Returns true if arr1[] and arr2[] are permutations of each other static Boolean arePermutations(int arr1[], int arr2[]) { // Arrays cannot be permutations of one another unless they are // of the same length if (arr1.length != arr2.length) return false; // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Traverse through the first array and add elements to hash map for (int i = 0; i < arr1.length; i++) { int x = arr1[i]; if (hM.get(x) == null) hM.put(x, 1); else { int k = hM.get(x); hM.put(x, k+1); } } // Traverse through second array and check if every element is // present in hash map for (int i = 0; i < arr2.length; i++) { int x = arr2[i]; // If element is not present in hash map or element // is not present less number of times if (hM.get(x) == null || hM.get(x) == 0) return false; int k = hM.get(x); hM.put(x, k-1); } return true; } // Driver function to test above function public static void main(String arg[]) { int arr1[] = {2, 1, 3, 5, 4, 3, 2}; int arr2[] = {3, 2, 2, 4, 5, 3, 1}; if (arePermutations(arr1, arr2)) System.out.println("Arrays are permutations of each other"); else System.out.println("Arrays are NOT permutations of each other"); }} # Python3 program to find one# array is permutation of other arrayfrom collections import defaultdict # Returns true if arr1[] and# arr2[] are permutations of# each otherdef arePermutations(arr1, arr2): # Arrays cannot be permutations of one another # unless they are of the same length if (len(arr1) != len(arr2)): return False # Creates an empty hashMap hM hM = defaultdict (int) # Traverse through the first # array and add elements to # hash map for i in range (len(arr1)): x = arr1[i] hM[x] += 1 # Traverse through second array # and check if every element is # present in hash map for i in range (len(arr2)): x = arr2[i] # If element is not present # in hash map or element # is not present less number # of times if x not in hM or hM[x] == 0: return False hM[x] -= 1 return True # Driver codeif __name__ == "__main__": arr1 = [2, 1, 3, 5, 4, 3, 2] arr2 = [3, 2, 2, 4, 5, 3, 1] if (arePermutations(arr1, arr2)): print("Arrays are permutations of each other") else: print("Arrays are NOT permutations of each other") # This code is contributed by Chitranayal // C# program to find one array// is permutation of other arrayusing System;using System.Collections.Generic; public class Permutations { // Returns true if arr1[] and arr2[] // are permutations of each other static Boolean arePermutations(int[] arr1, int[] arr2) { // Arrays cannot be permutations of one another if // they are not the the same length if (arr1.Length != arr2.Length) return false; // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); // Traverse through the first array // and add elements to hash map for (int i = 0; i < arr1.Length; i++) { int x = arr1[i]; if (!hM.ContainsKey(x)) hM.Add(x, 1); else { int k = hM[x]; hM.Remove(x); hM.Add(x, k + 1); } } // Traverse through second array and check if every // element is present in hash map (and the same // number of times) for (int i = 0; i < arr2.Length; i++) { int x = arr2[i]; // If element is not present in hash map or // element is not present the same number of // times if (!hM.ContainsKey(x)) return false; // Not present in the hash map int k = hM[x]; if (k == 0) return false; // Not present the same number // of times hM.Remove(x); hM.Add(x, k - 1); } return true; } // Driver code public static void Main() { int[] arr1 = { 2, 1, 3, 5, 4, 3, 2 }; int[] arr2 = { 3, 2, 2, 4, 5, 3, 1 }; if (arePermutations(arr1, arr2)) Console.WriteLine("Arrays are permutations of each other"); else Console.WriteLine("Arrays are NOT permutations of each other"); }} /* This code contributed by PrinciRaj1992 */ <script> // A Javascript program to find one array/// is permutation of other array // Returns true if arr1[] and arr2[] // are permutations of each other function arePermutations(arr1,arr2) { // Arrays cannot be permutations of // one another unless they are // of the same length if (arr1.length != arr2.length) return false; // Creates an empty hashMap hM let hM = new Map(); // Traverse through the first array // and add elements to hash map for (let i = 0; i < arr1.length; i++) { let x = arr1[i]; if (!hM.has(x)) hM.set(x, 1); else { let k = hM[x]; hM.set(x, k+1); } } // Traverse through second array and // check if every element is // present in hash map for (let i = 0; i < arr2.length; i++) { let x = arr2[i]; // If element is not present in // hash map or element // is not present less number of times if (!hM.has(x) || hM[x] == 0) return false; let k = hM[x]; hM.set(x, k-1); } return true; } // Driver function to test above function let arr1=[2, 1, 3, 5, 4, 3, 2]; let arr2=[3, 2, 2, 4, 5, 3, 1]; if (arePermutations(arr1, arr2)) document.write( "Arrays are permutations of each other" ); else document.write( "Arrays are NOT permutations of each other" ); // This code is contributed by rag2127 </script> Arrays are permutations of each other The time complexity of this method is O(n) under the assumption that we have a hash function inserts and finds elements in O(1) time.This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above princiraj1992 ukasp bmccorkendale avanitrachhadiya2155 rag2127 gabaa406 Arrays Combinatorial Hash Java Arrays Hash Java Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Factorial of a large number Count ways to reach the nth stair using step 1, 2 or 3
[ { "code": null, "e": 24698, "s": 24670, "text": "\n25 Aug, 2021" }, { "code": null, "e": 24840, "s": 24698, "text": "Given two unsorted arrays of the same size, write a function that returns true if two arrays are permutations of each other, otherwise false." }, { "code": null, "e": 24851, "s": 24840, "text": "Examples: " }, { "code": null, "e": 25010, "s": 24851, "text": "Input: arr1[] = {2, 1, 3, 5, 4, 3, 2}\n arr2[] = {3, 2, 2, 4, 5, 3, 1}\nOutput: Yes\n\nInput: arr1[] = {2, 1, 3, 5,}\n arr2[] = {3, 2, 2, 4}\nOutput: No" }, { "code": null, "e": 25243, "s": 25010, "text": "We strongly recommend you to minimize your browser and try this yourself first.A Simple Solution is to sort both arrays and compare sorted arrays. The time complexity of this solution is O(nLogn)A Better Solution is to use Hashing. " }, { "code": null, "e": 25566, "s": 25243, "text": "Create a Hash Map for all the elements of arr1[] such that array elements are keys and their counts are values.Traverse arr2[] and search for each element of arr2[] in the Hash Map. If an element is found then decrement its count in the hash map. If not found, then return false.If all elements are found then return true." }, { "code": null, "e": 25678, "s": 25566, "text": "Create a Hash Map for all the elements of arr1[] such that array elements are keys and their counts are values." }, { "code": null, "e": 25847, "s": 25678, "text": "Traverse arr2[] and search for each element of arr2[] in the Hash Map. If an element is found then decrement its count in the hash map. If not found, then return false." }, { "code": null, "e": 25891, "s": 25847, "text": "If all elements are found then return true." }, { "code": null, "e": 25939, "s": 25891, "text": "Below is the implementation of this approach. " }, { "code": null, "e": 25943, "s": 25939, "text": "C++" }, { "code": null, "e": 25948, "s": 25943, "text": "Java" }, { "code": null, "e": 25956, "s": 25948, "text": "Python3" }, { "code": null, "e": 25959, "s": 25956, "text": "C#" }, { "code": null, "e": 25970, "s": 25959, "text": "Javascript" }, { "code": "// A C++ program to find one array is permutation of other array#include <bits/stdc++.h>using namespace std; // Returns true if arr1[] and arr2[] are permutations of each otherbool arePermutations(int arr1[], int arr2[], int n, int m){ // Arrays cannot be permutations of one another unless they are // of the same length if(n != m) { return false; } // Creates an empty hashMap hM map<int, int> hm; // Traverse through the first array and add elements to hash map for (int i = 0; i < n; i++) { int x = arr1[i]; hm[x]++; } // Traverse through second array and check if every element is // present in hash map for (int i = 0; i < m; i++) { int x = arr2[i]; // If element is not present in hash map or element // is not present less number of times if(hm[x] == 0) { return false; } hm[x]--; } return true;} // Driver function to test above functionint main() { int arr1[] = {2, 1, 3, 5, 4, 3, 2}; int arr2[] = {3, 2, 2, 4, 5, 3, 1}; int n = sizeof(arr1)/sizeof(arr1[0]); int m = sizeof(arr2)/sizeof(arr2[0]); if (arePermutations(arr1, arr2, n, m)) cout << \"Arrays are permutations of each other\" << endl; else cout << \"Arrays are NOT permutations of each other\" << endl; return 0;} // This code is contributed by avanitrachhadiya2155", "e": 27399, "s": 25970, "text": null }, { "code": "// A Java program to find one array is permutation of other arrayimport java.util.HashMap; class Permutations{ // Returns true if arr1[] and arr2[] are permutations of each other static Boolean arePermutations(int arr1[], int arr2[]) { // Arrays cannot be permutations of one another unless they are // of the same length if (arr1.length != arr2.length) return false; // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // Traverse through the first array and add elements to hash map for (int i = 0; i < arr1.length; i++) { int x = arr1[i]; if (hM.get(x) == null) hM.put(x, 1); else { int k = hM.get(x); hM.put(x, k+1); } } // Traverse through second array and check if every element is // present in hash map for (int i = 0; i < arr2.length; i++) { int x = arr2[i]; // If element is not present in hash map or element // is not present less number of times if (hM.get(x) == null || hM.get(x) == 0) return false; int k = hM.get(x); hM.put(x, k-1); } return true; } // Driver function to test above function public static void main(String arg[]) { int arr1[] = {2, 1, 3, 5, 4, 3, 2}; int arr2[] = {3, 2, 2, 4, 5, 3, 1}; if (arePermutations(arr1, arr2)) System.out.println(\"Arrays are permutations of each other\"); else System.out.println(\"Arrays are NOT permutations of each other\"); }}", "e": 29112, "s": 27399, "text": null }, { "code": "# Python3 program to find one# array is permutation of other arrayfrom collections import defaultdict # Returns true if arr1[] and# arr2[] are permutations of# each otherdef arePermutations(arr1, arr2): # Arrays cannot be permutations of one another # unless they are of the same length if (len(arr1) != len(arr2)): return False # Creates an empty hashMap hM hM = defaultdict (int) # Traverse through the first # array and add elements to # hash map for i in range (len(arr1)): x = arr1[i] hM[x] += 1 # Traverse through second array # and check if every element is # present in hash map for i in range (len(arr2)): x = arr2[i] # If element is not present # in hash map or element # is not present less number # of times if x not in hM or hM[x] == 0: return False hM[x] -= 1 return True # Driver codeif __name__ == \"__main__\": arr1 = [2, 1, 3, 5, 4, 3, 2] arr2 = [3, 2, 2, 4, 5, 3, 1] if (arePermutations(arr1, arr2)): print(\"Arrays are permutations of each other\") else: print(\"Arrays are NOT permutations of each other\") # This code is contributed by Chitranayal", "e": 30373, "s": 29112, "text": null }, { "code": "// C# program to find one array// is permutation of other arrayusing System;using System.Collections.Generic; public class Permutations { // Returns true if arr1[] and arr2[] // are permutations of each other static Boolean arePermutations(int[] arr1, int[] arr2) { // Arrays cannot be permutations of one another if // they are not the the same length if (arr1.Length != arr2.Length) return false; // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); // Traverse through the first array // and add elements to hash map for (int i = 0; i < arr1.Length; i++) { int x = arr1[i]; if (!hM.ContainsKey(x)) hM.Add(x, 1); else { int k = hM[x]; hM.Remove(x); hM.Add(x, k + 1); } } // Traverse through second array and check if every // element is present in hash map (and the same // number of times) for (int i = 0; i < arr2.Length; i++) { int x = arr2[i]; // If element is not present in hash map or // element is not present the same number of // times if (!hM.ContainsKey(x)) return false; // Not present in the hash map int k = hM[x]; if (k == 0) return false; // Not present the same number // of times hM.Remove(x); hM.Add(x, k - 1); } return true; } // Driver code public static void Main() { int[] arr1 = { 2, 1, 3, 5, 4, 3, 2 }; int[] arr2 = { 3, 2, 2, 4, 5, 3, 1 }; if (arePermutations(arr1, arr2)) Console.WriteLine(\"Arrays are permutations of each other\"); else Console.WriteLine(\"Arrays are NOT permutations of each other\"); }} /* This code contributed by PrinciRaj1992 */", "e": 32345, "s": 30373, "text": null }, { "code": "<script> // A Javascript program to find one array/// is permutation of other array // Returns true if arr1[] and arr2[] // are permutations of each other function arePermutations(arr1,arr2) { // Arrays cannot be permutations of // one another unless they are // of the same length if (arr1.length != arr2.length) return false; // Creates an empty hashMap hM let hM = new Map(); // Traverse through the first array // and add elements to hash map for (let i = 0; i < arr1.length; i++) { let x = arr1[i]; if (!hM.has(x)) hM.set(x, 1); else { let k = hM[x]; hM.set(x, k+1); } } // Traverse through second array and // check if every element is // present in hash map for (let i = 0; i < arr2.length; i++) { let x = arr2[i]; // If element is not present in // hash map or element // is not present less number of times if (!hM.has(x) || hM[x] == 0) return false; let k = hM[x]; hM.set(x, k-1); } return true; } // Driver function to test above function let arr1=[2, 1, 3, 5, 4, 3, 2]; let arr2=[3, 2, 2, 4, 5, 3, 1]; if (arePermutations(arr1, arr2)) document.write( \"Arrays are permutations of each other\" ); else document.write( \"Arrays are NOT permutations of each other\" ); // This code is contributed by rag2127 </script>", "e": 34007, "s": 32345, "text": null }, { "code": null, "e": 34045, "s": 34007, "text": "Arrays are permutations of each other" }, { "code": null, "e": 34339, "s": 34045, "text": "The time complexity of this method is O(n) under the assumption that we have a hash function inserts and finds elements in O(1) time.This article is contributed by Ravi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 34353, "s": 34339, "text": "princiraj1992" }, { "code": null, "e": 34359, "s": 34353, "text": "ukasp" }, { "code": null, "e": 34373, "s": 34359, "text": "bmccorkendale" }, { "code": null, "e": 34394, "s": 34373, "text": "avanitrachhadiya2155" }, { "code": null, "e": 34402, "s": 34394, "text": "rag2127" }, { "code": null, "e": 34411, "s": 34402, "text": "gabaa406" }, { "code": null, "e": 34418, "s": 34411, "text": "Arrays" }, { "code": null, "e": 34432, "s": 34418, "text": "Combinatorial" }, { "code": null, "e": 34437, "s": 34432, "text": "Hash" }, { "code": null, "e": 34442, "s": 34437, "text": "Java" }, { "code": null, "e": 34449, "s": 34442, "text": "Arrays" }, { "code": null, "e": 34454, "s": 34449, "text": "Hash" }, { "code": null, "e": 34459, "s": 34454, "text": "Java" }, { "code": null, "e": 34473, "s": 34459, "text": "Combinatorial" }, { "code": null, "e": 34571, "s": 34473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34619, "s": 34571, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34663, "s": 34619, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34695, "s": 34663, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34718, "s": 34695, "text": "Introduction to Arrays" }, { "code": null, "e": 34732, "s": 34718, "text": "Linear Search" }, { "code": null, "e": 34792, "s": 34732, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 34830, "s": 34792, "text": "Permutation and Combination in Python" }, { "code": null, "e": 34907, "s": 34830, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 34935, "s": 34907, "text": "Factorial of a large number" } ]
URL getRef() method in Java with Examples - GeeksforGeeks
31 Dec, 2018 The getRef() function is a part of URL class. The function getRef() returns the Reference or anchor part of a specified URL. Function Signature: public String getRef() Syntax: url.getRef() Parameter: This function does not require any parameter Return Type: The function returns String Type Below programs illustrates the use of getRef() function: Example 1: Given a URL we will get the Reference or anchor using the getRef() function. // Java program to show the// use of the function getRef() import java.net.*; class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url= new URL("https:// www.geeksforgeeks.org#Arnab_Kundu"); // get the Reference or anchor String _Ref=url.getRef(); // display the URL System.out.println("URL = "+url); // display the Reference or anchor System.out.println(" Reference or anchor="+_Ref); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }} URL = https:// www.geeksforgeeks.org#Arnab_Kundu Reference or anchor=Arnab_Kundu Example 2: Now we will not provide any anchor and use the function to get the Reference or anchor and see the results. // Java program to show the// use of the function getRef() import java.net.*; class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL("https:// www.geeksforgeeks.org"); // get the Reference or anchor String _Ref = url.getRef(); // display the URL System.out.println("URL = " + url); // display the Reference or anchor System.out.println(" Reference or anchor= " + _Ref); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }} URL = https:// www.geeksforgeeks.org Reference or anchor= null Java-Functions Java-net-package Java-URL Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Overriding in Java Multidimensional Arrays in Java LinkedList in Java ArrayList in Java PriorityQueue in Java How to iterate any Map in Java Queue Interface In Java Stack Class in Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 23975, "s": 23947, "text": "\n31 Dec, 2018" }, { "code": null, "e": 24100, "s": 23975, "text": "The getRef() function is a part of URL class. The function getRef() returns the Reference or anchor part of a specified URL." }, { "code": null, "e": 24120, "s": 24100, "text": "Function Signature:" }, { "code": null, "e": 24143, "s": 24120, "text": "public String getRef()" }, { "code": null, "e": 24151, "s": 24143, "text": "Syntax:" }, { "code": null, "e": 24164, "s": 24151, "text": "url.getRef()" }, { "code": null, "e": 24220, "s": 24164, "text": "Parameter: This function does not require any parameter" }, { "code": null, "e": 24266, "s": 24220, "text": "Return Type: The function returns String Type" }, { "code": null, "e": 24323, "s": 24266, "text": "Below programs illustrates the use of getRef() function:" }, { "code": null, "e": 24411, "s": 24323, "text": "Example 1: Given a URL we will get the Reference or anchor using the getRef() function." }, { "code": "// Java program to show the// use of the function getRef() import java.net.*; class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url= new URL(\"https:// www.geeksforgeeks.org#Arnab_Kundu\"); // get the Reference or anchor String _Ref=url.getRef(); // display the URL System.out.println(\"URL = \"+url); // display the Reference or anchor System.out.println(\" Reference or anchor=\"+_Ref); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}", "e": 25163, "s": 24411, "text": null }, { "code": null, "e": 25246, "s": 25163, "text": "URL = https:// www.geeksforgeeks.org#Arnab_Kundu\n Reference or anchor=Arnab_Kundu\n" }, { "code": null, "e": 25365, "s": 25246, "text": "Example 2: Now we will not provide any anchor and use the function to get the Reference or anchor and see the results." }, { "code": "// Java program to show the// use of the function getRef() import java.net.*; class Solution { public static void main(String args[]) { // url object URL url = null; try { // create a URL url = new URL(\"https:// www.geeksforgeeks.org\"); // get the Reference or anchor String _Ref = url.getRef(); // display the URL System.out.println(\"URL = \" + url); // display the Reference or anchor System.out.println(\" Reference or anchor= \" + _Ref); } // if any error occurs catch (Exception e) { // display the error System.out.println(e); } }}", "e": 26117, "s": 25365, "text": null }, { "code": null, "e": 26182, "s": 26117, "text": "URL = https:// www.geeksforgeeks.org\n Reference or anchor= null\n" }, { "code": null, "e": 26197, "s": 26182, "text": "Java-Functions" }, { "code": null, "e": 26214, "s": 26197, "text": "Java-net-package" }, { "code": null, "e": 26223, "s": 26214, "text": "Java-URL" }, { "code": null, "e": 26228, "s": 26223, "text": "Java" }, { "code": null, "e": 26233, "s": 26228, "text": "Java" }, { "code": null, "e": 26331, "s": 26233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26340, "s": 26331, "text": "Comments" }, { "code": null, "e": 26353, "s": 26340, "text": "Old Comments" }, { "code": null, "e": 26385, "s": 26353, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26404, "s": 26385, "text": "Overriding in Java" }, { "code": null, "e": 26436, "s": 26404, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26455, "s": 26436, "text": "LinkedList in Java" }, { "code": null, "e": 26473, "s": 26455, "text": "ArrayList in Java" }, { "code": null, "e": 26495, "s": 26473, "text": "PriorityQueue in Java" }, { "code": null, "e": 26526, "s": 26495, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26550, "s": 26526, "text": "Queue Interface In Java" }, { "code": null, "e": 26570, "s": 26550, "text": "Stack Class in Java" } ]
Arduino - Wireless Communication
The wireless transmitter and receiver modules work at 315 Mhz. They can easily fit into a breadboard and work well with microcontrollers to create a very simple wireless data link. With one pair of transmitter and receiver, the modules will only work communicating data one-way, however, you would need two pairs (of different frequencies) to act as a transmitter/receiver pair. Note − These modules are indiscriminate and receive a fair amount of noise. Both the transmitter and receiver work at common frequencies and do not have IDs. Product Model − MX-05V Operating voltage − DC5V Quiescent Current − 4mA Receiving frequency − 315Mhz Receiver sensitivity − -105DB Size − 30 * 14 * 7mm Product Model − MX-FS-03V Launch distance − 20-200 meters (different voltage, different results) Operating voltage − 3.5-12V Dimensions − 19 * 19mm Operating mode − AM Transfer rate − 4KB / S Transmitting power − 10mW Transmitting frequency − 315Mhz An external antenna − 25cm ordinary multi-core or single-core line Pinout from left → right − (DATA; VCC; GND) You will need the following components − 2 × Arduino UNO board 1 × Rf link transmitter 1 × Rf link receiver Follow the circuit diagram and make the connections as shown in the image given below. Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New. Note − You must include the keypad library in your Arduino library file. Copy and paste the VirtualWire.lib file in the libraries folder as highlighted in the screenshot given below. //simple Tx on pin D12 #include <VirtualWire.h> char *controller; void setup() { pinMode(13,OUTPUT); vw_set_ptt_inverted(true); vw_set_tx_pin(12); vw_setup(4000);// speed of data transfer Kbps } void loop() { controller="1" ; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(13,1); delay(2000); controller="0" ; vw_send((uint8_t *)controller, strlen(controller)); vw_wait_tx(); // Wait until the whole message is gone digitalWrite(13,0); delay(2000); } This is a simple code. First, it will send character '1' and after two seconds it will send character '0' and so on. //simple Rx on pin D12 #include <VirtualWire.h> void setup() { vw_set_ptt_inverted(true); // Required for DR3100 vw_set_rx_pin(12); vw_setup(4000); // Bits per sec pinMode(5, OUTPUT); vw_rx_start(); // Start the receiver PLL running } void loop() { uint8_t buf[VW_MAX_MESSAGE_LEN]; uint8_t buflen = VW_MAX_MESSAGE_LEN; if (vw_get_message(buf, &buflen)) // Non-blocking { if(buf[0]=='1') { digitalWrite(5,1); } if(buf[0]=='0') { digitalWrite(5,0); } } } The LED connected to pin number 5 on the Arduino board is turned ON when character '1' is received and turned OFF when character '0' received. 65 Lectures 6.5 hours Amit Rana 43 Lectures 3 hours Amit Rana 20 Lectures 2 hours Ashraf Said 19 Lectures 1.5 hours Ashraf Said 11 Lectures 47 mins Ashraf Said 9 Lectures 41 mins Ashraf Said Print Add Notes Bookmark this page
[ { "code": null, "e": 3249, "s": 2870, "text": "The wireless transmitter and receiver modules work at 315 Mhz. They can easily fit into a breadboard and work well with microcontrollers to create a very simple wireless data link. With one pair of transmitter and receiver, the modules will only work communicating data one-way, however, you would need two pairs (of different frequencies) to act as a transmitter/receiver pair." }, { "code": null, "e": 3407, "s": 3249, "text": "Note − These modules are indiscriminate and receive a fair amount of noise. Both the transmitter and receiver work at common frequencies and do not have IDs." }, { "code": null, "e": 3430, "s": 3407, "text": "Product Model − MX-05V" }, { "code": null, "e": 3455, "s": 3430, "text": "Operating voltage − DC5V" }, { "code": null, "e": 3479, "s": 3455, "text": "Quiescent Current − 4mA" }, { "code": null, "e": 3508, "s": 3479, "text": "Receiving frequency − 315Mhz" }, { "code": null, "e": 3538, "s": 3508, "text": "Receiver sensitivity − -105DB" }, { "code": null, "e": 3559, "s": 3538, "text": "Size − 30 * 14 * 7mm" }, { "code": null, "e": 3585, "s": 3559, "text": "Product Model − MX-FS-03V" }, { "code": null, "e": 3656, "s": 3585, "text": "Launch distance − 20-200 meters (different voltage, different results)" }, { "code": null, "e": 3684, "s": 3656, "text": "Operating voltage − 3.5-12V" }, { "code": null, "e": 3707, "s": 3684, "text": "Dimensions − 19 * 19mm" }, { "code": null, "e": 3727, "s": 3707, "text": "Operating mode − AM" }, { "code": null, "e": 3751, "s": 3727, "text": "Transfer rate − 4KB / S" }, { "code": null, "e": 3777, "s": 3751, "text": "Transmitting power − 10mW" }, { "code": null, "e": 3809, "s": 3777, "text": "Transmitting frequency − 315Mhz" }, { "code": null, "e": 3876, "s": 3809, "text": "An external antenna − 25cm ordinary multi-core or single-core line" }, { "code": null, "e": 3920, "s": 3876, "text": "Pinout from left → right − (DATA; VCC; GND)" }, { "code": null, "e": 3961, "s": 3920, "text": "You will need the following components −" }, { "code": null, "e": 3983, "s": 3961, "text": "2 × Arduino UNO board" }, { "code": null, "e": 4007, "s": 3983, "text": "1 × Rf link transmitter" }, { "code": null, "e": 4028, "s": 4007, "text": "1 × Rf link receiver" }, { "code": null, "e": 4115, "s": 4028, "text": "Follow the circuit diagram and make the connections as shown in the image given below." }, { "code": null, "e": 4261, "s": 4115, "text": "Open the Arduino IDE software on your computer. Coding in the Arduino language will control your circuit. Open a new sketch File by clicking New." }, { "code": null, "e": 4444, "s": 4261, "text": "Note − You must include the keypad library in your Arduino library file. Copy and paste the VirtualWire.lib file in the libraries folder as highlighted in the screenshot given below." }, { "code": null, "e": 5011, "s": 4444, "text": "//simple Tx on pin D12\n#include <VirtualWire.h>\nchar *controller;\n\nvoid setup() {\n pinMode(13,OUTPUT);\n vw_set_ptt_inverted(true);\n vw_set_tx_pin(12);\n vw_setup(4000);// speed of data transfer Kbps\n}\n\nvoid loop() {\n controller=\"1\" ;\n vw_send((uint8_t *)controller, strlen(controller));\n vw_wait_tx(); // Wait until the whole message is gone\n digitalWrite(13,1);\n delay(2000);\n controller=\"0\" ;\n vw_send((uint8_t *)controller, strlen(controller));\n vw_wait_tx(); // Wait until the whole message is gone\n digitalWrite(13,0);\n delay(2000);\n}" }, { "code": null, "e": 5128, "s": 5011, "text": "This is a simple code. First, it will send character '1' and after two seconds it will send character '0' and so on." }, { "code": null, "e": 5652, "s": 5128, "text": "//simple Rx on pin D12\n#include <VirtualWire.h>\n\nvoid setup() {\n vw_set_ptt_inverted(true); // Required for DR3100\n vw_set_rx_pin(12);\n vw_setup(4000); // Bits per sec\n pinMode(5, OUTPUT);\n vw_rx_start(); // Start the receiver PLL running\n}\n\nvoid loop() {\n uint8_t buf[VW_MAX_MESSAGE_LEN];\n uint8_t buflen = VW_MAX_MESSAGE_LEN;\n if (vw_get_message(buf, &buflen)) // Non-blocking {\n if(buf[0]=='1') {\n digitalWrite(5,1);\n }\n if(buf[0]=='0') {\n digitalWrite(5,0);\n }\n }\n}" }, { "code": null, "e": 5795, "s": 5652, "text": "The LED connected to pin number 5 on the Arduino board is turned ON when character '1' is received and turned OFF when character '0' received." }, { "code": null, "e": 5830, "s": 5795, "text": "\n 65 Lectures \n 6.5 hours \n" }, { "code": null, "e": 5841, "s": 5830, "text": " Amit Rana" }, { "code": null, "e": 5874, "s": 5841, "text": "\n 43 Lectures \n 3 hours \n" }, { "code": null, "e": 5885, "s": 5874, "text": " Amit Rana" }, { "code": null, "e": 5918, "s": 5885, "text": "\n 20 Lectures \n 2 hours \n" }, { "code": null, "e": 5931, "s": 5918, "text": " Ashraf Said" }, { "code": null, "e": 5966, "s": 5931, "text": "\n 19 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5979, "s": 5966, "text": " Ashraf Said" }, { "code": null, "e": 6011, "s": 5979, "text": "\n 11 Lectures \n 47 mins\n" }, { "code": null, "e": 6024, "s": 6011, "text": " Ashraf Said" }, { "code": null, "e": 6055, "s": 6024, "text": "\n 9 Lectures \n 41 mins\n" }, { "code": null, "e": 6068, "s": 6055, "text": " Ashraf Said" }, { "code": null, "e": 6075, "s": 6068, "text": " Print" }, { "code": null, "e": 6086, "s": 6075, "text": " Add Notes" } ]
Topological sorting using Javascript DFS
A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge UV from vertex u to vertex v, u comes before v in the ordering. This only makes sense in directed graphs. There are many places where topological sort makes a lot of sense. For example, let's say you're following a recipe, in this, there are some steps that are must for going to the next steps. But some of these can be performed in parallel. In a similar fashion, during college when selecting courses, there are some prerequisites for more advanced courses which themselves may be prerequisites for further courses. For example − /** * CS101 CS102 * / \ / * CS204 CS340 * \ /| \ * CS380 | CS410 * \ | / * CS540 */ In the above graph, consider if you want to take the course on one level, You'll have to first take all courses it is connected to with from the level above it. Following are some possible topological sorts for the above graph − CS101 -> CS204 -> CS102 -> CS340 -> CS410 -> CS380 -> CS540 CS102 -> CS101 -> CS340 -> CS204 -> CS410 -> CS380 -> CS540 Let us implement this in JavaScript. We'll write 2 functions, topological sort, and topologicalSortHelper to help recursively mark and explore the graph. topologicalSortHelper(node, explored, s) { explored.add(node); // Marks this node as visited and goes on to the nodes // that are dependent on this node, the edge is node ----> n this.edges[node].forEach(n => { if (!explored.has(n)) { this.topologicalSortHelper(n, explored, s); } }); // All dependencies are resolved for this node, we can now add // This to the stack. s.push(node); } topologicalSort() { // Create a Stack to keep track of all elements in sorted order let s = new Stack(this.nodes.length); let explored = new Set(); // For every unvisited node in our graph, call the helper. this.nodes.forEach(node => { if (!explored.has(node)) { this.topologicalSortHelper(node, explored, s); } }); while (!s.isEmpty()) { console.log(s.pop()); } } You can test this using − let g = new Graph(); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addNode("E"); g.addNode("F"); g.addNode("G"); g.addDirectedEdge("A", "C"); g.addDirectedEdge("A", "B"); g.addDirectedEdge("A", "D"); g.addDirectedEdge("C", "D"); g.addDirectedEdge("D", "E"); g.addDirectedEdge("E", "F"); g.addDirectedEdge("B", "G"); g.topologicalSort(); The graph we created looks like − /** * A * / | \ * C | B * \ | | * D G * | * E * | * F */ This will give the output − A B G C D E F
[ { "code": null, "e": 1302, "s": 1062, "text": "A topological sort or topological ordering of a directed graph is a linear ordering of its vertices such that for every directed edge UV from vertex u to vertex v, u comes before v in the ordering. This only makes sense in directed graphs." }, { "code": null, "e": 1729, "s": 1302, "text": "There are many places where topological sort makes a lot of sense. For example, let's say you're following a recipe, in this, there are some steps that are must for going to the next steps. But some of these can be performed in parallel. In a similar fashion, during college when selecting courses, there are some prerequisites for more advanced courses which themselves may be prerequisites for further courses. For example −" }, { "code": null, "e": 1903, "s": 1729, "text": " /**\n * CS101 CS102\n * / \\ /\n * CS204 CS340\n * \\ /| \\\n * CS380 | CS410\n * \\ | /\n * CS540\n*/" }, { "code": null, "e": 2132, "s": 1903, "text": "In the above graph, consider if you want to take the course on one level, You'll have to first take all courses it is connected to with from the level above it. Following are some possible topological sorts for the above graph −" }, { "code": null, "e": 2252, "s": 2132, "text": "CS101 -> CS204 -> CS102 -> CS340 -> CS410 -> CS380 -> CS540\nCS102 -> CS101 -> CS340 -> CS204 -> CS410 -> CS380 -> CS540" }, { "code": null, "e": 2407, "s": 2252, "text": "Let us implement this in JavaScript. We'll write 2 functions, topological sort, and topologicalSortHelper to help recursively mark and explore the graph. " }, { "code": null, "e": 3257, "s": 2407, "text": "topologicalSortHelper(node, explored, s) {\n explored.add(node);\n // Marks this node as visited and goes on to the nodes\n // that are dependent on this node, the edge is node ----> n\n this.edges[node].forEach(n => {\n if (!explored.has(n)) {\n this.topologicalSortHelper(n, explored, s);\n }\n });\n // All dependencies are resolved for this node, we can now add\n // This to the stack.\n s.push(node);\n}\n\ntopologicalSort() {\n // Create a Stack to keep track of all elements in sorted order\n let s = new Stack(this.nodes.length);\n let explored = new Set();\n\n // For every unvisited node in our graph, call the helper.\n this.nodes.forEach(node => {\n if (!explored.has(node)) {\n this.topologicalSortHelper(node, explored, s);\n }\n });\n\n while (!s.isEmpty()) {\n console.log(s.pop());\n }\n}" }, { "code": null, "e": 3284, "s": 3257, "text": "You can test this using − " }, { "code": null, "e": 3643, "s": 3284, "text": "let g = new Graph();\ng.addNode(\"A\");\ng.addNode(\"B\");\ng.addNode(\"C\");\ng.addNode(\"D\");\ng.addNode(\"E\");\ng.addNode(\"F\");\ng.addNode(\"G\");\n\ng.addDirectedEdge(\"A\", \"C\");\ng.addDirectedEdge(\"A\", \"B\");\ng.addDirectedEdge(\"A\", \"D\");\ng.addDirectedEdge(\"C\", \"D\");\ng.addDirectedEdge(\"D\", \"E\");\ng.addDirectedEdge(\"E\", \"F\");\ng.addDirectedEdge(\"B\", \"G\");\n\ng.topologicalSort();" }, { "code": null, "e": 3678, "s": 3643, "text": "The graph we created looks like − " }, { "code": null, "e": 3828, "s": 3678, "text": "/**\n * A\n * / | \\\n * C | B\n * \\ | |\n * D G\n * |\n * E\n * |\n * F\n*/" }, { "code": null, "e": 3856, "s": 3828, "text": "This will give the output −" }, { "code": null, "e": 3870, "s": 3856, "text": "A\nB\nG\nC\nD\nE\nF" } ]
Pytest best practices for libraries | Towards Data Science
Disclaimer: You won’t be able to fit everything to the proposed structure, apply common sense and your judgement during the testing developing and design. These days many python libraries are built by ML researchers and practitioners. This is also true at my company, where we maintain several internal libraries and do a new release each sprint. Testing is involved whenever we want to add a new feature, fix an existing bug, or refactor the codebase. During this highly iterative process, we find that having a good testing framework save us a lots of time. As a data scientist who is not from a software engineering background, I want to share some of the testing best practices I have discovered in this post. We currently use pytest for testing all our internal libraries. So let’s start with some basic knowledge of pytest! Before digging into the testing strategies, some basic idea of pytest is needed. Note that this section covers and only covers the range of knowledge required to understand our testing strategies. For more information, please refer to pytest’s official documentation. For each of our internal libraries, we have a separate tests folder dedicated to testing. To use with pytest, the tests folder will have the following structure: tests | — conftest.py | — test_some_name.py | — test_some_other_name.py ... As we can see, there is one conftest.py and several test_*.py files. conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest. The test_*.py files are where the actual test functions reside. Remember, this naming convention is mandatory. Otherwise pytest will not be able to locate the fixtures and test functions. Next we will look at the content of these two types of files to get a better idea of what fixtures are and what test functions look like. To put it simple, conftest.py is a collection of pytest fixtures that are used by test functions across different test_*.py files. Before writing any fixtures, remember to """conftest.py"""import pytest First let’s look at an example of a configuration fixture, a spark configuration fixture. """conftest.py"""@pytest.fixture(scope="session")def spark_session(request): """ fixture for creating a spark context Args: request: pytest.FixtureRequest object """ spark = ( SparkSession .builder .master("local[4]") .appName("testing-something") .getOrCreate() ) request.addfinalizer(lambda: spark.sparkContext.stop()) return spark You should notice three things about this code snippet: pytest fixture is really just a function wrapped by the pytest.fixture decorator, and it returns the spark instance that will be used for testing.It has an optional scope argument, which specifies how long the fixture will persist. It defaults to “function”, so the fixture, spark instance in our case, will be created for each test function. Since it is an expensive operation and the spark instance can be reused by different test functions, we specify the scope to “session”, which means that it will persist for the whole testing session.Our function takes a request argument, which is a pytest built-in fixture. We use it to stop the spark instance after the testing session terminates, which is done by the line before the return statement. If your configuration do not need the teardown step, you can simply remove the request from the function signature. pytest fixture is really just a function wrapped by the pytest.fixture decorator, and it returns the spark instance that will be used for testing. It has an optional scope argument, which specifies how long the fixture will persist. It defaults to “function”, so the fixture, spark instance in our case, will be created for each test function. Since it is an expensive operation and the spark instance can be reused by different test functions, we specify the scope to “session”, which means that it will persist for the whole testing session. Our function takes a request argument, which is a pytest built-in fixture. We use it to stop the spark instance after the testing session terminates, which is done by the line before the return statement. If your configuration do not need the teardown step, you can simply remove the request from the function signature. Next let’s look at the more widely used testcase fixture. Suppose our testcase is a pandas dataframe. """conftest.py"""@pytest.fixturedef text_language_df(): return pd.DataFrame({ "text": ['hello', 'hola', 'bonjour'], "language": ["english", "spanish", "french"] }) And that’s it! It’s as simple as returning the testcase you want to use. Here we omit the scope argument so it’s default to “function”. Next, we will look at the content of the test_*.py files, and hopefully you will see the magic of pytest. Now suppose we want to test our language detection function, which takes in a text string and returns the most possible language it is written in. So in our test_language_detection.py, we will have this code snippet: """test_language_detection.py"""# import the detect_language function heredef test_detect_language(text_language_df): for i in range(len(text_language_df)): assert detect_language(text_language_df.text[i]) == text_language_df.language[i] You should notice two things about this code snippet: The test function’s name starts with “test”. This is required for a test function to be visible to pytest when it is invoked. One trick that makes use of this property is to prepend an underscore to the name of the test function you want to skip for now.text_language_df is the fixture you declared in conftest.py. Without any import or extra overhead, you can use it in any of the test functions in any of the test_*.py files. You can treat it as a normal pandas dataframe. The test function’s name starts with “test”. This is required for a test function to be visible to pytest when it is invoked. One trick that makes use of this property is to prepend an underscore to the name of the test function you want to skip for now. text_language_df is the fixture you declared in conftest.py. Without any import or extra overhead, you can use it in any of the test functions in any of the test_*.py files. You can treat it as a normal pandas dataframe. Now you will understand why we say conftest.py is “a collection of pytest fixtures that are used by test functions across different test_*.py files”. These fixtures are defined once and used everywhere. In fact, pytest also allows you to create pytest fixtures in each test_*.py file. We find it best to put fixtures that are only used by this one test_*.py file there, so that the conftest.py is not overwhelmed by fixtures. pytest is invoked in CLI. The most direct way is to call $ pytest tests/or$ pytest tests/test_language_detection.py tests/test_something.pyor$ pytest tests/test_language_detection.py::test_detect_language tests/test_something.py For more info on specifying tests/selecting tests, please refer to the official documentation. In this section, we will discuss common testing strategies we developed in testing our internal libraries. The core idea behind these strategies is to enable faster iteration. All the tests we have run for our internal libraries can be roughly divided into three categories based on different granularities: unit tests focus on particular methods or functionality which don’t rely on other untested components; integration tests deal with complex flows and interactions that involve several units. They almost always rely on some mocked functionality for faster iteration; end-to-end tests, as opposite to the previous category, don’t take advantage of mocked functionality. They test the whole feature as it is, all the dependencies are present and set up. During our library development, we find two types of workflow that are extremely common, namely testing workflow for new code and testing workflow for bug fixing code. For adding new code, you need to implement three levels of tests if applicable. The code has to pass all three levels of testing. Failing on a higher level restarts the code from the lowest level. For adding code that fixes a bug, we highly recommend adding tests before making changes to the existing code. You should expect the added tests to fail before the bug is fixed, and expect them to pass after the bug is fixed. Through this way, the tests can serve as regression tests which prevent us from accidentally reproducing the same bug again in the future. Another takeaway is that always running and passing all tests before merging in the code. If no CI/CD tools are available, you have to enforce this rule manually. Next we will look at two testing strategies we use for shorter testing waiting time and faster tests update. In the previous section, we show how we can create a testcase fixture in conftest.py and then reuse it in our test functions. The testcase fixture is a pandas dataframe which consists of a list of testcases. One drawback of using dataframes (in fact any collection data structure such as list, tuple, set) is that when one of the testcases in the dataframe fails, the entire test function will be marked as fail. It’s hard to find out which single testcase fails the function. What is more inconvenient, if the test function is computationally expensive, you will not be able to get the testing result for all testcases in one run, if one of the testcases fails. You have to first fix the failed testcase, rerun pytest, and repeat this routine if another fail occurs. Fortunately, pytest provides several ways of parametrizing testcases so that each testcase is treated separately and you can get all their results in one run. This is done with the @pytest.mark.parametrize decorator, which is applied on the test function directly. Let’s see how it works with our language detection testing example. """test_language_detection.py"""@pytest.mark.parametrize( "text,expected", [ ('hello', 'english'), ('hola', 'spanish'), ('bonjour', 'french') ])def test_detect_language(text, expected): assert detect_language(text) == expected It is quite self-explaining. In one run, the test function will be called three times, so that we can get the result for each testcase separately. For more info on parametrizing test functions, please refer to the official documentation. In this case, instead of parametrizing on test functions, we parametrize the fixture function. """conftest.py"""import pytestfrom collections import namedtupleTestCase = namedtuple("TestCase", ["text", "expected"])@pytest.fixture( params=[ TestCase("hello", "english"), TestCase("hola", "spanish"), TestCase("bonjour", "french") ])def test_case(request): return request.param Then in the test function, we can use the parametrized fixture as follows: """test_language_detection.py"""def test_detect_language(test_case): assert detect_language(test_case.text) == test_case.expected You should notice two things about this code snippet: The built-in request fixture is responsible for coordinating the parametrization. It is somewhat counterintuitive at first glance, but you can think of it as simply a “syntax” for parametrizing.The params argument in pytest.fixture takes in a list. Here we define each item in the list as a namedtuple to avoid hard coded indices or strings. Using a namedtuple enables us to refer to the testcase’s input and output as test_case.text and test_case.expected later in the test function. Instead, if you have items having the form of [“hello”, “english”], then you have to refer to them as test_case[0] and test_case[1] in the test function, which is not a good programming practice The built-in request fixture is responsible for coordinating the parametrization. It is somewhat counterintuitive at first glance, but you can think of it as simply a “syntax” for parametrizing. The params argument in pytest.fixture takes in a list. Here we define each item in the list as a namedtuple to avoid hard coded indices or strings. Using a namedtuple enables us to refer to the testcase’s input and output as test_case.text and test_case.expected later in the test function. Instead, if you have items having the form of [“hello”, “english”], then you have to refer to them as test_case[0] and test_case[1] in the test function, which is not a good programming practice For more info on parametrizing fixtures, please refer to the official documentation. Another implicit benefit of parametrizing testcases is that it enables updating existing tests with new testcases easily. We find this extremely useful in the testing workflow for bug fixing code. For example, suppose a user reports to us that the detect_language function incorrectly assigns “nǐ hǎo” to “vietnamese”, which should be “chinese”. Following the testing workflow for bug fixing code, we add the regression tests first. As the testcases are already parametrized, this can be done by simply adding a tuple (“nǐ hǎo”, “chinese”) into the list if we are using @pytest.mark.parametrize, or adding a TestCase(“nǐ hǎo”, “chinese”) if we are parametrizing the fixture function. It would be much harder to achieve the same effect if the testcases are not parametrized. When writing tests for a class from our internal libraries, one common situation we run into is that some abstract methods of the class haven’t been implemented yet. These abstract methods are intended for our end users, namely data scientists, to implement based on their use cases. The absence of the implementation prevents us from instantiating the class and testing it. The workaround we find is to subclass the class, explicitly implement the abstract methods, but leave the method body empty. For example, suppose we want to test a Classifier class, which has three abstract methods: load_dataset, load_model, compute_metrics. As our testing scope is to make sure a Classifier instance functions correctly for general use cases, we don’t want to introduce any specific dataset or model. We create a new class, MockedClassifier, that subclasses Classifier and explicitly implement these abstract methods. """test_classifier.py"""class MockedClassifier(Classifier): def load_dataset(self, *args, **kwargs): pass def load_model(self, *args, **kwargs): pass def compute_metrics(self, *args, **kwargs): pass Then we can use MockedClassifier instead of Classifier to test its functionality. For example, to test its instantiation """test_classifier.py"""def test_instantiation(): trainer = MockedClassifier("init args here") Another situation when mocking is useful is when the class you want to test has some computationally expensive operations that are unrelated to the testing scope. You can subclass it and override the expensive operations with much lighter ones. For example, """test_class_with_expensive_operation.py"""class MockedClass(ClassWithExpensiveOP): def some_expensive_operation(self, *args, **kwargs): # code for lighter operation here In the last section, we will cover some of the advanced pytest techniques we find useful from past experience. Sometimes we may want to pass in some arguments from command line to control the testing behavior. For example, suppose we want to test loading a file from some file path. The file path varies from platform to platform. To make our tests portable, we can pass in a platform argument from the command line and set the file path based on it. To add a command line argument, """conftest.py"""import pytestdef pytest_addoption(parser): parser.addoption( "--platform", action="store", default="platform_0", choices=["platform_0", "platform_1", "platform_2"], help="The name of the platform you are on")@pytest.fixturedef platform(pytestconfig): return pytestconfig.getoption("platform") Now we can call $ pytest tests/ --platform platform_2 And the platform fixture will stores the platform info we type in from the command line. It defaults to “platform_0” if no explicit platform is given. Next we add in the file path fixture, which is determined by the platform we are on. """conftest.py"""@pytest.fixturedef filepath(platform): if platform == "platform_0": return "the file path on platform_0" elif platform == "platform_1": return "the file path on platform_1" elif platform == "platform_2": return "the file path on "platform_2"" Finally, we can test loading with this filepath fixture. """test_file_load.py"""def test_load_file(filepath): with open(filepath, "r") as f: f.read() Some of our library code will write to disk files when running. For example, when testing our experiment tracking library, it will write logs, metrics, etc. to disk files. pytest provides several temporary directories and files fixtures aiming for this use case. They already have a very comprehensive documentation here. When testing some classes, we want to make sure that not only the result is as expected, but also the number of function calls made is as expected. To enable this powerful functionality, we need to install pytest-mock, which is a pytest plugin that provides a mocker fixture. Currently we only make use of its spy utility, a clear documentation with a simple example can be found here. One way of working with fixtures is to put fixtures that are shared among multiple test_*.py files in the conftest.py, leaving the fixtures which are specific to a test module in there. One potential drawback of this approach is that it results in enormously large conftest.py, which is hard to navigate and can lead to merge conflicts even though folks are working on different testing modules. In that sense, when the conftest.py becomes too large that the downside of inefficient navigation and collaboration has outweighed the benefit of centralization, it should be split into multiple fixture files. For example, one fixture file for dataset fixtures, one fixture file for configuration fixtures, and so on. In fact, pytest provides a way to do this without sacrificing the benefit of sharing fixtures among different testing modules. After splitting the conftest.py into several fixture files, you can include them back into conftest.py as plugins. To be more specific, suppose we have a dataset_fixtures.py and a config_fixtures.py that look like this: """dataset_fixtures.py"""import pytest@pytest.fixturedef dataset_fixture_0(): # some code here@pytest.fixturedef dataset_fixture_1(): # some code here"""config_fixtures.py"""import pytest@pytest.fixturedef config_fixture_0(): # some code here@pytest.fixturedef config_fixture_1(): # some code here Then to include them back into conftest.py, only need to add one line """conftest.py"""import pytestpytest_plugins = ["dataset_fixtures", "config_fixtures"]# code for fixtures in conftest.py here And that’s it! These testing practices are quite easy to carry out, yet they prove to be really handy throughout our development cycle. Hope they will help you develop python libraries in a faster and more robust way :)
[ { "code": null, "e": 327, "s": 172, "text": "Disclaimer: You won’t be able to fit everything to the proposed structure, apply common sense and your judgement during the testing developing and design." }, { "code": null, "e": 732, "s": 327, "text": "These days many python libraries are built by ML researchers and practitioners. This is also true at my company, where we maintain several internal libraries and do a new release each sprint. Testing is involved whenever we want to add a new feature, fix an existing bug, or refactor the codebase. During this highly iterative process, we find that having a good testing framework save us a lots of time." }, { "code": null, "e": 886, "s": 732, "text": "As a data scientist who is not from a software engineering background, I want to share some of the testing best practices I have discovered in this post." }, { "code": null, "e": 1002, "s": 886, "text": "We currently use pytest for testing all our internal libraries. So let’s start with some basic knowledge of pytest!" }, { "code": null, "e": 1270, "s": 1002, "text": "Before digging into the testing strategies, some basic idea of pytest is needed. Note that this section covers and only covers the range of knowledge required to understand our testing strategies. For more information, please refer to pytest’s official documentation." }, { "code": null, "e": 1432, "s": 1270, "text": "For each of our internal libraries, we have a separate tests folder dedicated to testing. To use with pytest, the tests folder will have the following structure:" }, { "code": null, "e": 1438, "s": 1432, "text": "tests" }, { "code": null, "e": 1454, "s": 1438, "text": "| — conftest.py" }, { "code": null, "e": 1476, "s": 1454, "text": "| — test_some_name.py" }, { "code": null, "e": 1504, "s": 1476, "text": "| — test_some_other_name.py" }, { "code": null, "e": 1508, "s": 1504, "text": "..." }, { "code": null, "e": 1940, "s": 1508, "text": "As we can see, there is one conftest.py and several test_*.py files. conftest.py is where you setup test configurations and store the testcases that are used by test functions. The configurations and the testcases are called fixture in pytest. The test_*.py files are where the actual test functions reside. Remember, this naming convention is mandatory. Otherwise pytest will not be able to locate the fixtures and test functions." }, { "code": null, "e": 2078, "s": 1940, "text": "Next we will look at the content of these two types of files to get a better idea of what fixtures are and what test functions look like." }, { "code": null, "e": 2250, "s": 2078, "text": "To put it simple, conftest.py is a collection of pytest fixtures that are used by test functions across different test_*.py files. Before writing any fixtures, remember to" }, { "code": null, "e": 2281, "s": 2250, "text": "\"\"\"conftest.py\"\"\"import pytest" }, { "code": null, "e": 2371, "s": 2281, "text": "First let’s look at an example of a configuration fixture, a spark configuration fixture." }, { "code": null, "e": 2764, "s": 2371, "text": "\"\"\"conftest.py\"\"\"@pytest.fixture(scope=\"session\")def spark_session(request): \"\"\" fixture for creating a spark context Args: request: pytest.FixtureRequest object \"\"\" spark = ( SparkSession .builder .master(\"local[4]\") .appName(\"testing-something\") .getOrCreate() ) request.addfinalizer(lambda: spark.sparkContext.stop()) return spark" }, { "code": null, "e": 2820, "s": 2764, "text": "You should notice three things about this code snippet:" }, { "code": null, "e": 3683, "s": 2820, "text": "pytest fixture is really just a function wrapped by the pytest.fixture decorator, and it returns the spark instance that will be used for testing.It has an optional scope argument, which specifies how long the fixture will persist. It defaults to “function”, so the fixture, spark instance in our case, will be created for each test function. Since it is an expensive operation and the spark instance can be reused by different test functions, we specify the scope to “session”, which means that it will persist for the whole testing session.Our function takes a request argument, which is a pytest built-in fixture. We use it to stop the spark instance after the testing session terminates, which is done by the line before the return statement. If your configuration do not need the teardown step, you can simply remove the request from the function signature." }, { "code": null, "e": 3830, "s": 3683, "text": "pytest fixture is really just a function wrapped by the pytest.fixture decorator, and it returns the spark instance that will be used for testing." }, { "code": null, "e": 4227, "s": 3830, "text": "It has an optional scope argument, which specifies how long the fixture will persist. It defaults to “function”, so the fixture, spark instance in our case, will be created for each test function. Since it is an expensive operation and the spark instance can be reused by different test functions, we specify the scope to “session”, which means that it will persist for the whole testing session." }, { "code": null, "e": 4548, "s": 4227, "text": "Our function takes a request argument, which is a pytest built-in fixture. We use it to stop the spark instance after the testing session terminates, which is done by the line before the return statement. If your configuration do not need the teardown step, you can simply remove the request from the function signature." }, { "code": null, "e": 4650, "s": 4548, "text": "Next let’s look at the more widely used testcase fixture. Suppose our testcase is a pandas dataframe." }, { "code": null, "e": 4834, "s": 4650, "text": "\"\"\"conftest.py\"\"\"@pytest.fixturedef text_language_df(): return pd.DataFrame({ \"text\": ['hello', 'hola', 'bonjour'], \"language\": [\"english\", \"spanish\", \"french\"] })" }, { "code": null, "e": 4970, "s": 4834, "text": "And that’s it! It’s as simple as returning the testcase you want to use. Here we omit the scope argument so it’s default to “function”." }, { "code": null, "e": 5076, "s": 4970, "text": "Next, we will look at the content of the test_*.py files, and hopefully you will see the magic of pytest." }, { "code": null, "e": 5223, "s": 5076, "text": "Now suppose we want to test our language detection function, which takes in a text string and returns the most possible language it is written in." }, { "code": null, "e": 5293, "s": 5223, "text": "So in our test_language_detection.py, we will have this code snippet:" }, { "code": null, "e": 5541, "s": 5293, "text": "\"\"\"test_language_detection.py\"\"\"# import the detect_language function heredef test_detect_language(text_language_df): for i in range(len(text_language_df)): assert detect_language(text_language_df.text[i]) == text_language_df.language[i]" }, { "code": null, "e": 5595, "s": 5541, "text": "You should notice two things about this code snippet:" }, { "code": null, "e": 6070, "s": 5595, "text": "The test function’s name starts with “test”. This is required for a test function to be visible to pytest when it is invoked. One trick that makes use of this property is to prepend an underscore to the name of the test function you want to skip for now.text_language_df is the fixture you declared in conftest.py. Without any import or extra overhead, you can use it in any of the test functions in any of the test_*.py files. You can treat it as a normal pandas dataframe." }, { "code": null, "e": 6325, "s": 6070, "text": "The test function’s name starts with “test”. This is required for a test function to be visible to pytest when it is invoked. One trick that makes use of this property is to prepend an underscore to the name of the test function you want to skip for now." }, { "code": null, "e": 6546, "s": 6325, "text": "text_language_df is the fixture you declared in conftest.py. Without any import or extra overhead, you can use it in any of the test functions in any of the test_*.py files. You can treat it as a normal pandas dataframe." }, { "code": null, "e": 6749, "s": 6546, "text": "Now you will understand why we say conftest.py is “a collection of pytest fixtures that are used by test functions across different test_*.py files”. These fixtures are defined once and used everywhere." }, { "code": null, "e": 6972, "s": 6749, "text": "In fact, pytest also allows you to create pytest fixtures in each test_*.py file. We find it best to put fixtures that are only used by this one test_*.py file there, so that the conftest.py is not overwhelmed by fixtures." }, { "code": null, "e": 7029, "s": 6972, "text": "pytest is invoked in CLI. The most direct way is to call" }, { "code": null, "e": 7201, "s": 7029, "text": "$ pytest tests/or$ pytest tests/test_language_detection.py tests/test_something.pyor$ pytest tests/test_language_detection.py::test_detect_language tests/test_something.py" }, { "code": null, "e": 7296, "s": 7201, "text": "For more info on specifying tests/selecting tests, please refer to the official documentation." }, { "code": null, "e": 7472, "s": 7296, "text": "In this section, we will discuss common testing strategies we developed in testing our internal libraries. The core idea behind these strategies is to enable faster iteration." }, { "code": null, "e": 7604, "s": 7472, "text": "All the tests we have run for our internal libraries can be roughly divided into three categories based on different granularities:" }, { "code": null, "e": 7707, "s": 7604, "text": "unit tests focus on particular methods or functionality which don’t rely on other untested components;" }, { "code": null, "e": 7869, "s": 7707, "text": "integration tests deal with complex flows and interactions that involve several units. They almost always rely on some mocked functionality for faster iteration;" }, { "code": null, "e": 8054, "s": 7869, "text": "end-to-end tests, as opposite to the previous category, don’t take advantage of mocked functionality. They test the whole feature as it is, all the dependencies are present and set up." }, { "code": null, "e": 8222, "s": 8054, "text": "During our library development, we find two types of workflow that are extremely common, namely testing workflow for new code and testing workflow for bug fixing code." }, { "code": null, "e": 8419, "s": 8222, "text": "For adding new code, you need to implement three levels of tests if applicable. The code has to pass all three levels of testing. Failing on a higher level restarts the code from the lowest level." }, { "code": null, "e": 8947, "s": 8419, "text": "For adding code that fixes a bug, we highly recommend adding tests before making changes to the existing code. You should expect the added tests to fail before the bug is fixed, and expect them to pass after the bug is fixed. Through this way, the tests can serve as regression tests which prevent us from accidentally reproducing the same bug again in the future. Another takeaway is that always running and passing all tests before merging in the code. If no CI/CD tools are available, you have to enforce this rule manually." }, { "code": null, "e": 9056, "s": 8947, "text": "Next we will look at two testing strategies we use for shorter testing waiting time and faster tests update." }, { "code": null, "e": 9824, "s": 9056, "text": "In the previous section, we show how we can create a testcase fixture in conftest.py and then reuse it in our test functions. The testcase fixture is a pandas dataframe which consists of a list of testcases. One drawback of using dataframes (in fact any collection data structure such as list, tuple, set) is that when one of the testcases in the dataframe fails, the entire test function will be marked as fail. It’s hard to find out which single testcase fails the function. What is more inconvenient, if the test function is computationally expensive, you will not be able to get the testing result for all testcases in one run, if one of the testcases fails. You have to first fix the failed testcase, rerun pytest, and repeat this routine if another fail occurs." }, { "code": null, "e": 9983, "s": 9824, "text": "Fortunately, pytest provides several ways of parametrizing testcases so that each testcase is treated separately and you can get all their results in one run." }, { "code": null, "e": 10157, "s": 9983, "text": "This is done with the @pytest.mark.parametrize decorator, which is applied on the test function directly. Let’s see how it works with our language detection testing example." }, { "code": null, "e": 10417, "s": 10157, "text": "\"\"\"test_language_detection.py\"\"\"@pytest.mark.parametrize( \"text,expected\", [ ('hello', 'english'), ('hola', 'spanish'), ('bonjour', 'french') ])def test_detect_language(text, expected): assert detect_language(text) == expected" }, { "code": null, "e": 10564, "s": 10417, "text": "It is quite self-explaining. In one run, the test function will be called three times, so that we can get the result for each testcase separately." }, { "code": null, "e": 10655, "s": 10564, "text": "For more info on parametrizing test functions, please refer to the official documentation." }, { "code": null, "e": 10750, "s": 10655, "text": "In this case, instead of parametrizing on test functions, we parametrize the fixture function." }, { "code": null, "e": 11061, "s": 10750, "text": "\"\"\"conftest.py\"\"\"import pytestfrom collections import namedtupleTestCase = namedtuple(\"TestCase\", [\"text\", \"expected\"])@pytest.fixture( params=[ TestCase(\"hello\", \"english\"), TestCase(\"hola\", \"spanish\"), TestCase(\"bonjour\", \"french\") ])def test_case(request): return request.param" }, { "code": null, "e": 11136, "s": 11061, "text": "Then in the test function, we can use the parametrized fixture as follows:" }, { "code": null, "e": 11269, "s": 11136, "text": "\"\"\"test_language_detection.py\"\"\"def test_detect_language(test_case): assert detect_language(test_case.text) == test_case.expected" }, { "code": null, "e": 11323, "s": 11269, "text": "You should notice two things about this code snippet:" }, { "code": null, "e": 12003, "s": 11323, "text": "The built-in request fixture is responsible for coordinating the parametrization. It is somewhat counterintuitive at first glance, but you can think of it as simply a “syntax” for parametrizing.The params argument in pytest.fixture takes in a list. Here we define each item in the list as a namedtuple to avoid hard coded indices or strings. Using a namedtuple enables us to refer to the testcase’s input and output as test_case.text and test_case.expected later in the test function. Instead, if you have items having the form of [“hello”, “english”], then you have to refer to them as test_case[0] and test_case[1] in the test function, which is not a good programming practice" }, { "code": null, "e": 12198, "s": 12003, "text": "The built-in request fixture is responsible for coordinating the parametrization. It is somewhat counterintuitive at first glance, but you can think of it as simply a “syntax” for parametrizing." }, { "code": null, "e": 12684, "s": 12198, "text": "The params argument in pytest.fixture takes in a list. Here we define each item in the list as a namedtuple to avoid hard coded indices or strings. Using a namedtuple enables us to refer to the testcase’s input and output as test_case.text and test_case.expected later in the test function. Instead, if you have items having the form of [“hello”, “english”], then you have to refer to them as test_case[0] and test_case[1] in the test function, which is not a good programming practice" }, { "code": null, "e": 12769, "s": 12684, "text": "For more info on parametrizing fixtures, please refer to the official documentation." }, { "code": null, "e": 13549, "s": 12769, "text": "Another implicit benefit of parametrizing testcases is that it enables updating existing tests with new testcases easily. We find this extremely useful in the testing workflow for bug fixing code. For example, suppose a user reports to us that the detect_language function incorrectly assigns “nǐ hǎo” to “vietnamese”, which should be “chinese”. Following the testing workflow for bug fixing code, we add the regression tests first. As the testcases are already parametrized, this can be done by simply adding a tuple (“nǐ hǎo”, “chinese”) into the list if we are using @pytest.mark.parametrize, or adding a TestCase(“nǐ hǎo”, “chinese”) if we are parametrizing the fixture function. It would be much harder to achieve the same effect if the testcases are not parametrized." }, { "code": null, "e": 14049, "s": 13549, "text": "When writing tests for a class from our internal libraries, one common situation we run into is that some abstract methods of the class haven’t been implemented yet. These abstract methods are intended for our end users, namely data scientists, to implement based on their use cases. The absence of the implementation prevents us from instantiating the class and testing it. The workaround we find is to subclass the class, explicitly implement the abstract methods, but leave the method body empty." }, { "code": null, "e": 14460, "s": 14049, "text": "For example, suppose we want to test a Classifier class, which has three abstract methods: load_dataset, load_model, compute_metrics. As our testing scope is to make sure a Classifier instance functions correctly for general use cases, we don’t want to introduce any specific dataset or model. We create a new class, MockedClassifier, that subclasses Classifier and explicitly implement these abstract methods." }, { "code": null, "e": 14689, "s": 14460, "text": "\"\"\"test_classifier.py\"\"\"class MockedClassifier(Classifier): def load_dataset(self, *args, **kwargs): pass def load_model(self, *args, **kwargs): pass def compute_metrics(self, *args, **kwargs): pass" }, { "code": null, "e": 14810, "s": 14689, "text": "Then we can use MockedClassifier instead of Classifier to test its functionality. For example, to test its instantiation" }, { "code": null, "e": 14908, "s": 14810, "text": "\"\"\"test_classifier.py\"\"\"def test_instantiation(): trainer = MockedClassifier(\"init args here\")" }, { "code": null, "e": 15166, "s": 14908, "text": "Another situation when mocking is useful is when the class you want to test has some computationally expensive operations that are unrelated to the testing scope. You can subclass it and override the expensive operations with much lighter ones. For example," }, { "code": null, "e": 15348, "s": 15166, "text": "\"\"\"test_class_with_expensive_operation.py\"\"\"class MockedClass(ClassWithExpensiveOP): def some_expensive_operation(self, *args, **kwargs): # code for lighter operation here" }, { "code": null, "e": 15459, "s": 15348, "text": "In the last section, we will cover some of the advanced pytest techniques we find useful from past experience." }, { "code": null, "e": 15799, "s": 15459, "text": "Sometimes we may want to pass in some arguments from command line to control the testing behavior. For example, suppose we want to test loading a file from some file path. The file path varies from platform to platform. To make our tests portable, we can pass in a platform argument from the command line and set the file path based on it." }, { "code": null, "e": 15831, "s": 15799, "text": "To add a command line argument," }, { "code": null, "e": 16182, "s": 15831, "text": "\"\"\"conftest.py\"\"\"import pytestdef pytest_addoption(parser): parser.addoption( \"--platform\", action=\"store\", default=\"platform_0\", choices=[\"platform_0\", \"platform_1\", \"platform_2\"], help=\"The name of the platform you are on\")@pytest.fixturedef platform(pytestconfig): return pytestconfig.getoption(\"platform\")" }, { "code": null, "e": 16198, "s": 16182, "text": "Now we can call" }, { "code": null, "e": 16236, "s": 16198, "text": "$ pytest tests/ --platform platform_2" }, { "code": null, "e": 16387, "s": 16236, "text": "And the platform fixture will stores the platform info we type in from the command line. It defaults to “platform_0” if no explicit platform is given." }, { "code": null, "e": 16472, "s": 16387, "text": "Next we add in the file path fixture, which is determined by the platform we are on." }, { "code": null, "e": 16762, "s": 16472, "text": "\"\"\"conftest.py\"\"\"@pytest.fixturedef filepath(platform): if platform == \"platform_0\": return \"the file path on platform_0\" elif platform == \"platform_1\": return \"the file path on platform_1\" elif platform == \"platform_2\": return \"the file path on \"platform_2\"\"" }, { "code": null, "e": 16819, "s": 16762, "text": "Finally, we can test loading with this filepath fixture." }, { "code": null, "e": 16922, "s": 16819, "text": "\"\"\"test_file_load.py\"\"\"def test_load_file(filepath): with open(filepath, \"r\") as f: f.read()" }, { "code": null, "e": 17244, "s": 16922, "text": "Some of our library code will write to disk files when running. For example, when testing our experiment tracking library, it will write logs, metrics, etc. to disk files. pytest provides several temporary directories and files fixtures aiming for this use case. They already have a very comprehensive documentation here." }, { "code": null, "e": 17630, "s": 17244, "text": "When testing some classes, we want to make sure that not only the result is as expected, but also the number of function calls made is as expected. To enable this powerful functionality, we need to install pytest-mock, which is a pytest plugin that provides a mocker fixture. Currently we only make use of its spy utility, a clear documentation with a simple example can be found here." }, { "code": null, "e": 18026, "s": 17630, "text": "One way of working with fixtures is to put fixtures that are shared among multiple test_*.py files in the conftest.py, leaving the fixtures which are specific to a test module in there. One potential drawback of this approach is that it results in enormously large conftest.py, which is hard to navigate and can lead to merge conflicts even though folks are working on different testing modules." }, { "code": null, "e": 18344, "s": 18026, "text": "In that sense, when the conftest.py becomes too large that the downside of inefficient navigation and collaboration has outweighed the benefit of centralization, it should be split into multiple fixture files. For example, one fixture file for dataset fixtures, one fixture file for configuration fixtures, and so on." }, { "code": null, "e": 18586, "s": 18344, "text": "In fact, pytest provides a way to do this without sacrificing the benefit of sharing fixtures among different testing modules. After splitting the conftest.py into several fixture files, you can include them back into conftest.py as plugins." }, { "code": null, "e": 18691, "s": 18586, "text": "To be more specific, suppose we have a dataset_fixtures.py and a config_fixtures.py that look like this:" }, { "code": null, "e": 19001, "s": 18691, "text": "\"\"\"dataset_fixtures.py\"\"\"import pytest@pytest.fixturedef dataset_fixture_0(): # some code here@pytest.fixturedef dataset_fixture_1(): # some code here\"\"\"config_fixtures.py\"\"\"import pytest@pytest.fixturedef config_fixture_0(): # some code here@pytest.fixturedef config_fixture_1(): # some code here" }, { "code": null, "e": 19071, "s": 19001, "text": "Then to include them back into conftest.py, only need to add one line" }, { "code": null, "e": 19197, "s": 19071, "text": "\"\"\"conftest.py\"\"\"import pytestpytest_plugins = [\"dataset_fixtures\", \"config_fixtures\"]# code for fixtures in conftest.py here" } ]
SQLite - CREATE Table
SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column's data type. Following is the basic syntax of CREATE TABLE statement. CREATE TABLE database_name.table_name( column1 datatype PRIMARY KEY(one or more columns), column2 datatype, column3 datatype, ..... columnN datatype ); CREATE TABLE is the keyword telling the database system to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Optionally, you can specify database_name along with table_name. Following is an example which creates a COMPANY table with ID as the primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table. sqlite> CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); Let us create one more table, which we will use in our exercises in subsequent chapters. sqlite> CREATE TABLE DEPARTMENT( ID INT PRIMARY KEY NOT NULL, DEPT CHAR(50) NOT NULL, EMP_ID INT NOT NULL ); You can verify if your table has been created successfully using SQLite command .tables command, which will be used to list down all the tables in an attached database. sqlite>.tables COMPANY DEPARTMENT Here, you can see the COMPANY table twice because its showing COMPANY table for main database and test.COMPANY table for 'test' alias created for your testDB.db. You can get complete information about a table using the following SQLite .schema command. sqlite>.schema COMPANY CREATE TABLE COMPANY( ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT NOT NULL, ADDRESS CHAR(50), SALARY REAL ); 25 Lectures 4.5 hours Sandip Bhattacharya 17 Lectures 1 hours Laurence Svekis 5 Lectures 51 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 2831, "s": 2638, "text": "SQLite CREATE TABLE statement is used to create a new table in any of the given database. Creating a basic table involves naming the table and defining its columns and each column's data type." }, { "code": null, "e": 2888, "s": 2831, "text": "Following is the basic syntax of CREATE TABLE statement." }, { "code": null, "e": 3056, "s": 2888, "text": "CREATE TABLE database_name.table_name(\n column1 datatype PRIMARY KEY(one or more columns),\n column2 datatype,\n column3 datatype,\n .....\n columnN datatype\n);\n" }, { "code": null, "e": 3281, "s": 3056, "text": "CREATE TABLE is the keyword telling the database system to create a new table. The unique name or identifier for the table follows the CREATE TABLE statement. Optionally, you can specify database_name along with table_name." }, { "code": null, "e": 3474, "s": 3281, "text": "Following is an example which creates a COMPANY table with ID as the primary key and NOT NULL are the constraints showing that these fields cannot be NULL while creating records in this table." }, { "code": null, "e": 3666, "s": 3474, "text": "sqlite> CREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 3755, "s": 3666, "text": "Let us create one more table, which we will use in our exercises in subsequent chapters." }, { "code": null, "e": 3901, "s": 3755, "text": "sqlite> CREATE TABLE DEPARTMENT(\n ID INT PRIMARY KEY NOT NULL,\n DEPT CHAR(50) NOT NULL,\n EMP_ID INT NOT NULL\n);" }, { "code": null, "e": 4070, "s": 3901, "text": "You can verify if your table has been created successfully using SQLite command .tables command, which will be used to list down all the tables in an attached database." }, { "code": null, "e": 4108, "s": 4070, "text": "sqlite>.tables\nCOMPANY DEPARTMENT" }, { "code": null, "e": 4361, "s": 4108, "text": "Here, you can see the COMPANY table twice because its showing COMPANY table for main database and test.COMPANY table for 'test' alias created for your testDB.db. You can get complete information about a table using the following SQLite .schema command." }, { "code": null, "e": 4568, "s": 4361, "text": "sqlite>.schema COMPANY\nCREATE TABLE COMPANY(\n ID INT PRIMARY KEY NOT NULL,\n NAME TEXT NOT NULL,\n AGE INT NOT NULL,\n ADDRESS CHAR(50),\n SALARY REAL\n);" }, { "code": null, "e": 4603, "s": 4568, "text": "\n 25 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4624, "s": 4603, "text": " Sandip Bhattacharya" }, { "code": null, "e": 4657, "s": 4624, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 4674, "s": 4657, "text": " Laurence Svekis" }, { "code": null, "e": 4705, "s": 4674, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 4718, "s": 4705, "text": " Vinay Kumar" }, { "code": null, "e": 4725, "s": 4718, "text": " Print" }, { "code": null, "e": 4736, "s": 4725, "text": " Add Notes" } ]
Python Input, Output and Import. In this tutorial let us understand the... | by Tanu N Prabhu | Towards Data Science
In this tutorial let us understand the Input and Output built-in-functions used in python, also we will learn how to import libraries and use them in our programs. Before getting started let us understand what are built-in-functions? Any function that is provided as part of a high-level language and can be executed by a simple reference with or without the specification of arguments — Credits: Yourdictionary There are many built-in-functions available in python. It is highly impossible to remember the name and the syntax of every built-in-functions. So below is the documentation of all the built-in-function available in python available in alphabetical order provided by the python.org — I call it as the cheat sheet of built-in-function, have a look below: docs.python.org Theinput()and the print() built-in-functions are one of the most commonly used functions for performing standard input and output operations. There is no output() function in python, rather print() is used to perform the standard output operations. You can also find the documentation of this tutorial on my GitHub Repository below: github.com The print function in python is normally used to print the output on the screen. As the name suggests “print” meaning to print something “where?” on the screen. Now you don’t have to write the entire body (contents) of the print function every time, personally I don’t even know how the body of the print function looks like. All you have to do is just call the function by passing the parameters. Whatever you write inside the print function are called parameters. Let us see how to print something onto the screen. variable = "Welcome to Python Tutorials"print(variable)Welcome to Python Tutorials Like I said the variable is the parameter that is passed along with the print function, you don't need to write the body of the print function you just need to call the print function. The actual syntax of the print function is given below: print(value, ..., sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream. Even you can try this just call help(print) and the help function will provide you the help you need (Duh ;)) Now let us see how to pass more than one parameter inside the print function and what would be the result? variable = "Welcome to Python Tutorials"variable2 = ",This is a good place to learn programming"print(variable, variable2)Welcome to Python Tutorials ,This is a good place to learn programming You can pass as many parameters inside the print function but make sure that you separate the variable from one another. Let us use a “sep” (separator) inside a print function and see the output. print(1, 2, 3, 4, 5, sep="--->")1--->2--->3--->4--->5 The “end” parameter is used to append a character to the end of the string which we pass inside the print function. print(1, 2, 3, 4, 5, end=" This is the end")1 2 3 4 5 This is the end There might be some situations wherein formatting the output is required, in that case, we can use the str.format() method. variable = "Python"variable2 = "Programming"print("I love {0} and {1}".format(variable,variable2))I love Python and Programming Further, the format() method can do a great job such as adding the comma separator to the string of integers as shown below: print(format(1234567, ",d"))1,234,567 Similarly, we can format the output using the “%” operator as shown below: number = 12.3456print("The value of x is %1.2f" %number)The value of x is 12.35print("The value of x is %1.5f" %number)The value of x is 12.34560 In the past, we used to hard code the value of the variable inside our main program. But sometimes we need to take the input from the users. This can be achieved by using the Input function. The Input function as the name suggests taking the user's input. The syntax of the input function is: input(prompt = ‘ ’) Here the prompt is the one that would be displayed on the screen. number = input("Enter the number of your choice: ")print("The number that you have entered is: %s" %number)Enter the number of your choice: 100 The number that you have entered is: 100 Here, the prompt is “Enter the number of your choice”, here you might wonder why did I use “%s” when I entered an integer as an input. It is because all the variables are stored as string in Python, to explicitly typecast it use can use either int(variable_name), or float(variable_name) and many more. Go try it and let me know. Sometimes, we need to import some libraries from a different module (a module is a python file that comprises definitions and statements). In those cases, we can import those methods or modules by using the import keyword along with the name of the module. Consider an example, think you want to see what is the value of “pi”, all you can do is rather than doing (22/7, or memorizing 3.1423... I don't know further), just import the math module and call the math method and then your job is done. import mathprint(math.pi)3.141592653589793 Also using the from keyword we can access specific attributes from the module. For example: from math import piprint(pi)3.141592653589793 It's more like “From this module import this function, method or attribute”. This is the end of the “Python Input, Output and Import” tutorial. Hope you enjoyed it. If you have any comments or suggestions let me know in the comment section below. Until then Goodbye !!!.
[ { "code": null, "e": 336, "s": 172, "text": "In this tutorial let us understand the Input and Output built-in-functions used in python, also we will learn how to import libraries and use them in our programs." }, { "code": null, "e": 406, "s": 336, "text": "Before getting started let us understand what are built-in-functions?" }, { "code": null, "e": 584, "s": 406, "text": "Any function that is provided as part of a high-level language and can be executed by a simple reference with or without the specification of arguments — Credits: Yourdictionary" }, { "code": null, "e": 938, "s": 584, "text": "There are many built-in-functions available in python. It is highly impossible to remember the name and the syntax of every built-in-functions. So below is the documentation of all the built-in-function available in python available in alphabetical order provided by the python.org — I call it as the cheat sheet of built-in-function, have a look below:" }, { "code": null, "e": 954, "s": 938, "text": "docs.python.org" }, { "code": null, "e": 1287, "s": 954, "text": "Theinput()and the print() built-in-functions are one of the most commonly used functions for performing standard input and output operations. There is no output() function in python, rather print() is used to perform the standard output operations. You can also find the documentation of this tutorial on my GitHub Repository below:" }, { "code": null, "e": 1298, "s": 1287, "text": "github.com" }, { "code": null, "e": 1815, "s": 1298, "text": "The print function in python is normally used to print the output on the screen. As the name suggests “print” meaning to print something “where?” on the screen. Now you don’t have to write the entire body (contents) of the print function every time, personally I don’t even know how the body of the print function looks like. All you have to do is just call the function by passing the parameters. Whatever you write inside the print function are called parameters. Let us see how to print something onto the screen." }, { "code": null, "e": 1898, "s": 1815, "text": "variable = \"Welcome to Python Tutorials\"print(variable)Welcome to Python Tutorials" }, { "code": null, "e": 2139, "s": 1898, "text": "Like I said the variable is the parameter that is passed along with the print function, you don't need to write the body of the print function you just need to call the print function. The actual syntax of the print function is given below:" }, { "code": null, "e": 2549, "s": 2139, "text": "print(value, ..., sep=’ ‘, end=’\\n’, file=sys.stdout, flush=False)Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. flush: whether to forcibly flush the stream." }, { "code": null, "e": 2659, "s": 2549, "text": "Even you can try this just call help(print) and the help function will provide you the help you need (Duh ;))" }, { "code": null, "e": 2766, "s": 2659, "text": "Now let us see how to pass more than one parameter inside the print function and what would be the result?" }, { "code": null, "e": 2959, "s": 2766, "text": "variable = \"Welcome to Python Tutorials\"variable2 = \",This is a good place to learn programming\"print(variable, variable2)Welcome to Python Tutorials ,This is a good place to learn programming" }, { "code": null, "e": 3080, "s": 2959, "text": "You can pass as many parameters inside the print function but make sure that you separate the variable from one another." }, { "code": null, "e": 3155, "s": 3080, "text": "Let us use a “sep” (separator) inside a print function and see the output." }, { "code": null, "e": 3209, "s": 3155, "text": "print(1, 2, 3, 4, 5, sep=\"--->\")1--->2--->3--->4--->5" }, { "code": null, "e": 3325, "s": 3209, "text": "The “end” parameter is used to append a character to the end of the string which we pass inside the print function." }, { "code": null, "e": 3395, "s": 3325, "text": "print(1, 2, 3, 4, 5, end=\" This is the end\")1 2 3 4 5 This is the end" }, { "code": null, "e": 3519, "s": 3395, "text": "There might be some situations wherein formatting the output is required, in that case, we can use the str.format() method." }, { "code": null, "e": 3647, "s": 3519, "text": "variable = \"Python\"variable2 = \"Programming\"print(\"I love {0} and {1}\".format(variable,variable2))I love Python and Programming" }, { "code": null, "e": 3772, "s": 3647, "text": "Further, the format() method can do a great job such as adding the comma separator to the string of integers as shown below:" }, { "code": null, "e": 3810, "s": 3772, "text": "print(format(1234567, \",d\"))1,234,567" }, { "code": null, "e": 3885, "s": 3810, "text": "Similarly, we can format the output using the “%” operator as shown below:" }, { "code": null, "e": 4031, "s": 3885, "text": "number = 12.3456print(\"The value of x is %1.2f\" %number)The value of x is 12.35print(\"The value of x is %1.5f\" %number)The value of x is 12.34560" }, { "code": null, "e": 4222, "s": 4031, "text": "In the past, we used to hard code the value of the variable inside our main program. But sometimes we need to take the input from the users. This can be achieved by using the Input function." }, { "code": null, "e": 4324, "s": 4222, "text": "The Input function as the name suggests taking the user's input. The syntax of the input function is:" }, { "code": null, "e": 4344, "s": 4324, "text": "input(prompt = ‘ ’)" }, { "code": null, "e": 4410, "s": 4344, "text": "Here the prompt is the one that would be displayed on the screen." }, { "code": null, "e": 4595, "s": 4410, "text": "number = input(\"Enter the number of your choice: \")print(\"The number that you have entered is: %s\" %number)Enter the number of your choice: 100 The number that you have entered is: 100" }, { "code": null, "e": 4925, "s": 4595, "text": "Here, the prompt is “Enter the number of your choice”, here you might wonder why did I use “%s” when I entered an integer as an input. It is because all the variables are stored as string in Python, to explicitly typecast it use can use either int(variable_name), or float(variable_name) and many more. Go try it and let me know." }, { "code": null, "e": 5182, "s": 4925, "text": "Sometimes, we need to import some libraries from a different module (a module is a python file that comprises definitions and statements). In those cases, we can import those methods or modules by using the import keyword along with the name of the module." }, { "code": null, "e": 5422, "s": 5182, "text": "Consider an example, think you want to see what is the value of “pi”, all you can do is rather than doing (22/7, or memorizing 3.1423... I don't know further), just import the math module and call the math method and then your job is done." }, { "code": null, "e": 5465, "s": 5422, "text": "import mathprint(math.pi)3.141592653589793" }, { "code": null, "e": 5557, "s": 5465, "text": "Also using the from keyword we can access specific attributes from the module. For example:" }, { "code": null, "e": 5603, "s": 5557, "text": "from math import piprint(pi)3.141592653589793" }, { "code": null, "e": 5680, "s": 5603, "text": "It's more like “From this module import this function, method or attribute”." } ]
GATE | GATE-CS-2000 | Question 35 - GeeksforGeeks
19 Nov, 2018 The following arrangement of master-slave flip flops has the initial state of P, Q as 0, 1 (respectively). After three clock cycles the output state P, Q is (re­spectively), (A) 1, 0(B) 1, 1(C) 0, 0(D) 0,1Answer: (A)Explanation: Given P = 0 , J = 1 and k = 1 JK flipflop toggles the input in ‘11’ state. Therefore, output of first flipflop at P is ‘1’. Initial value of P is input for D flipflop. So, D = 0 .Therefore, output of second flipflop at Q is ‘0’.Thus, option (A) is the answer.Please comment below if you find anything wrong in the above post. Thus, option (A) is the answer. Please comment below if you find anything wrong in the above post. Quiz of this Question GATE-CS-2000 GATE-GATE-CS-2000 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2014-(Set-1) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2015 (Set 1) | Question 42
[ { "code": null, "e": 24081, "s": 24053, "text": "\n19 Nov, 2018" }, { "code": null, "e": 24255, "s": 24081, "text": "The following arrangement of master-slave flip flops has the initial state of P, Q as 0, 1 (respectively). After three clock cycles the output state P, Q is (re­spectively)," }, { "code": null, "e": 24341, "s": 24255, "text": "(A) 1, 0(B) 1, 1(C) 0, 0(D) 0,1Answer: (A)Explanation: Given P = 0 , J = 1 and k = 1" }, { "code": null, "e": 24435, "s": 24341, "text": "JK flipflop toggles the input in ‘11’ state. Therefore, output of first flipflop at P is ‘1’." }, { "code": null, "e": 24637, "s": 24435, "text": "Initial value of P is input for D flipflop. So, D = 0 .Therefore, output of second flipflop at Q is ‘0’.Thus, option (A) is the answer.Please comment below if you find anything wrong in the above post." }, { "code": null, "e": 24669, "s": 24637, "text": "Thus, option (A) is the answer." }, { "code": null, "e": 24736, "s": 24669, "text": "Please comment below if you find anything wrong in the above post." }, { "code": null, "e": 24758, "s": 24736, "text": "Quiz of this Question" }, { "code": null, "e": 24771, "s": 24758, "text": "GATE-CS-2000" }, { "code": null, "e": 24789, "s": 24771, "text": "GATE-GATE-CS-2000" }, { "code": null, "e": 24794, "s": 24789, "text": "GATE" }, { "code": null, "e": 24892, "s": 24794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24901, "s": 24892, "text": "Comments" }, { "code": null, "e": 24914, "s": 24901, "text": "Old Comments" }, { "code": null, "e": 24956, "s": 24914, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 24998, "s": 24956, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25032, "s": 24998, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25074, "s": 25032, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25108, "s": 25074, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25150, "s": 25108, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25204, "s": 25150, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25246, "s": 25204, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25279, "s": 25246, "text": "GATE | GATE-CS-2004 | Question 3" } ]
How can a simple bivariate distribution be shown using ‘imshow’ in Matplotlib Python?
Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations. It helps in communicating the quantitative insights to the audience effectively. Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on. It is written in Python. It is created using Numpy, which is the Numerical Python package in Python. Python can be installed on Windows using the below command − pip install matplotlib The dependencies of Matplotlib are − Python ( greater than or equal to version 3.4) NumPy Setuptools Pyparsing Libpng Pytz Free type Six Cycler Dateutil Bivariate distribution is the probability that a certain event would occur when two independent random variables are present. The ‘imshow’ function is generally used to display images as well as plots in Matplotlib. Let us understand how Matplotlib can be used to plot a bivariate distribution − import numpy as np import matplotlib.cm as cm import matplotlib.pyplot as plt import matplotlib.cbook as cbook from matplotlib.path import Path from matplotlib.patches import PathPatch np.random.seed(9654241) delta = 0.025 x = y = np.arange(−4.5, 4.5, delta) X, Y = np.meshgrid(x, y) Z1 = np.exp(−X**2 − Y**2) Z2 = np.exp(−(X − 1)**2 − (Y − 1)**2) Z = (Z1 − Z2) * 2 fig, ax = plt.subplots() plt.title('A bivariate distribution') plt.xlabel('x−axis') plt.ylabel('y−axis') im = ax.imshow(Z, interpolation='bilinear', origin='lower', extent=[−3, 3, −3, 3], vmax=abs(Z).max(), vmin=−abs(Z).max()) plt.show() The required packages are imported and its alias is defined for ease of use. The required packages are imported and its alias is defined for ease of use. The data is created using the ‘random’ library’s ‘seed’ function. The data is created using the ‘random’ library’s ‘seed’ function. The data is created using the ‘Numpy’ library for two different data sets. The data is created using the ‘Numpy’ library for two different data sets. An empty figure is created using the ‘figure’ function. An empty figure is created using the ‘figure’ function. The ‘subplot’ function is used to create 2 separate plots within the same plot. The ‘subplot’ function is used to create 2 separate plots within the same plot. The data is plotted using the ‘plot’ function. The data is plotted using the ‘plot’ function. The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title. The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title. The figure is assigned to a variable using ‘imshow’ function. The figure is assigned to a variable using ‘imshow’ function. It is shown on the console using the ‘show’ function. It is shown on the console using the ‘show’ function.
[ { "code": null, "e": 1305, "s": 1062, "text": "Matplotlib is a popular Python package that is used for data visualization. Visualizing data is a key step since it helps understand what is going on in the data without actually looking at the numbers and performing complicated computations." }, { "code": null, "e": 1629, "s": 1305, "text": "It helps in communicating the quantitative insights to the audience effectively. Matplotlib is used to create 2 dimensional plots with the data. It comes with an object oriented API that helps in embedding the plots in Python applications. Matplotlib can be used with IPython shells, Jupyter notebook, Spyder IDE and so on." }, { "code": null, "e": 1730, "s": 1629, "text": "It is written in Python. It is created using Numpy, which is the Numerical Python package in Python." }, { "code": null, "e": 1791, "s": 1730, "text": "Python can be installed on Windows using the below command −" }, { "code": null, "e": 1814, "s": 1791, "text": "pip install matplotlib" }, { "code": null, "e": 1851, "s": 1814, "text": "The dependencies of Matplotlib are −" }, { "code": null, "e": 1967, "s": 1851, "text": "Python ( greater than or equal to version 3.4)\nNumPy\nSetuptools\nPyparsing\nLibpng\nPytz\nFree type\nSix\nCycler\nDateutil" }, { "code": null, "e": 2093, "s": 1967, "text": "Bivariate distribution is the probability that a certain event would occur when two independent random variables are present." }, { "code": null, "e": 2183, "s": 2093, "text": "The ‘imshow’ function is generally used to display images as well as plots in Matplotlib." }, { "code": null, "e": 2263, "s": 2183, "text": "Let us understand how Matplotlib can be used to plot a bivariate distribution −" }, { "code": null, "e": 2870, "s": 2263, "text": "import numpy as np\nimport matplotlib.cm as cm\nimport matplotlib.pyplot as plt\nimport matplotlib.cbook as cbook\nfrom matplotlib.path import Path\nfrom matplotlib.patches import PathPatch\nnp.random.seed(9654241)\n\ndelta = 0.025\nx = y = np.arange(−4.5, 4.5, delta)\nX, Y = np.meshgrid(x, y)\nZ1 = np.exp(−X**2 − Y**2)\nZ2 = np.exp(−(X − 1)**2 − (Y − 1)**2)\nZ = (Z1 − Z2) * 2\n\nfig, ax = plt.subplots()\nplt.title('A bivariate distribution')\nplt.xlabel('x−axis')\nplt.ylabel('y−axis')\n\nim = ax.imshow(Z, interpolation='bilinear',\norigin='lower', extent=[−3, 3, −3, 3],\nvmax=abs(Z).max(), vmin=−abs(Z).max())\nplt.show()" }, { "code": null, "e": 2947, "s": 2870, "text": "The required packages are imported and its alias is defined for ease of use." }, { "code": null, "e": 3024, "s": 2947, "text": "The required packages are imported and its alias is defined for ease of use." }, { "code": null, "e": 3090, "s": 3024, "text": "The data is created using the ‘random’ library’s ‘seed’ function." }, { "code": null, "e": 3156, "s": 3090, "text": "The data is created using the ‘random’ library’s ‘seed’ function." }, { "code": null, "e": 3231, "s": 3156, "text": "The data is created using the ‘Numpy’ library for two different data sets." }, { "code": null, "e": 3306, "s": 3231, "text": "The data is created using the ‘Numpy’ library for two different data sets." }, { "code": null, "e": 3362, "s": 3306, "text": "An empty figure is created using the ‘figure’ function." }, { "code": null, "e": 3418, "s": 3362, "text": "An empty figure is created using the ‘figure’ function." }, { "code": null, "e": 3498, "s": 3418, "text": "The ‘subplot’ function is used to create 2 separate plots within the same plot." }, { "code": null, "e": 3578, "s": 3498, "text": "The ‘subplot’ function is used to create 2 separate plots within the same plot." }, { "code": null, "e": 3625, "s": 3578, "text": "The data is plotted using the ‘plot’ function." }, { "code": null, "e": 3672, "s": 3625, "text": "The data is plotted using the ‘plot’ function." }, { "code": null, "e": 3784, "s": 3672, "text": "The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title." }, { "code": null, "e": 3896, "s": 3784, "text": "The set_xlabel, set_ylabel and set_title functions are used to provide labels for ‘X’ axis, ‘Y’ axis and title." }, { "code": null, "e": 3958, "s": 3896, "text": "The figure is assigned to a variable using ‘imshow’ function." }, { "code": null, "e": 4020, "s": 3958, "text": "The figure is assigned to a variable using ‘imshow’ function." }, { "code": null, "e": 4074, "s": 4020, "text": "It is shown on the console using the ‘show’ function." }, { "code": null, "e": 4128, "s": 4074, "text": "It is shown on the console using the ‘show’ function." } ]
Select Odd and Even Rows and Columns from DataFrame in R - GeeksforGeeks
23 Sep, 2021 In this article, we will discuss how to select odd and even rows from a dataframe in R programming language. The number of rows in a data frame in R can be fetched by the nrow() method. It returns the number of rows in the data frame. The seq_len() method is then applied to generate the integers beginning with 1 to the number of rows. The modulo method with the integer 2 in R can be used to fetch the odd or even rows based on their indexes on the obtained vector. The corresponding row indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame. Syntax: seq_len(rows)%%2 Data frame indexing method can then be used to obtain rows where the odd row index is equivalent to 1. Syntax: data_frame[odd_row == 1, ] Example: Select odd rows from dataframe R # creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print ("Original Dataframe")print(data_frame) # getting number of rows in Rrows <- nrow(data_frame) # extracting odd rows odd_rows <- seq_len(rows) %% 2 # getting data from odd data framedata_mod <- data_frame[odd_rows == 1, ] print ("odd rows of dataframe")print(data_mod) Output: [1] "Original Dataframe" col1 col2 col3 1 1 a 5 2 2 b 6 3 3 c 7 4 4 d 8 5 5 e 9 6 6 f 5 7 7 g 6 8 8 h 7 9 9 i 8 10 10 j 9 [1] "odd rows of dataframe" col1 col2 col3 1 1 a 5 3 3 c 7 5 5 e 9 7 7 g 6 9 9 i 8 The number of rows in a data frame in R can be fetched by the nrow() method. It returns the number of rows in the data frame. The seq_len() method is then applied to generate the integers beginning with 1 to the number of rows. The modulo method with the integer 2 in R can be used to fetch the odd or even rows based on their indexes on the obtained vector. The corresponding row indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame. Syntax: seq_len(rows)%%2 Data frame indexing method can then be used to obtain rows where the even row index is equivalent to 0. Syntax: data_frame[odd_row == 0, ] Example: Select even rows from dataframe R # creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print ("Original Dataframe")print(data_frame) # getting number of rows in Rrows <- nrow(data_frame) # extracting odd rows even_rows <- seq_len(rows) %% 2 # getting data from odd data framedata_mod <- data_frame[even_rows == 0, ] print ("even rows of dataframe")print(data_mod) Output: [1] "Original Dataframe" col1 col2 col3 1 1 a 5 2 2 b 6 3 3 c 7 4 4 d 8 5 5 e 9 6 6 f 5 7 7 g 6 8 8 h 7 9 9 i 8 10 10 j 9 [1] "even rows of dataframe" > print(data_mod) col1 col2 col3 2 2 b 6 4 4 d 8 6 6 f 5 8 8 h 7 10 10 j 9 The number of columns in a data frame in R can be fetched by the ncol() method. It returns the number of columns in the data frame. The modulo method can then be used with the integer 2 in R can be used to fetch the odd or even columns based on their indexes on the obtained vector. The corresponding column indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame. Syntax: seq_len(cols)%%2 Data frame indexing method can then be used to obtain rows where the odd column index is equivalent to 1. Syntax: Data_frame[, odd_cols==1 ] Example: select odd columns from dataframe R # creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print ("Original Dataframe")print(data_frame) # getting number of columns in Rcols <- ncol(data_frame) # extracting odd rows odd_cols <- seq_len(cols) %% 2 # getting data from odd data framedata_mod <- data_frame[, odd_cols == 1] print ("odd columns of dataframe")print(data_mod) Output: [1] "Original Dataframe" col1 col2 col3 1 1 a 5 2 2 b 6 3 3 c 7 4 4 d 8 5 5 e 9 6 6 f 5 7 7 g 6 8 8 h 7 9 9 i 8 10 10 j 9 [1] "odd rows of dataframe" col1 col3 1 1 5 2 2 6 3 3 7 4 4 8 5 5 9 6 6 5 7 7 6 8 8 7 9 9 8 10 10 9 The number of columns in a data frame in R can be fetched by the ncol() method. It returns the number of columns in the data frame. The modulo method can then be used with the integer 2 in R can be used to fetch the odd or even columns based on their indexes on the obtained vector. The corresponding column indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame. Syntax: seq_len(cols)%%2 Data frame indexing method can then be used to obtain rows where the odd column index is equivalent to 0. Syntax: Data_frame[, odd_cols==0 ] Example: select even columns from dataframe R # creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print ("Original Dataframe")print(data_frame) # getting number of columns in Rcols <- ncol(data_frame) # extracting odd rows even_cols <- seq_len(cols) %% 2 # getting data from odd data framedata_mod <- data_frame[, even_cols == 0] print ("even columns of dataframe")print(data_mod) Output: [1] "Original Dataframe" col1 col2 col3 1 1 a 5 2 2 b 6 3 3 c 7 4 4 d 8 5 5 e 9 6 6 f 5 7 7 g 6 8 8 h 7 9 9 i 8 10 10 j 9 [1] "even columns of dataframe" [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n23 Sep, 2021" }, { "code": null, "e": 26596, "s": 26487, "text": "In this article, we will discuss how to select odd and even rows from a dataframe in R programming language." }, { "code": null, "e": 27108, "s": 26596, "text": "The number of rows in a data frame in R can be fetched by the nrow() method. It returns the number of rows in the data frame. The seq_len() method is then applied to generate the integers beginning with 1 to the number of rows. The modulo method with the integer 2 in R can be used to fetch the odd or even rows based on their indexes on the obtained vector. The corresponding row indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame." }, { "code": null, "e": 27116, "s": 27108, "text": "Syntax:" }, { "code": null, "e": 27133, "s": 27116, "text": "seq_len(rows)%%2" }, { "code": null, "e": 27236, "s": 27133, "text": "Data frame indexing method can then be used to obtain rows where the odd row index is equivalent to 1." }, { "code": null, "e": 27244, "s": 27236, "text": "Syntax:" }, { "code": null, "e": 27271, "s": 27244, "text": "data_frame[odd_row == 1, ]" }, { "code": null, "e": 27311, "s": 27271, "text": "Example: Select odd rows from dataframe" }, { "code": null, "e": 27313, "s": 27311, "text": "R" }, { "code": "# creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print (\"Original Dataframe\")print(data_frame) # getting number of rows in Rrows <- nrow(data_frame) # extracting odd rows odd_rows <- seq_len(rows) %% 2 # getting data from odd data framedata_mod <- data_frame[odd_rows == 1, ] print (\"odd rows of dataframe\")print(data_mod)", "e": 27747, "s": 27313, "text": null }, { "code": null, "e": 27755, "s": 27747, "text": "Output:" }, { "code": null, "e": 28108, "s": 27755, "text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 5\n2 2 b 6\n3 3 c 7\n4 4 d 8\n5 5 e 9\n6 6 f 5\n7 7 g 6\n8 8 h 7\n9 9 i 8\n10 10 j 9\n[1] \"odd rows of dataframe\"\n col1 col2 col3\n1 1 a 5\n3 3 c 7\n5 5 e 9\n7 7 g 6\n9 9 i 8" }, { "code": null, "e": 28620, "s": 28108, "text": "The number of rows in a data frame in R can be fetched by the nrow() method. It returns the number of rows in the data frame. The seq_len() method is then applied to generate the integers beginning with 1 to the number of rows. The modulo method with the integer 2 in R can be used to fetch the odd or even rows based on their indexes on the obtained vector. The corresponding row indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame." }, { "code": null, "e": 28628, "s": 28620, "text": "Syntax:" }, { "code": null, "e": 28645, "s": 28628, "text": "seq_len(rows)%%2" }, { "code": null, "e": 28749, "s": 28645, "text": "Data frame indexing method can then be used to obtain rows where the even row index is equivalent to 0." }, { "code": null, "e": 28757, "s": 28749, "text": "Syntax:" }, { "code": null, "e": 28784, "s": 28757, "text": "data_frame[odd_row == 0, ]" }, { "code": null, "e": 28825, "s": 28784, "text": "Example: Select even rows from dataframe" }, { "code": null, "e": 28827, "s": 28825, "text": "R" }, { "code": "# creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print (\"Original Dataframe\")print(data_frame) # getting number of rows in Rrows <- nrow(data_frame) # extracting odd rows even_rows <- seq_len(rows) %% 2 # getting data from odd data framedata_mod <- data_frame[even_rows == 0, ] print (\"even rows of dataframe\")print(data_mod)", "e": 29264, "s": 28827, "text": null }, { "code": null, "e": 29272, "s": 29264, "text": "Output:" }, { "code": null, "e": 29650, "s": 29272, "text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 5\n2 2 b 6\n3 3 c 7\n4 4 d 8\n5 5 e 9\n6 6 f 5\n7 7 g 6\n8 8 h 7\n9 9 i 8\n10 10 j 9\n[1] \"even rows of dataframe\"\n> print(data_mod)\n col1 col2 col3\n2 2 b 6\n4 4 d 8\n6 6 f 5\n8 8 h 7\n10 10 j 9" }, { "code": null, "e": 30089, "s": 29650, "text": "The number of columns in a data frame in R can be fetched by the ncol() method. It returns the number of columns in the data frame. The modulo method can then be used with the integer 2 in R can be used to fetch the odd or even columns based on their indexes on the obtained vector. The corresponding column indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame." }, { "code": null, "e": 30097, "s": 30089, "text": "Syntax:" }, { "code": null, "e": 30114, "s": 30097, "text": "seq_len(cols)%%2" }, { "code": null, "e": 30220, "s": 30114, "text": "Data frame indexing method can then be used to obtain rows where the odd column index is equivalent to 1." }, { "code": null, "e": 30228, "s": 30220, "text": "Syntax:" }, { "code": null, "e": 30255, "s": 30228, "text": "Data_frame[, odd_cols==1 ]" }, { "code": null, "e": 30298, "s": 30255, "text": "Example: select odd columns from dataframe" }, { "code": null, "e": 30300, "s": 30298, "text": "R" }, { "code": "# creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print (\"Original Dataframe\")print(data_frame) # getting number of columns in Rcols <- ncol(data_frame) # extracting odd rows odd_cols <- seq_len(cols) %% 2 # getting data from odd data framedata_mod <- data_frame[, odd_cols == 1] print (\"odd columns of dataframe\")print(data_mod)", "e": 30740, "s": 30300, "text": null }, { "code": null, "e": 30748, "s": 30740, "text": "Output:" }, { "code": null, "e": 31142, "s": 30748, "text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 5\n2 2 b 6\n3 3 c 7\n4 4 d 8\n5 5 e 9\n6 6 f 5\n7 7 g 6\n8 8 h 7\n9 9 i 8\n10 10 j 9\n[1] \"odd rows of dataframe\"\n col1 col3\n1 1 5\n2 2 6\n3 3 7\n4 4 8\n5 5 9\n6 6 5\n7 7 6\n8 8 7\n9 9 8\n10 10 9" }, { "code": null, "e": 31581, "s": 31142, "text": "The number of columns in a data frame in R can be fetched by the ncol() method. It returns the number of columns in the data frame. The modulo method can then be used with the integer 2 in R can be used to fetch the odd or even columns based on their indexes on the obtained vector. The corresponding column indices of the data frame are operated with a modulo method. The following syntax is used to fetch the odd rows of the data frame." }, { "code": null, "e": 31589, "s": 31581, "text": "Syntax:" }, { "code": null, "e": 31606, "s": 31589, "text": "seq_len(cols)%%2" }, { "code": null, "e": 31712, "s": 31606, "text": "Data frame indexing method can then be used to obtain rows where the odd column index is equivalent to 0." }, { "code": null, "e": 31720, "s": 31712, "text": "Syntax:" }, { "code": null, "e": 31747, "s": 31720, "text": "Data_frame[, odd_cols==0 ]" }, { "code": null, "e": 31791, "s": 31747, "text": "Example: select even columns from dataframe" }, { "code": null, "e": 31793, "s": 31791, "text": "R" }, { "code": "# creating a data frame in Rdata_frame <- data.frame(col1 = 1:10, col2 = letters[1:10], col3 = rep(5:9,2)) print (\"Original Dataframe\")print(data_frame) # getting number of columns in Rcols <- ncol(data_frame) # extracting odd rows even_cols <- seq_len(cols) %% 2 # getting data from odd data framedata_mod <- data_frame[, even_cols == 0] print (\"even columns of dataframe\")print(data_mod)", "e": 32236, "s": 31793, "text": null }, { "code": null, "e": 32244, "s": 32236, "text": "Output:" }, { "code": null, "e": 32544, "s": 32244, "text": "[1] \"Original Dataframe\"\n col1 col2 col3\n1 1 a 5\n2 2 b 6\n3 3 c 7\n4 4 d 8\n5 5 e 9\n6 6 f 5\n7 7 g 6\n8 8 h 7\n9 9 i 8\n10 10 j 9\n[1] \"even columns of dataframe\"\n [1] \"a\" \"b\" \"c\" \"d\" \"e\" \"f\" \"g\" \"h\" \"i\" \"j\"" }, { "code": null, "e": 32551, "s": 32544, "text": "Picked" }, { "code": null, "e": 32572, "s": 32551, "text": "R DataFrame-Programs" }, { "code": null, "e": 32584, "s": 32572, "text": "R-DataFrame" }, { "code": null, "e": 32595, "s": 32584, "text": "R Language" }, { "code": null, "e": 32606, "s": 32595, "text": "R Programs" }, { "code": null, "e": 32704, "s": 32606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32756, "s": 32704, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 32791, "s": 32756, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 32829, "s": 32791, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 32887, "s": 32829, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 32930, "s": 32887, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 32988, "s": 32930, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 33031, "s": 32988, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 33080, "s": 33031, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 33130, "s": 33080, "text": "How to filter R dataframe by multiple conditions?" } ]
Change Color of ggplot2 Boxplot in R - GeeksforGeeks
12 Dec, 2021 In this article, we are going to see how to change the color of boxplots using ggplot2 in R Programming Language. We have considered the built-in data frame “ChickWeight”. It contains information about the feed type and growth rate of chickens for six different types of foods like casein, soybean, etc. It has two vectors feed which will be in the x-axis and weight which will be in the y-axis. Same outlines Here we will use the color keyword. Outliers are observations that are located outside the whiskers of a box plot. We will keep the default black color for them. Use the command outlier.color to add color to the outliers in the plot. Since we need the same color in the outlines, we will write the command inside the geom_boxplot( ). Example: R # Same outline colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight))+ geom_boxplot(color="red",outlier.color="black") ch Output: Different outlines Since the color is variable here, we will write the command color inside aes( ) of ggplot assigned to the x-axis value. The outliers will have the same black color, so write the command inside the geom_boxplot( ) only. Example: R # Different outline colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,color=feed))+ geom_boxplot(outlier.color="black") ch Output: Same fill Here, we will use the keyword fill. Since we need the same color in the fill of boxplots, we will write the command inside the geom_boxplot( ). By default, fill for outliers is black. Example: R # Same fill colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight))+ geom_boxplot(fill="violet") ch Output: Different fill Since the color of fill is variable here, we will write the command fill inside aes( ) of ggplot assigned to the x-axis value. Example: R # Different fill colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,fill=feed))+ geom_boxplot() ch Output: 1) For outlines In this we use the following functions : scale_color_manual( ) : Custom colors available. You can either enter the color code using “#XXXXXX” or simply write the color name. Syntax: scale_color_manual( values) scale_color_brewer( ) : Tons of color palettes are available in the RColorBrewer package. Syntax: scale_color_brewer(palette) scale_color_grey( ) : It is used to add gray scale. Example: R library(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,color=feed))+ geom_boxplot(outlier.colour = "black") # Assign custom colorch+scale_color_manual(values=c("#999999", "purple", "#33FFFF", "red", "green", "brown"))# Assign brewer colorch+scale_color_brewer(palette="Dark2") # Assign gray scalech+scale_color_grey() + theme_classic() Output: 2) For filling Similarly, we can fill the box plot. The functions used for this are: scale_fill_manual( ) Custom colors available. You can either enter the color code using “#XXXXXX” or simply write the color name. Syntax: scale_fill_manual( values) scale_fill_brewer( ) : Tons of color palettes are available in the RColorBrewer package. Syntax: scale_fill_brewer(palette) scale_fill_grey( ) : It is used to add gray scale. Example: R library(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,fill=feed))+ geom_boxplot() ch # Assign custom colorch+scale_fill_manual(values=c("#999999", "purple", "#33FFFF", "red", "green", "brown")) # Assign brewer colorch+scale_fill_brewer(palette="Dark2") # Assign gray scalech+scale_fill_grey() + theme_classic() Output: sooda367 Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R How to filter R dataframe by multiple conditions?
[ { "code": null, "e": 26513, "s": 26485, "text": "\n12 Dec, 2021" }, { "code": null, "e": 26628, "s": 26513, "text": "In this article, we are going to see how to change the color of boxplots using ggplot2 in R Programming Language. " }, { "code": null, "e": 26911, "s": 26628, "text": "We have considered the built-in data frame “ChickWeight”. It contains information about the feed type and growth rate of chickens for six different types of foods like casein, soybean, etc. It has two vectors feed which will be in the x-axis and weight which will be in the y-axis." }, { "code": null, "e": 26925, "s": 26911, "text": "Same outlines" }, { "code": null, "e": 27259, "s": 26925, "text": "Here we will use the color keyword. Outliers are observations that are located outside the whiskers of a box plot. We will keep the default black color for them. Use the command outlier.color to add color to the outliers in the plot. Since we need the same color in the outlines, we will write the command inside the geom_boxplot( )." }, { "code": null, "e": 27268, "s": 27259, "text": "Example:" }, { "code": null, "e": 27270, "s": 27268, "text": "R" }, { "code": "# Same outline colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight))+ geom_boxplot(color=\"red\",outlier.color=\"black\") ch", "e": 27408, "s": 27270, "text": null }, { "code": null, "e": 27416, "s": 27408, "text": "Output:" }, { "code": null, "e": 27435, "s": 27416, "text": "Different outlines" }, { "code": null, "e": 27654, "s": 27435, "text": "Since the color is variable here, we will write the command color inside aes( ) of ggplot assigned to the x-axis value. The outliers will have the same black color, so write the command inside the geom_boxplot( ) only." }, { "code": null, "e": 27663, "s": 27654, "text": "Example:" }, { "code": null, "e": 27665, "s": 27663, "text": "R" }, { "code": "# Different outline colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,color=feed))+ geom_boxplot(outlier.color=\"black\") ch", "e": 27807, "s": 27665, "text": null }, { "code": null, "e": 27816, "s": 27807, "text": "Output: " }, { "code": null, "e": 27826, "s": 27816, "text": "Same fill" }, { "code": null, "e": 28010, "s": 27826, "text": "Here, we will use the keyword fill. Since we need the same color in the fill of boxplots, we will write the command inside the geom_boxplot( ). By default, fill for outliers is black." }, { "code": null, "e": 28019, "s": 28010, "text": "Example:" }, { "code": null, "e": 28021, "s": 28019, "text": "R" }, { "code": "# Same fill colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight))+ geom_boxplot(fill=\"violet\") ch", "e": 28136, "s": 28021, "text": null }, { "code": null, "e": 28145, "s": 28136, "text": "Output: " }, { "code": null, "e": 28160, "s": 28145, "text": "Different fill" }, { "code": null, "e": 28287, "s": 28160, "text": "Since the color of fill is variable here, we will write the command fill inside aes( ) of ggplot assigned to the x-axis value." }, { "code": null, "e": 28296, "s": 28287, "text": "Example:" }, { "code": null, "e": 28298, "s": 28296, "text": "R" }, { "code": "# Different fill colorlibrary(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,fill=feed))+ geom_boxplot() ch", "e": 28415, "s": 28298, "text": null }, { "code": null, "e": 28424, "s": 28415, "text": "Output: " }, { "code": null, "e": 28440, "s": 28424, "text": "1) For outlines" }, { "code": null, "e": 28481, "s": 28440, "text": "In this we use the following functions :" }, { "code": null, "e": 28614, "s": 28481, "text": "scale_color_manual( ) : Custom colors available. You can either enter the color code using “#XXXXXX” or simply write the color name." }, { "code": null, "e": 28622, "s": 28614, "text": "Syntax:" }, { "code": null, "e": 28650, "s": 28622, "text": "scale_color_manual( values)" }, { "code": null, "e": 28740, "s": 28650, "text": "scale_color_brewer( ) : Tons of color palettes are available in the RColorBrewer package." }, { "code": null, "e": 28748, "s": 28740, "text": "Syntax:" }, { "code": null, "e": 28776, "s": 28748, "text": "scale_color_brewer(palette)" }, { "code": null, "e": 28828, "s": 28776, "text": "scale_color_grey( ) : It is used to add gray scale." }, { "code": null, "e": 28837, "s": 28828, "text": "Example:" }, { "code": null, "e": 28839, "s": 28837, "text": "R" }, { "code": "library(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,color=feed))+ geom_boxplot(outlier.colour = \"black\") # Assign custom colorch+scale_color_manual(values=c(\"#999999\", \"purple\", \"#33FFFF\", \"red\", \"green\", \"brown\"))# Assign brewer colorch+scale_color_brewer(palette=\"Dark2\") # Assign gray scalech+scale_color_grey() + theme_classic()", "e": 29334, "s": 28839, "text": null }, { "code": null, "e": 29342, "s": 29334, "text": "Output:" }, { "code": null, "e": 29357, "s": 29342, "text": "2) For filling" }, { "code": null, "e": 29427, "s": 29357, "text": "Similarly, we can fill the box plot. The functions used for this are:" }, { "code": null, "e": 29557, "s": 29427, "text": "scale_fill_manual( ) Custom colors available. You can either enter the color code using “#XXXXXX” or simply write the color name." }, { "code": null, "e": 29565, "s": 29557, "text": "Syntax:" }, { "code": null, "e": 29592, "s": 29565, "text": "scale_fill_manual( values)" }, { "code": null, "e": 29681, "s": 29592, "text": "scale_fill_brewer( ) : Tons of color palettes are available in the RColorBrewer package." }, { "code": null, "e": 29689, "s": 29681, "text": "Syntax:" }, { "code": null, "e": 29716, "s": 29689, "text": "scale_fill_brewer(palette)" }, { "code": null, "e": 29767, "s": 29716, "text": "scale_fill_grey( ) : It is used to add gray scale." }, { "code": null, "e": 29776, "s": 29767, "text": "Example:" }, { "code": null, "e": 29778, "s": 29776, "text": "R" }, { "code": "library(ggplot2) ch <- ggplot(chickwts,aes(x=feed,y=weight,fill=feed))+ geom_boxplot() ch # Assign custom colorch+scale_fill_manual(values=c(\"#999999\", \"purple\", \"#33FFFF\", \"red\", \"green\", \"brown\")) # Assign brewer colorch+scale_fill_brewer(palette=\"Dark2\") # Assign gray scalech+scale_fill_grey() + theme_classic()", "e": 30249, "s": 29778, "text": null }, { "code": null, "e": 30257, "s": 30249, "text": "Output:" }, { "code": null, "e": 30266, "s": 30257, "text": "sooda367" }, { "code": null, "e": 30273, "s": 30266, "text": "Picked" }, { "code": null, "e": 30282, "s": 30273, "text": "R-ggplot" }, { "code": null, "e": 30293, "s": 30282, "text": "R Language" }, { "code": null, "e": 30391, "s": 30293, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30443, "s": 30391, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30478, "s": 30443, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30516, "s": 30478, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30574, "s": 30516, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30617, "s": 30574, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30666, "s": 30617, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30703, "s": 30666, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30720, "s": 30703, "text": "R - if statement" }, { "code": null, "e": 30746, "s": 30720, "text": "Time Series Analysis in R" } ]
Scala String compareTo() method with example - GeeksforGeeks
03 Oct, 2019 The compareTo() method is utilized to compare a string with another string.Some points to remember: Here, If a string(S1) is same as string(S2) in comparison then this method returns zero. If S1 is less than S2 then a negative number is returned which is the difference of character value. If S1 is greater than S2 then a positive number is returned. Method Definition: int compareTo(String another String)Return Type: It returns an integer. Example #1: // Scala program of compareTo()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = "Nidhi" // Applying compareTo() method val result = m1.compareTo("Nidhi") // Displays output println(result) }} 0 It returns zero as both the strings are same.Example #2: // Scala program of compareTo()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = "Nidhi" // Applying compareTo() method val result = m1.compareTo("Nidh") // Displays output println(result) }} 1 It returns a positive number as S1 is greater than S2 here.Example #3: // Scala program of compareTo()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = "Nidhi" // Applying compareTo() method val result = m1.compareTo("nidh") // Displays output println(result) }} -32 It returns a negative number as S1 is less than S2 here. Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Inheritance in Scala Scala Lists Scala Tutorial – Learn Scala with Step By Step Guide Operators in Scala Scala Constructors Scala | Arrays Scala String substring() method with example Lambda Expression in Scala
[ { "code": null, "e": 25231, "s": 25203, "text": "\n03 Oct, 2019" }, { "code": null, "e": 25331, "s": 25231, "text": "The compareTo() method is utilized to compare a string with another string.Some points to remember:" }, { "code": null, "e": 25420, "s": 25331, "text": "Here, If a string(S1) is same as string(S2) in comparison then this method returns zero." }, { "code": null, "e": 25521, "s": 25420, "text": "If S1 is less than S2 then a negative number is returned which is the difference of character value." }, { "code": null, "e": 25582, "s": 25521, "text": "If S1 is greater than S2 then a positive number is returned." }, { "code": null, "e": 25673, "s": 25582, "text": "Method Definition: int compareTo(String another String)Return Type: It returns an integer." }, { "code": null, "e": 25685, "s": 25673, "text": "Example #1:" }, { "code": "// Scala program of compareTo()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = \"Nidhi\" // Applying compareTo() method val result = m1.compareTo(\"Nidhi\") // Displays output println(result) }} ", "e": 26029, "s": 25685, "text": null }, { "code": null, "e": 26032, "s": 26029, "text": "0\n" }, { "code": null, "e": 26089, "s": 26032, "text": "It returns zero as both the strings are same.Example #2:" }, { "code": "// Scala program of compareTo()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = \"Nidhi\" // Applying compareTo() method val result = m1.compareTo(\"Nidh\") // Displays output println(result) }} ", "e": 26432, "s": 26089, "text": null }, { "code": null, "e": 26435, "s": 26432, "text": "1\n" }, { "code": null, "e": 26506, "s": 26435, "text": "It returns a positive number as S1 is greater than S2 here.Example #3:" }, { "code": "// Scala program of compareTo()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1 = \"Nidhi\" // Applying compareTo() method val result = m1.compareTo(\"nidh\") // Displays output println(result) }} ", "e": 26849, "s": 26506, "text": null }, { "code": null, "e": 26854, "s": 26849, "text": "-32\n" }, { "code": null, "e": 26911, "s": 26854, "text": "It returns a negative number as S1 is less than S2 here." }, { "code": null, "e": 26917, "s": 26911, "text": "Scala" }, { "code": null, "e": 26930, "s": 26917, "text": "Scala-Method" }, { "code": null, "e": 26944, "s": 26930, "text": "Scala-Strings" }, { "code": null, "e": 26950, "s": 26944, "text": "Scala" }, { "code": null, "e": 27048, "s": 26950, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27070, "s": 27048, "text": "Type Casting in Scala" }, { "code": null, "e": 27096, "s": 27070, "text": "Class and Object in Scala" }, { "code": null, "e": 27117, "s": 27096, "text": "Inheritance in Scala" }, { "code": null, "e": 27129, "s": 27117, "text": "Scala Lists" }, { "code": null, "e": 27182, "s": 27129, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 27201, "s": 27182, "text": "Operators in Scala" }, { "code": null, "e": 27220, "s": 27201, "text": "Scala Constructors" }, { "code": null, "e": 27235, "s": 27220, "text": "Scala | Arrays" }, { "code": null, "e": 27280, "s": 27235, "text": "Scala String substring() method with example" } ]
Introduction to Social Networks using NetworkX in Python - GeeksforGeeks
21 Aug, 2021 Prerequisite – Python Basics Ever wondered how the most popular social networking site Facebook works? How we are connected with friends using just Facebook? So, Facebook and other social networking sites work on a methodology called social networks. Social networking is used in mostly all social media sites such as Facebook, Instagram, and LinkedIn, etc. It has a significant effect on marketers to engage customers. Social networks use graphs for creating a network. Their nodes are people and edges are their connection between each other. Two nodes with edges connected are friends. Now let’s see an example for understanding what is social networks. The network of 50 students in a class The network of 50 people The most important python library used in social networking is Networkx. NetworkX is a graph package that is used to create and modify different types of graphs. It provides a rapid development environment for collaborative, multidisciplinary projects. pip install networkx After starting python, we have to import networkx module: import networkx as nx Graph: This type of graph stores nodes and edges and edges are un-directed. It can have self-loops but cannot have parallel edges. Di-Graph: This type of graph is the base class for directed graphs. It can have nodes and edges and edges are directed in nature. It can have self-loops but parallel edges are not allowed in Di-Graph. Multi-Graph: This type of graph is an undirected graph class that can store multi or parallel edges. It can have self-loops as well. Multi-edges are multiple edges between 2 nodes. Multi-DiGraph: This type of graph is a directed graph class that can store multi edges. It can have self-loops as well. Multi-edges are multiple edges between 2 nodes. Python3 # import networkx libraryimport networkx as nx # create an empty undirected graphG = nx.Graph() # adding edge in graph GG.add_edge(1, 2)G.add_edge(2, 3, weight=0.9) Drawing can be done using Matplotlib.pyplot library. Python3 # import matplotlib.pyplot libraryimport matplotlib.pyplot as plt # import networkx libraryimport networkx as nx # create a cubical empty graphG = nx.cubical_graph() # plotting the graphplt.subplot(122) # draw a graph with red# node and value edge colornx.draw(G, pos = nx.circular_layout(G), node_color = 'r', edge_color = 'b') Output: Circular Graph To remove an edge from the graph, use the remove_edge() method of graph object. Syntax: G.remove_edge(u, v) Parameters: u: first node v: second node Return: None Graph Node Removal: To remove a node from the graph, use the remove_node() method of graph object. Syntax: G.remove_node(u) Parameter: Node to remove Return: None Python3 # import networkx libraryimport netwokx as nx # create an empty undirected graphG = nx.Graph() # add edge to the graphG.add_edge('1', '2')G.add_edge('2', '3') # print the adjacent verticesprint(G.adj) Output: {'1': {'2': {}}, '2': {'1': {}, '3': {}}, '3': {'2': {}}} varshagumber28 python-modules python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26341, "s": 26313, "text": "\n21 Aug, 2021" }, { "code": null, "e": 26371, "s": 26341, "text": "Prerequisite – Python Basics " }, { "code": null, "e": 27000, "s": 26371, "text": "Ever wondered how the most popular social networking site Facebook works? How we are connected with friends using just Facebook? So, Facebook and other social networking sites work on a methodology called social networks. Social networking is used in mostly all social media sites such as Facebook, Instagram, and LinkedIn, etc. It has a significant effect on marketers to engage customers. Social networks use graphs for creating a network. Their nodes are people and edges are their connection between each other. Two nodes with edges connected are friends. Now let’s see an example for understanding what is social networks. " }, { "code": null, "e": 27039, "s": 27000, "text": "The network of 50 students in a class " }, { "code": null, "e": 27064, "s": 27039, "text": "The network of 50 people" }, { "code": null, "e": 27137, "s": 27064, "text": "The most important python library used in social networking is Networkx." }, { "code": null, "e": 27317, "s": 27137, "text": "NetworkX is a graph package that is used to create and modify different types of graphs. It provides a rapid development environment for collaborative, multidisciplinary projects." }, { "code": null, "e": 27338, "s": 27317, "text": "pip install networkx" }, { "code": null, "e": 27396, "s": 27338, "text": "After starting python, we have to import networkx module:" }, { "code": null, "e": 27418, "s": 27396, "text": "import networkx as nx" }, { "code": null, "e": 27549, "s": 27418, "text": "Graph: This type of graph stores nodes and edges and edges are un-directed. It can have self-loops but cannot have parallel edges." }, { "code": null, "e": 27750, "s": 27549, "text": "Di-Graph: This type of graph is the base class for directed graphs. It can have nodes and edges and edges are directed in nature. It can have self-loops but parallel edges are not allowed in Di-Graph." }, { "code": null, "e": 27931, "s": 27750, "text": "Multi-Graph: This type of graph is an undirected graph class that can store multi or parallel edges. It can have self-loops as well. Multi-edges are multiple edges between 2 nodes." }, { "code": null, "e": 28099, "s": 27931, "text": "Multi-DiGraph: This type of graph is a directed graph class that can store multi edges. It can have self-loops as well. Multi-edges are multiple edges between 2 nodes." }, { "code": null, "e": 28107, "s": 28099, "text": "Python3" }, { "code": "# import networkx libraryimport networkx as nx # create an empty undirected graphG = nx.Graph() # adding edge in graph GG.add_edge(1, 2)G.add_edge(2, 3, weight=0.9)", "e": 28272, "s": 28107, "text": null }, { "code": null, "e": 28327, "s": 28272, "text": "Drawing can be done using Matplotlib.pyplot library. " }, { "code": null, "e": 28335, "s": 28327, "text": "Python3" }, { "code": "# import matplotlib.pyplot libraryimport matplotlib.pyplot as plt # import networkx libraryimport networkx as nx # create a cubical empty graphG = nx.cubical_graph() # plotting the graphplt.subplot(122) # draw a graph with red# node and value edge colornx.draw(G, pos = nx.circular_layout(G), node_color = 'r', edge_color = 'b')", "e": 28678, "s": 28335, "text": null }, { "code": null, "e": 28687, "s": 28678, "text": "Output: " }, { "code": null, "e": 28702, "s": 28687, "text": "Circular Graph" }, { "code": null, "e": 28783, "s": 28702, "text": "To remove an edge from the graph, use the remove_edge() method of graph object. " }, { "code": null, "e": 28812, "s": 28783, "text": " Syntax: G.remove_edge(u, v)" }, { "code": null, "e": 28827, "s": 28812, "text": " Parameters: " }, { "code": null, "e": 28841, "s": 28827, "text": "u: first node" }, { "code": null, "e": 28856, "s": 28841, "text": "v: second node" }, { "code": null, "e": 28869, "s": 28856, "text": "Return: None" }, { "code": null, "e": 28889, "s": 28869, "text": "Graph Node Removal:" }, { "code": null, "e": 28968, "s": 28889, "text": "To remove a node from the graph, use the remove_node() method of graph object." }, { "code": null, "e": 28993, "s": 28968, "text": "Syntax: G.remove_node(u)" }, { "code": null, "e": 29019, "s": 28993, "text": "Parameter: Node to remove" }, { "code": null, "e": 29032, "s": 29019, "text": "Return: None" }, { "code": null, "e": 29040, "s": 29032, "text": "Python3" }, { "code": "# import networkx libraryimport netwokx as nx # create an empty undirected graphG = nx.Graph() # add edge to the graphG.add_edge('1', '2')G.add_edge('2', '3') # print the adjacent verticesprint(G.adj)", "e": 29241, "s": 29040, "text": null }, { "code": null, "e": 29250, "s": 29241, "text": "Output: " }, { "code": null, "e": 29308, "s": 29250, "text": "{'1': {'2': {}}, '2': {'1': {}, '3': {}}, '3': {'2': {}}}" }, { "code": null, "e": 29325, "s": 29310, "text": "varshagumber28" }, { "code": null, "e": 29340, "s": 29325, "text": "python-modules" }, { "code": null, "e": 29355, "s": 29340, "text": "python-utility" }, { "code": null, "e": 29362, "s": 29355, "text": "Python" }, { "code": null, "e": 29460, "s": 29362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29478, "s": 29460, "text": "Python Dictionary" }, { "code": null, "e": 29513, "s": 29478, "text": "Read a file line by line in Python" }, { "code": null, "e": 29545, "s": 29513, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29567, "s": 29545, "text": "Enumerate() in Python" }, { "code": null, "e": 29609, "s": 29567, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29639, "s": 29609, "text": "Iterate over a list in Python" }, { "code": null, "e": 29665, "s": 29639, "text": "Python String | replace()" }, { "code": null, "e": 29694, "s": 29665, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29738, "s": 29694, "text": "Reading and Writing to text files in Python" } ]
How to change radio button state programmatically in jQuery ? - GeeksforGeeks
25 Jul, 2021 In this article, we will change the selected option of the radio button using jQuery. To select the value of the radio button we can set the “checked” to set to the desired option. For setting the property, we can use the prop() method in jQuery. Syntax: $(selector).prop("checked", true); Note: Selector, is the desired radio option element to be selected. Example: Let us create a radio button group to select a favorite cricket player. We have created a radio option. By default, “Sachin” will be selected. When we click the button, the “Dhoni” option will be selected as given in the program. HTML <!DOCTYPE html><html> <head> <meta charset="utf-8" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script> </head> <body> <fieldset> <legend>Who is Your Favorite Cricketer?</legend> <input type="radio" name="favorite" value="Dhoni" />Dhoni<br /> <input type="radio" name="favorite" value="Shewag" />Shewag<br /> <input type="radio" name="favorite" checked value="Sachin" />Sachin<br /> <br /> <button id="selectID">Select option</button> </fieldset> <script> $("#selectID").on("click", function () { selectRadio(); }); function selectRadio() { let radioOption = jQuery("input:radio[value=Dhoni]"); // This will select the radio button radioOption.prop("checked", true); } </script> </body></html> Output: change radio state Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. jQuery-Questions jQuery-Selectors Picked HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26202, "s": 26174, "text": "\n25 Jul, 2021" }, { "code": null, "e": 26449, "s": 26202, "text": "In this article, we will change the selected option of the radio button using jQuery. To select the value of the radio button we can set the “checked” to set to the desired option. For setting the property, we can use the prop() method in jQuery." }, { "code": null, "e": 26457, "s": 26449, "text": "Syntax:" }, { "code": null, "e": 26493, "s": 26457, "text": "$(selector).prop(\"checked\", true); " }, { "code": null, "e": 26561, "s": 26493, "text": "Note: Selector, is the desired radio option element to be selected." }, { "code": null, "e": 26800, "s": 26561, "text": "Example: Let us create a radio button group to select a favorite cricket player. We have created a radio option. By default, “Sachin” will be selected. When we click the button, the “Dhoni” option will be selected as given in the program." }, { "code": null, "e": 26805, "s": 26800, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <meta charset=\"utf-8\" /> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js\"> </script> </head> <body> <fieldset> <legend>Who is Your Favorite Cricketer?</legend> <input type=\"radio\" name=\"favorite\" value=\"Dhoni\" />Dhoni<br /> <input type=\"radio\" name=\"favorite\" value=\"Shewag\" />Shewag<br /> <input type=\"radio\" name=\"favorite\" checked value=\"Sachin\" />Sachin<br /> <br /> <button id=\"selectID\">Select option</button> </fieldset> <script> $(\"#selectID\").on(\"click\", function () { selectRadio(); }); function selectRadio() { let radioOption = jQuery(\"input:radio[value=Dhoni]\"); // This will select the radio button radioOption.prop(\"checked\", true); } </script> </body></html>", "e": 27724, "s": 26805, "text": null }, { "code": null, "e": 27732, "s": 27724, "text": "Output:" }, { "code": null, "e": 27751, "s": 27732, "text": "change radio state" }, { "code": null, "e": 27888, "s": 27751, "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": 27905, "s": 27888, "text": "jQuery-Questions" }, { "code": null, "e": 27922, "s": 27905, "text": "jQuery-Selectors" }, { "code": null, "e": 27929, "s": 27922, "text": "Picked" }, { "code": null, "e": 27934, "s": 27929, "text": "HTML" }, { "code": null, "e": 27941, "s": 27934, "text": "JQuery" }, { "code": null, "e": 27958, "s": 27941, "text": "Web Technologies" }, { "code": null, "e": 27963, "s": 27958, "text": "HTML" }, { "code": null, "e": 28061, "s": 27963, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28085, "s": 28061, "text": "REST API (Introduction)" }, { "code": null, "e": 28126, "s": 28085, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 28163, "s": 28126, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28192, "s": 28163, "text": "Form validation using jQuery" }, { "code": null, "e": 28212, "s": 28192, "text": "Angular File Upload" }, { "code": null, "e": 28258, "s": 28212, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 28287, "s": 28258, "text": "Form validation using jQuery" }, { "code": null, "e": 28350, "s": 28287, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 28427, "s": 28350, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
K-th smallest element after removing some integers from natural numbers - GeeksforGeeks
28 Apr, 2021 Given an array arr[] of size ‘n’ and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[p] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print “-1”. Examples : Input : arr[] = { 1 } and k = 1. Output: 2 Natural numbers are {1, 2, 3, 4, .... } After removing {1}, we get {2, 3, 4, ...}. Now, K-th smallest element = 2. Input : arr[] = {1, 3}, k = 4. Output : 6 First 5 Natural number {1, 2, 3, 4, 5, 6, .. } After removing {1, 3}, we get {2, 4, 5, 6, ... }. Method 1 (Simple): Make an auxiliary array b[] for presence/absence of natural numbers and initialize all with 0. Make all the integer equal to 1 which are present in array arr[] i.e b[arr[i]] = 1. Now, run a loop and decrement k whenever unmarked cell is encountered. When the value of k is 0, we get the answer. Below is implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find the K-th smallest element// after removing some integers from natural number.#include <bits/stdc++.h>#define MAX 1000000using namespace std; // Return the K-th smallest element.int ksmallest(int arr[], int n, int k){ // Making an array, and mark all number as unmarked. int b[MAX]; memset(b, 0, sizeof b); // Marking the number present in the given array. for (int i = 0; i < n; i++) b[arr[i]] = 1; for (int j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) k--; // If k is 0 return j. if (!k) return j; }} // Driven Programint main(){ int k = 1; int arr[] = { 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ksmallest(arr, n, k); return 0;} // Java program to find the K-th smallest element// after removing some integers from natural number.class GFG { static final int MAX = 1000000; // Return the K-th smallest element. static int ksmallest(int arr[], int n, int k) { // Making an array, and mark // all number as unmarked. int b[] = new int[MAX]; // Marking the number present // in the given array. for (int i = 0; i < n; i++) { b[arr[i]] = 1; } for (int j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) { k--; } // If k is 0 return j. if (k != 1) { return j; } } return Integer.MAX_VALUE; } // Driven code public static void main(String[] args) { int k = 1; int arr[] = { 1 }; int n = arr.length; System.out.println(ksmallest(arr, n, k)); }} // This code has been contributed by 29AjayKumar # Python program to find the K-th smallest element# after removing some integers from natural number.MAX = 1000000 # Return the K-th smallest element.def ksmallest(arr, n, k): # Making an array, and mark all number as unmarked. b = [0]*MAX; # Marking the number present in the given array. for i in range(n): b[arr[i]] = 1; for j in range(1, MAX): # If j is unmarked, reduce k by 1. if (b[j] != 1): k-= 1; # If k is 0 return j. if (k is not 1): return j; # Driven Programk = 1;arr = [ 1 ];n = len(arr);print(ksmallest(arr, n, k)); # This code contributed by Rajput-Ji // C# program to find the K-th smallest element// after removing some integers from natural number.using System; class GFG { static int MAX = 1000000; // Return the K-th smallest element. static int ksmallest(int[] arr, int n, int k) { // Making an array, and mark // all number as unmarked. int[] b = new int[MAX]; // Marking the number present // in the given array. for (int i = 0; i < n; i++) { b[arr[i]] = 1; } for (int j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) { k--; } // If k is 0 return j. if (k != 1) { return j; } } return int.MaxValue; } // Driven code public static void Main() { int k = 1; int[] arr = { 1 }; int n = arr.Length; Console.WriteLine(ksmallest(arr, n, k)); }} /* This code contributed by PrinciRaj1992 */ <?php// PHP program to find the K-th smallest element// after removing some integers from natural number.$MAX = 10000; // Return the K-th smallest element.function ksmallest($arr, $n, $k){ global $MAX; // Making an array, and mark all number as unmarked. $b=array_fill(0, $MAX, 0); // Marking the number present in the given array. for ($i = 0; $i < $n; $i++) $b[$arr[$i]] = 1; for ($j = 1; $j < $MAX; $j++) { // If j is unmarked, reduce k by 1. if ($b[$j] != 1) $k--; // If k is 0 return j. if ($k == 0) return $j; }} // Driver code $k = 1; $arr = array( 1 ); $n = count($arr); echo ksmallest($arr, $n, $k); // This code is contributed by mits?> <script> // Javascript program to find the K-th// smallest element after removing some// integers from natural number. let MAX = 1000000; // Return the K-th smallest element.function ksmallest(arr, n, k){ // Making an array, and mark // all number as unmarked. let b = []; // Marking the number present // in the given array. for(let i = 0; i < n; i++) { b[arr[i]] = 1; } for(let j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) { k--; } // If k is 0 return j. if (k != 1) { return j; } } return Number.MAX_VALUE;} // Driver code let k = 1;let arr = [1];let n = arr.length; document.write(ksmallest(arr, n, k)); // This code is contributed by susmitakundugoaldanga </script> Output : 2 Time Complexity : O(n). Method 2 (Efficient): First, sort the array arr[]. Observe, there will be arr[0] – 1 numbers between 0 and arr[0], similarly, arr[1] – arr[0] – 1 numbers between arr[0] and arr[1] and so on. So, if k lies between arr[i] – arr[i+1] – 1, then return K-th smallest element in the range. Else reduce k by arr[i] – arr[i+1] – 1 i.e., k = k – (arr[i] – arr[i+1] – 1). Algorithm to solve the problem: 1. Sort the array arr[]. 2. For i = 1 to k. Find c = arr[i+1] - arr[i] -1. a) if k - c <= 0, return arr[i-1] + k. b) else k = k - c. Below is implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program to find the Kth smallest element// after removing some integer from first n// natural number.#include <bits/stdc++.h>using namespace std; // Return the K-th smallest element.int ksmallest(int arr[], int n, int k){ sort(arr, arr + n); // Checking if k lies before 1st element if (k < arr[0]) return k; // If k is the first element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more than last element if (k > arr[n - 1]) return k + n; // If first element of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest element after removing // array elements. for (int i = 1; i < n; i++) { // Finding count of element between i-th // and (i-1)-th element. int c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k;} // Driven Programint main(){ int k = 1; int arr[] = { 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ksmallest(arr, n, k); return 0;} // Java program to find the// Kth smallest element after// removing some integer from// first n natural number.import java.util.Arrays;import java.io.*; class GFG { // Return the K-th // smallest element. static int ksmallest(int arr[], int n, int k) { // sort(arr, arr+n); Arrays.sort(arr); // Checking if k lies // before 1st element if (k < arr[0]) return k; // If k is the first // element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more // than last element if (k > arr[n - 1]) return k + n; // If first element // of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers // before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest // element after removing // array elements. for (int i = 1; i < n; i++) { // Finding count of // element between i-th // and (i-1)-th element. int c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k; } // Driven Code public static void main(String[] args) { int k = 1; int arr[] = { 1 }; int n = arr.length; System.out.println(ksmallest(arr, n, k)); }} // This code is contributed// by ajit # Python3 program to find the Kth# smallest element after# removing some integer from# first n natural number. # Return the K-th# smallest element.def ksmallest(arr, n, k): arr.sort(); # Checking if k lies # before 1st element if (k < arr[0]): return k; # If k is the first # element of array arr[]. if (k == arr[0]): return arr[0] + 1; # If k is more # than last element if (k > arr[n - 1]): return k + n; # If first element # of array is 1. if (arr[0] == 1): k-= 1; # Reducing k by numbers # before arr[0]. else: k -= (arr[0] - 1); # Finding k'th smallest element # after removing array elements. for i in range(1, n): # Finding count of element between # i-th and (i-1)-th element. c = arr[i] - arr[i - 1] - 1; if (k <= c): return arr[i - 1] + k; else: k -= c; return arr[n - 1] + k; # Driver Codek = 1;arr =[ 1 ];n = len(arr);print(ksmallest(arr, n, k)); # This code is contributed by mits // C# program to find the// Kth smallest element after// removing some integer from// first n natural number.using System; class GFG { // Return the K-th // smallest element. static int ksmallest(int[] arr, int n, int k) { // sort(arr, arr+n); Array.Sort(arr); // Checking if k lies // before 1st element if (k < arr[0]) return k; // If k is the first // element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more // than last element if (k > arr[n - 1]) return k + n; // If first element // of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers // before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest // element after removing // array elements. for (int i = 1; i < n; i++) { // Finding count of // element between i-th // and (i-1)-th element. int c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k; } // Driver Code static public void Main() { int k = 1; int[] arr = { 1 }; int n = arr.Length; Console.WriteLine(ksmallest(arr, n, k)); }} // This code is contributed// by ajit <?php// PHP program to find the Kth// smallest element after// removing some integer from// first n natural number. // Return the K-th// smallest element.function ksmallest($arr, $n, $k){ sort($arr); // Checking if k lies // before 1st element if ($k < $arr[0]) return $k; // If k is the first // element of array arr[]. if ($k == $arr[0]) return $arr[0] + 1; // If k is more // than last element if ($k > $arr[$n - 1]) return $k + $n; // If first element // of array is 1. if ($arr[0] == 1) $k--; // Reducing k by numbers // before arr[0]. else $k -= ($arr[0] - 1); // Finding k'th smallest element // after removing array elements. for ($i = 1; $i < $n; $i++) { // Finding count of element between // i-th and (i-1)-th element. $c = $arr[$i] - $arr[$i - 1] - 1; if ($k <= $c) return $arr[$i - 1] + $k; else $k -= $c; } return $arr[$n - 1] + $k;} // Driver Code$k = 1;$arr = array ( 1 );$n = sizeof($arr);echo ksmallest($arr, $n, $k); // This code is contributed by aj_36?> <script> // Javascript program to find the// Kth smallest element after// removing some integer from// first n natural number. // Return the K-th// smallest element.function ksmallest(arr, n, k){ // sort(arr, arr+n); arr.sort(function(a, b){return a - b}); // Checking if k lies // before 1st element if (k < arr[0]) return k; // If k is the first // element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more // than last element if (k > arr[n - 1]) return k + n; // If first element // of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers // before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest // element after removing // array elements. for(let i = 1; i < n; i++) { // Finding count of // element between i-th // and (i-1)-th element. let c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k;} // Driver codelet k = 1;let arr = [1];let n = arr.length; document.write(ksmallest(arr, n, k)); // This code is contributed by divyesh072019 </script> Output : 2 More efficient method : K-th smallest element after removing given integers from natural numbers | Set 2This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. jit_t 29AjayKumar princiraj1992 Rajput-Ji Mithun Kumar susmitakundugoaldanga divyesh072019 Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem C++ Program for QuickSort Stability in sorting algorithms Quick Sort vs Merge Sort Quickselect Algorithm Sorting in Java Recursive Bubble Sort Python | Sort a List according to the Length of the Elements Check if two arrays are equal or not Segregate 0s and 1s in an array
[ { "code": null, "e": 25323, "s": 25295, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25596, "s": 25323, "text": "Given an array arr[] of size ‘n’ and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[p] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print “-1”." }, { "code": null, "e": 25609, "s": 25596, "text": "Examples : " }, { "code": null, "e": 25908, "s": 25609, "text": "Input : arr[] = { 1 } and k = 1.\nOutput: 2\nNatural numbers are {1, 2, 3, 4, .... }\nAfter removing {1}, we get {2, 3, 4, ...}.\nNow, K-th smallest element = 2.\n\nInput : arr[] = {1, 3}, k = 4.\nOutput : 6\nFirst 5 Natural number {1, 2, 3, 4, 5, 6, .. }\nAfter removing {1, 3}, we get {2, 4, 5, 6, ... }." }, { "code": null, "e": 26222, "s": 25908, "text": "Method 1 (Simple): Make an auxiliary array b[] for presence/absence of natural numbers and initialize all with 0. Make all the integer equal to 1 which are present in array arr[] i.e b[arr[i]] = 1. Now, run a loop and decrement k whenever unmarked cell is encountered. When the value of k is 0, we get the answer." }, { "code": null, "e": 26266, "s": 26222, "text": "Below is implementation of this approach: " }, { "code": null, "e": 26270, "s": 26266, "text": "C++" }, { "code": null, "e": 26275, "s": 26270, "text": "Java" }, { "code": null, "e": 26283, "s": 26275, "text": "Python3" }, { "code": null, "e": 26286, "s": 26283, "text": "C#" }, { "code": null, "e": 26290, "s": 26286, "text": "PHP" }, { "code": null, "e": 26301, "s": 26290, "text": "Javascript" }, { "code": "// C++ program to find the K-th smallest element// after removing some integers from natural number.#include <bits/stdc++.h>#define MAX 1000000using namespace std; // Return the K-th smallest element.int ksmallest(int arr[], int n, int k){ // Making an array, and mark all number as unmarked. int b[MAX]; memset(b, 0, sizeof b); // Marking the number present in the given array. for (int i = 0; i < n; i++) b[arr[i]] = 1; for (int j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) k--; // If k is 0 return j. if (!k) return j; }} // Driven Programint main(){ int k = 1; int arr[] = { 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ksmallest(arr, n, k); return 0;}", "e": 27089, "s": 26301, "text": null }, { "code": "// Java program to find the K-th smallest element// after removing some integers from natural number.class GFG { static final int MAX = 1000000; // Return the K-th smallest element. static int ksmallest(int arr[], int n, int k) { // Making an array, and mark // all number as unmarked. int b[] = new int[MAX]; // Marking the number present // in the given array. for (int i = 0; i < n; i++) { b[arr[i]] = 1; } for (int j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) { k--; } // If k is 0 return j. if (k != 1) { return j; } } return Integer.MAX_VALUE; } // Driven code public static void main(String[] args) { int k = 1; int arr[] = { 1 }; int n = arr.length; System.out.println(ksmallest(arr, n, k)); }} // This code has been contributed by 29AjayKumar", "e": 28108, "s": 27089, "text": null }, { "code": "# Python program to find the K-th smallest element# after removing some integers from natural number.MAX = 1000000 # Return the K-th smallest element.def ksmallest(arr, n, k): # Making an array, and mark all number as unmarked. b = [0]*MAX; # Marking the number present in the given array. for i in range(n): b[arr[i]] = 1; for j in range(1, MAX): # If j is unmarked, reduce k by 1. if (b[j] != 1): k-= 1; # If k is 0 return j. if (k is not 1): return j; # Driven Programk = 1;arr = [ 1 ];n = len(arr);print(ksmallest(arr, n, k)); # This code contributed by Rajput-Ji", "e": 28769, "s": 28108, "text": null }, { "code": "// C# program to find the K-th smallest element// after removing some integers from natural number.using System; class GFG { static int MAX = 1000000; // Return the K-th smallest element. static int ksmallest(int[] arr, int n, int k) { // Making an array, and mark // all number as unmarked. int[] b = new int[MAX]; // Marking the number present // in the given array. for (int i = 0; i < n; i++) { b[arr[i]] = 1; } for (int j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) { k--; } // If k is 0 return j. if (k != 1) { return j; } } return int.MaxValue; } // Driven code public static void Main() { int k = 1; int[] arr = { 1 }; int n = arr.Length; Console.WriteLine(ksmallest(arr, n, k)); }} /* This code contributed by PrinciRaj1992 */", "e": 29771, "s": 28769, "text": null }, { "code": "<?php// PHP program to find the K-th smallest element// after removing some integers from natural number.$MAX = 10000; // Return the K-th smallest element.function ksmallest($arr, $n, $k){ global $MAX; // Making an array, and mark all number as unmarked. $b=array_fill(0, $MAX, 0); // Marking the number present in the given array. for ($i = 0; $i < $n; $i++) $b[$arr[$i]] = 1; for ($j = 1; $j < $MAX; $j++) { // If j is unmarked, reduce k by 1. if ($b[$j] != 1) $k--; // If k is 0 return j. if ($k == 0) return $j; }} // Driver code $k = 1; $arr = array( 1 ); $n = count($arr); echo ksmallest($arr, $n, $k); // This code is contributed by mits?>", "e": 30519, "s": 29771, "text": null }, { "code": "<script> // Javascript program to find the K-th// smallest element after removing some// integers from natural number. let MAX = 1000000; // Return the K-th smallest element.function ksmallest(arr, n, k){ // Making an array, and mark // all number as unmarked. let b = []; // Marking the number present // in the given array. for(let i = 0; i < n; i++) { b[arr[i]] = 1; } for(let j = 1; j < MAX; j++) { // If j is unmarked, reduce k by 1. if (b[j] != 1) { k--; } // If k is 0 return j. if (k != 1) { return j; } } return Number.MAX_VALUE;} // Driver code let k = 1;let arr = [1];let n = arr.length; document.write(ksmallest(arr, n, k)); // This code is contributed by susmitakundugoaldanga </script>", "e": 31383, "s": 30519, "text": null }, { "code": null, "e": 31394, "s": 31383, "text": "Output : " }, { "code": null, "e": 31396, "s": 31394, "text": "2" }, { "code": null, "e": 31782, "s": 31396, "text": "Time Complexity : O(n). Method 2 (Efficient): First, sort the array arr[]. Observe, there will be arr[0] – 1 numbers between 0 and arr[0], similarly, arr[1] – arr[0] – 1 numbers between arr[0] and arr[1] and so on. So, if k lies between arr[i] – arr[i+1] – 1, then return K-th smallest element in the range. Else reduce k by arr[i] – arr[i+1] – 1 i.e., k = k – (arr[i] – arr[i+1] – 1)." }, { "code": null, "e": 31815, "s": 31782, "text": "Algorithm to solve the problem: " }, { "code": null, "e": 31952, "s": 31815, "text": "1. Sort the array arr[].\n2. For i = 1 to k. Find c = arr[i+1] - arr[i] -1.\n a) if k - c <= 0, return arr[i-1] + k.\n b) else k = k - c." }, { "code": null, "e": 31995, "s": 31952, "text": "Below is implementation of this approach: " }, { "code": null, "e": 31999, "s": 31995, "text": "C++" }, { "code": null, "e": 32004, "s": 31999, "text": "Java" }, { "code": null, "e": 32012, "s": 32004, "text": "Python3" }, { "code": null, "e": 32015, "s": 32012, "text": "C#" }, { "code": null, "e": 32019, "s": 32015, "text": "PHP" }, { "code": null, "e": 32030, "s": 32019, "text": "Javascript" }, { "code": "// C++ program to find the Kth smallest element// after removing some integer from first n// natural number.#include <bits/stdc++.h>using namespace std; // Return the K-th smallest element.int ksmallest(int arr[], int n, int k){ sort(arr, arr + n); // Checking if k lies before 1st element if (k < arr[0]) return k; // If k is the first element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more than last element if (k > arr[n - 1]) return k + n; // If first element of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest element after removing // array elements. for (int i = 1; i < n; i++) { // Finding count of element between i-th // and (i-1)-th element. int c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k;} // Driven Programint main(){ int k = 1; int arr[] = { 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << ksmallest(arr, n, k); return 0;}", "e": 33186, "s": 32030, "text": null }, { "code": "// Java program to find the// Kth smallest element after// removing some integer from// first n natural number.import java.util.Arrays;import java.io.*; class GFG { // Return the K-th // smallest element. static int ksmallest(int arr[], int n, int k) { // sort(arr, arr+n); Arrays.sort(arr); // Checking if k lies // before 1st element if (k < arr[0]) return k; // If k is the first // element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more // than last element if (k > arr[n - 1]) return k + n; // If first element // of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers // before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest // element after removing // array elements. for (int i = 1; i < n; i++) { // Finding count of // element between i-th // and (i-1)-th element. int c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k; } // Driven Code public static void main(String[] args) { int k = 1; int arr[] = { 1 }; int n = arr.length; System.out.println(ksmallest(arr, n, k)); }} // This code is contributed// by ajit", "e": 34696, "s": 33186, "text": null }, { "code": "# Python3 program to find the Kth# smallest element after# removing some integer from# first n natural number. # Return the K-th# smallest element.def ksmallest(arr, n, k): arr.sort(); # Checking if k lies # before 1st element if (k < arr[0]): return k; # If k is the first # element of array arr[]. if (k == arr[0]): return arr[0] + 1; # If k is more # than last element if (k > arr[n - 1]): return k + n; # If first element # of array is 1. if (arr[0] == 1): k-= 1; # Reducing k by numbers # before arr[0]. else: k -= (arr[0] - 1); # Finding k'th smallest element # after removing array elements. for i in range(1, n): # Finding count of element between # i-th and (i-1)-th element. c = arr[i] - arr[i - 1] - 1; if (k <= c): return arr[i - 1] + k; else: k -= c; return arr[n - 1] + k; # Driver Codek = 1;arr =[ 1 ];n = len(arr);print(ksmallest(arr, n, k)); # This code is contributed by mits", "e": 35750, "s": 34696, "text": null }, { "code": "// C# program to find the// Kth smallest element after// removing some integer from// first n natural number.using System; class GFG { // Return the K-th // smallest element. static int ksmallest(int[] arr, int n, int k) { // sort(arr, arr+n); Array.Sort(arr); // Checking if k lies // before 1st element if (k < arr[0]) return k; // If k is the first // element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more // than last element if (k > arr[n - 1]) return k + n; // If first element // of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers // before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest // element after removing // array elements. for (int i = 1; i < n; i++) { // Finding count of // element between i-th // and (i-1)-th element. int c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k; } // Driver Code static public void Main() { int k = 1; int[] arr = { 1 }; int n = arr.Length; Console.WriteLine(ksmallest(arr, n, k)); }} // This code is contributed// by ajit", "e": 37214, "s": 35750, "text": null }, { "code": "<?php// PHP program to find the Kth// smallest element after// removing some integer from// first n natural number. // Return the K-th// smallest element.function ksmallest($arr, $n, $k){ sort($arr); // Checking if k lies // before 1st element if ($k < $arr[0]) return $k; // If k is the first // element of array arr[]. if ($k == $arr[0]) return $arr[0] + 1; // If k is more // than last element if ($k > $arr[$n - 1]) return $k + $n; // If first element // of array is 1. if ($arr[0] == 1) $k--; // Reducing k by numbers // before arr[0]. else $k -= ($arr[0] - 1); // Finding k'th smallest element // after removing array elements. for ($i = 1; $i < $n; $i++) { // Finding count of element between // i-th and (i-1)-th element. $c = $arr[$i] - $arr[$i - 1] - 1; if ($k <= $c) return $arr[$i - 1] + $k; else $k -= $c; } return $arr[$n - 1] + $k;} // Driver Code$k = 1;$arr = array ( 1 );$n = sizeof($arr);echo ksmallest($arr, $n, $k); // This code is contributed by aj_36?>", "e": 38354, "s": 37214, "text": null }, { "code": "<script> // Javascript program to find the// Kth smallest element after// removing some integer from// first n natural number. // Return the K-th// smallest element.function ksmallest(arr, n, k){ // sort(arr, arr+n); arr.sort(function(a, b){return a - b}); // Checking if k lies // before 1st element if (k < arr[0]) return k; // If k is the first // element of array arr[]. if (k == arr[0]) return arr[0] + 1; // If k is more // than last element if (k > arr[n - 1]) return k + n; // If first element // of array is 1. if (arr[0] == 1) k--; // Reducing k by numbers // before arr[0]. else k -= (arr[0] - 1); // Finding k'th smallest // element after removing // array elements. for(let i = 1; i < n; i++) { // Finding count of // element between i-th // and (i-1)-th element. let c = arr[i] - arr[i - 1] - 1; if (k <= c) return arr[i - 1] + k; else k -= c; } return arr[n - 1] + k;} // Driver codelet k = 1;let arr = [1];let n = arr.length; document.write(ksmallest(arr, n, k)); // This code is contributed by divyesh072019 </script>", "e": 39580, "s": 38354, "text": null }, { "code": null, "e": 39590, "s": 39580, "text": "Output : " }, { "code": null, "e": 39592, "s": 39590, "text": "2" }, { "code": null, "e": 40116, "s": 39592, "text": "More efficient method : K-th smallest element after removing given integers from natural numbers | Set 2This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.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. " }, { "code": null, "e": 40122, "s": 40116, "text": "jit_t" }, { "code": null, "e": 40134, "s": 40122, "text": "29AjayKumar" }, { "code": null, "e": 40148, "s": 40134, "text": "princiraj1992" }, { "code": null, "e": 40158, "s": 40148, "text": "Rajput-Ji" }, { "code": null, "e": 40171, "s": 40158, "text": "Mithun Kumar" }, { "code": null, "e": 40193, "s": 40171, "text": "susmitakundugoaldanga" }, { "code": null, "e": 40207, "s": 40193, "text": "divyesh072019" }, { "code": null, "e": 40215, "s": 40207, "text": "Sorting" }, { "code": null, "e": 40223, "s": 40215, "text": "Sorting" }, { "code": null, "e": 40321, "s": 40223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40352, "s": 40321, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 40378, "s": 40352, "text": "C++ Program for QuickSort" }, { "code": null, "e": 40410, "s": 40378, "text": "Stability in sorting algorithms" }, { "code": null, "e": 40435, "s": 40410, "text": "Quick Sort vs Merge Sort" }, { "code": null, "e": 40457, "s": 40435, "text": "Quickselect Algorithm" }, { "code": null, "e": 40473, "s": 40457, "text": "Sorting in Java" }, { "code": null, "e": 40495, "s": 40473, "text": "Recursive Bubble Sort" }, { "code": null, "e": 40556, "s": 40495, "text": "Python | Sort a List according to the Length of the Elements" }, { "code": null, "e": 40593, "s": 40556, "text": "Check if two arrays are equal or not" } ]
Node.js Stream readable.resume() Method - GeeksforGeeks
12 Oct, 2021 The readable.resume() method in a Readable Stream is used to paused data that can be resumed again and data starts flowing again. Syntax: readable.resume() Parameters: This method doesn’t accept any parameters. Return Value: If this method is used then the data that was paused, starts flowing again. Below examples illustrate the use of readable.resume() method in Node.js: Example 1: // Node.js program to demonstrate the // readable.resume() method // Including fs moduleconst fs = require('fs'); // Constructing readable streamconst readable = fs.createReadStream("input.text");readable.on('data', (chunk) => { console.log(`${chunk}`);}); // Calling pause methodreadable.pause(); // Calling resume methodreadable.resume(); console.log("Data starts flowing again!!"); Output: Data starts flowing again!! Hello!!! Example 2: // Node.js program to demonstrate the // readable.resume() method // Include fs moduleconst fs = require('fs'); // Create readable streamconst readable = fs.createReadStream("input.text"); // Handling data eventreadable.on('data', (chunk) => { console.log(`${chunk}`); // Calling pause method readable.pause(); // After this any data will be displayed // after 3 sec. console.log('No additional data will be ' + 'displayed for 3 seconds.'); // Using setTimeout function setTimeout(() => { console.log('Now data starts flowing again.'); // Calling resume method readable.resume(); }, 3000);}); // Displays that program // is endedconsole.log("Program ends!!"); Output: Program ends!! Hello!!! No additional data will be displayed for 3 seconds. Now data starts flowing again. However, you can see while running, that after the execution of pause() method, no further data will be displayed for 3 seconds. Reference: https://nodejs.org/api/stream.html#stream_readable_resume Node.js-Stream-module Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Express.js res.render() Function Mongoose | findByIdAndUpdate() Function 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": 25779, "s": 25751, "text": "\n12 Oct, 2021" }, { "code": null, "e": 25909, "s": 25779, "text": "The readable.resume() method in a Readable Stream is used to paused data that can be resumed again and data starts flowing again." }, { "code": null, "e": 25917, "s": 25909, "text": "Syntax:" }, { "code": null, "e": 25935, "s": 25917, "text": "readable.resume()" }, { "code": null, "e": 25990, "s": 25935, "text": "Parameters: This method doesn’t accept any parameters." }, { "code": null, "e": 26080, "s": 25990, "text": "Return Value: If this method is used then the data that was paused, starts flowing again." }, { "code": null, "e": 26154, "s": 26080, "text": "Below examples illustrate the use of readable.resume() method in Node.js:" }, { "code": null, "e": 26165, "s": 26154, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the // readable.resume() method // Including fs moduleconst fs = require('fs'); // Constructing readable streamconst readable = fs.createReadStream(\"input.text\");readable.on('data', (chunk) => { console.log(`${chunk}`);}); // Calling pause methodreadable.pause(); // Calling resume methodreadable.resume(); console.log(\"Data starts flowing again!!\");", "e": 26562, "s": 26165, "text": null }, { "code": null, "e": 26570, "s": 26562, "text": "Output:" }, { "code": null, "e": 26608, "s": 26570, "text": "Data starts flowing again!!\nHello!!!\n" }, { "code": null, "e": 26619, "s": 26608, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the // readable.resume() method // Include fs moduleconst fs = require('fs'); // Create readable streamconst readable = fs.createReadStream(\"input.text\"); // Handling data eventreadable.on('data', (chunk) => { console.log(`${chunk}`); // Calling pause method readable.pause(); // After this any data will be displayed // after 3 sec. console.log('No additional data will be ' + 'displayed for 3 seconds.'); // Using setTimeout function setTimeout(() => { console.log('Now data starts flowing again.'); // Calling resume method readable.resume(); }, 3000);}); // Displays that program // is endedconsole.log(\"Program ends!!\");", "e": 27328, "s": 26619, "text": null }, { "code": null, "e": 27336, "s": 27328, "text": "Output:" }, { "code": null, "e": 27444, "s": 27336, "text": "Program ends!!\nHello!!!\nNo additional data will be displayed for 3 seconds.\nNow data starts flowing again.\n" }, { "code": null, "e": 27573, "s": 27444, "text": "However, you can see while running, that after the execution of pause() method, no further data will be displayed for 3 seconds." }, { "code": null, "e": 27642, "s": 27573, "text": "Reference: https://nodejs.org/api/stream.html#stream_readable_resume" }, { "code": null, "e": 27664, "s": 27642, "text": "Node.js-Stream-module" }, { "code": null, "e": 27672, "s": 27664, "text": "Node.js" }, { "code": null, "e": 27689, "s": 27672, "text": "Web Technologies" }, { "code": null, "e": 27787, "s": 27689, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27844, "s": 27787, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27898, "s": 27844, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27935, "s": 27898, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 27968, "s": 27935, "text": "Express.js res.render() Function" }, { "code": null, "e": 28008, "s": 27968, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 28048, "s": 28008, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28093, "s": 28048, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28136, "s": 28093, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28186, "s": 28136, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Integrating Facebook Like & Share Plugin Using Django - GeeksforGeeks
16 Feb, 2021 Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. In this article we will learn to integrate facebook comment plugin in django. How to Integrate Facebook Like & Share Plugin in Django ? Installation pip install django 1) Create new project django-admin startproject Test_prj 2) Navigate to Test_prj directory cd Test_prj 3) Create new app python manage.py startapp main Folder Structure : Then add the app name inside the INSTALLED_APPS (settings.py). views.py Python3 from django.shortcuts import render # Create your views here.def home(request): return render(request,"main/index.html") Create new file urls.py inside the main directory Python3 from django.urls import pathfrom .views import * urlpatterns = [ path('',home,name="home")] Add the main/urls.py inside the urls.py Python3 from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include("main.urls")),] https://developers.facebook.com/docs/plugins/like-button/ Go to this link to get code Click on get code Create new directory templates inside the main app inside that create main directory index.html HTML <!DOCTYPE html><html><head> <title>GFG</title> <div id="fb-root"></div> <script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v9.0" nonce="8E6OZDVx"></script></head><body> <h1>Welcome To GFG</h1> <div class="fb-like" data-href="http://127.0.0.1:8000/8000" data-width="" data-layout="button_count" data-action="like" data-size="large" data-share="true"></div></body></html> Open cmd or terminal to run this app python manage.py runserver OUTPUT :- Python Django Python Framework Python Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 25539, "s": 25511, "text": "\n16 Feb, 2021" }, { "code": null, "e": 25891, "s": 25539, "text": "Django is a Python-based web framework that allows you to quickly create efficient web applications. It is also called batteries included framework because Django provides built-in features for everything including Django Admin Interface, default database – SQLlite3, etc. In this article we will learn to integrate facebook comment plugin in django." }, { "code": null, "e": 25949, "s": 25891, "text": "How to Integrate Facebook Like & Share Plugin in Django ?" }, { "code": null, "e": 25962, "s": 25949, "text": "Installation" }, { "code": null, "e": 25981, "s": 25962, "text": "pip install django" }, { "code": null, "e": 26003, "s": 25981, "text": "1) Create new project" }, { "code": null, "e": 26038, "s": 26003, "text": "django-admin startproject Test_prj" }, { "code": null, "e": 26072, "s": 26038, "text": "2) Navigate to Test_prj directory" }, { "code": null, "e": 26084, "s": 26072, "text": "cd Test_prj" }, { "code": null, "e": 26102, "s": 26084, "text": "3) Create new app" }, { "code": null, "e": 26133, "s": 26102, "text": "python manage.py startapp main" }, { "code": null, "e": 26152, "s": 26133, "text": "Folder Structure :" }, { "code": null, "e": 26216, "s": 26152, "text": "Then add the app name inside the INSTALLED_APPS (settings.py)." }, { "code": null, "e": 26225, "s": 26216, "text": "views.py" }, { "code": null, "e": 26233, "s": 26225, "text": "Python3" }, { "code": "from django.shortcuts import render # Create your views here.def home(request): return render(request,\"main/index.html\")", "e": 26358, "s": 26233, "text": null }, { "code": null, "e": 26408, "s": 26358, "text": "Create new file urls.py inside the main directory" }, { "code": null, "e": 26416, "s": 26408, "text": "Python3" }, { "code": "from django.urls import pathfrom .views import * urlpatterns = [ path('',home,name=\"home\")]", "e": 26512, "s": 26416, "text": null }, { "code": null, "e": 26552, "s": 26512, "text": "Add the main/urls.py inside the urls.py" }, { "code": null, "e": 26560, "s": 26552, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('',include(\"main.urls\")),]", "e": 26717, "s": 26560, "text": null }, { "code": null, "e": 26775, "s": 26717, "text": "https://developers.facebook.com/docs/plugins/like-button/" }, { "code": null, "e": 26803, "s": 26775, "text": "Go to this link to get code" }, { "code": null, "e": 26821, "s": 26803, "text": "Click on get code" }, { "code": null, "e": 26907, "s": 26821, "text": "Create new directory templates inside the main app inside that create main directory" }, { "code": null, "e": 26918, "s": 26907, "text": "index.html" }, { "code": null, "e": 26923, "s": 26918, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>GFG</title> <div id=\"fb-root\"></div> <script async defer crossorigin=\"anonymous\" src=\"https://connect.facebook.net/en_GB/sdk.js#xfbml=1&version=v9.0\" nonce=\"8E6OZDVx\"></script></head><body> <h1>Welcome To GFG</h1> <div class=\"fb-like\" data-href=\"http://127.0.0.1:8000/8000\" data-width=\"\" data-layout=\"button_count\" data-action=\"like\" data-size=\"large\" data-share=\"true\"></div></body></html>", "e": 27405, "s": 26923, "text": null }, { "code": null, "e": 27442, "s": 27405, "text": "Open cmd or terminal to run this app" }, { "code": null, "e": 27469, "s": 27442, "text": "python manage.py runserver" }, { "code": null, "e": 27479, "s": 27469, "text": "OUTPUT :-" }, { "code": null, "e": 27493, "s": 27479, "text": "Python Django" }, { "code": null, "e": 27510, "s": 27493, "text": "Python Framework" }, { "code": null, "e": 27517, "s": 27510, "text": "Python" }, { "code": null, "e": 27534, "s": 27517, "text": "Web Technologies" }, { "code": null, "e": 27632, "s": 27534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27664, "s": 27632, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27706, "s": 27664, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27748, "s": 27706, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27775, "s": 27748, "text": "Python Classes and Objects" }, { "code": null, "e": 27831, "s": 27775, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27871, "s": 27831, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27904, "s": 27871, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27949, "s": 27904, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27992, "s": 27949, "text": "How to fetch data from an API in ReactJS ?" } ]
Learn How to Setup Email Services using Postfix in Linux
There are a number of reasons why you would want to set up your own Linux mail server. These days more people than ever are compelled to get their email fixed – if it ever fails. Postfix is an MTA (Mail switch Agent), a software used to send and receive mail. It is Wietse Venema’s mail server that began life at IBM research alternatively to the largely used Sendmail application. Now at Google, Wietse continues to support Postfix. This article explains about – How to setup Email Services using postfix in Linux. To install Postfix and test mail utilities, use the following command – $ sudo apt-get install mailutils The sample output should be like this- Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: linux-headers-4.4.0-53 linux-headers-4.4.0-53-generic linux-image-4.4.0-53-generic linux-image-extra-4.4.0-53-generic linux-signed-image-4.4.0-53-generic Use 'sudo apt autoremove' to remove them. The following additional packages will be installed: libgsasl7 libkyotocabinet16v5 libmailutils4 libntlm0 mailutils-common postfix Suggested packages: mailutils-mh mailutils-doc procmail postfix-mysql postfix-pgsql postfix-ldap postfix-pcre sasl2-bin dovecot-common postfix-cdb postfix-doc The following NEW packages will be installed: libgsasl7 libkyotocabinet16v5 libmailutils4 libntlm0 mailutils mailutils-common postfix While installation process is going on, it will promote the following screen to configure postfix- Click on ok button to move ahead. Now it will promote the following screen to configure general type of mail configuration as shown below – Select internet site and click on Ok button. By default, it takes the system name as system mail name as shown in the below screen – Change the system mail name according to the requirement. For instance, we have taken as tutorialspoint.com as system mail name. Now click on ok button. After completing the installation process, you are required to configure postfix. To do that, open the configure file using the following command. $sudo nano /etc/postfix/main.cf The sample output should be like this – # See /usr/share/postfix/main.cf.dist for a commented, more complete version # Debian specific: Specifying a file name will cause the first # line of that file to be used as the name. The Debian default # is /etc/mailname. #myorigin = /etc/mailname smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu) biff = no # appending .domain is the MUA's job. append_dot_mydomain = no # Uncomment the next line to generate "delayed mail" warnings #delay_warning_time = 4h readme_directory = no Now look up for inet_interfaces = all and rechange it as inet_interfaces = loopback-only.The sample output should be like this – mailbox_size_limit = 0 recipient_delimiter = + inet_interfaces = loopback-only inet_protocols = all Save the file by clicking Ctrl+O and close the file by clicking Ctrl+X.Now restart Postfix using the following command – $ sudo service postfix restart To get the more information about postfix, use the following command – $ man postfix The sample output should be like this – POSTFIX(1) General Commands Manual POSTFIX(1) NAME postfix - Postfix control program SYNOPSIS postfix [-Dv] [-c config_dir] command DESCRIPTION This command is reserved for the superuser. To submit mail, use the Postfix sendmail(1) command. The postfix(1) command controls the operation of the Postfix mail sys‐ tem: start or stop the master(8) daemon, do a health check, and other maintenance. By default, the postfix(1) command sets up a standardized environment and runs the postfix-script shell script to do the actual work. However, when support for multiple Postfix instances is configured, postfix(1) executes the command specified with the multi_instance_wrap‐ per configuration parameter. This command will execute the command for each applicable Postfix instance. Using the following command to send the mail using Postfix as shown blow – echo "Tutorials Point originated from the idea that there exists a class of readers who respond better to online content and prefer to learn new skills at their own pace from the comforts of their drawing rooms." | mail -s "About us" sairamkrishna@tutorialspoint.com Now check your inbox or spam folder to verify mail.The sample output of above mail should be like this – In the above article, we have learnt about – Learn how to setup Email Services using postfix in Linux. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!
[ { "code": null, "e": 1578, "s": 1062, "text": "There are a number of reasons why you would want to set up your own Linux mail server. These days more people than ever are compelled to get their email fixed – if it ever fails. Postfix is an MTA (Mail switch Agent), a software used to send and receive mail. It is Wietse Venema’s mail server that began life at IBM research alternatively to the largely used Sendmail application. Now at Google, Wietse continues to support Postfix. This article explains about – How to setup Email Services using postfix in Linux." }, { "code": null, "e": 1650, "s": 1578, "text": "To install Postfix and test mail utilities, use the following command –" }, { "code": null, "e": 1683, "s": 1650, "text": "$ sudo apt-get install mailutils" }, { "code": null, "e": 1722, "s": 1683, "text": "The sample output should be like this-" }, { "code": null, "e": 2538, "s": 1722, "text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n linux-headers-4.4.0-53 linux-headers-4.4.0-53-generic\n linux-image-4.4.0-53-generic linux-image-extra-4.4.0-53-generic\n linux-signed-image-4.4.0-53-generic\nUse 'sudo apt autoremove' to remove them.\nThe following additional packages will be installed:\n libgsasl7 libkyotocabinet16v5 libmailutils4 libntlm0 mailutils-common\n postfix\nSuggested packages:\n mailutils-mh mailutils-doc procmail postfix-mysql postfix-pgsql postfix-ldap\n postfix-pcre sasl2-bin dovecot-common postfix-cdb postfix-doc\nThe following NEW packages will be installed:\n libgsasl7 libkyotocabinet16v5 libmailutils4 libntlm0 mailutils\n mailutils-common postfix" }, { "code": null, "e": 2637, "s": 2538, "text": "While installation process is going on, it will promote the following screen to configure postfix-" }, { "code": null, "e": 2777, "s": 2637, "text": "Click on ok button to move ahead. Now it will promote the following screen to configure general type of mail configuration as shown below –" }, { "code": null, "e": 2910, "s": 2777, "text": "Select internet site and click on Ok button. By default, it takes the system name as system mail name as shown in the below screen –" }, { "code": null, "e": 3210, "s": 2910, "text": "Change the system mail name according to the requirement. For instance, we have taken as tutorialspoint.com as system mail name. Now click on ok button. After completing the installation process, you are required to configure postfix. To do that, open the configure file using the following command." }, { "code": null, "e": 3242, "s": 3210, "text": "$sudo nano /etc/postfix/main.cf" }, { "code": null, "e": 3282, "s": 3242, "text": "The sample output should be like this –" }, { "code": null, "e": 3774, "s": 3282, "text": "# See /usr/share/postfix/main.cf.dist for a commented, more complete version\n\n\n# Debian specific: Specifying a file name will cause the first\n# line of that file to be used as the name. The Debian default\n# is /etc/mailname.\n#myorigin = /etc/mailname\n\nsmtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)\nbiff = no\n\n# appending .domain is the MUA's job.\nappend_dot_mydomain = no\n\n# Uncomment the next line to generate \"delayed mail\" warnings\n#delay_warning_time = 4h\n\nreadme_directory = no\n\n" }, { "code": null, "e": 3903, "s": 3774, "text": "Now look up for inet_interfaces = all and rechange it as inet_interfaces = loopback-only.The sample output should be like this –" }, { "code": null, "e": 4003, "s": 3903, "text": "mailbox_size_limit = 0\nrecipient_delimiter = +\ninet_interfaces = loopback-only\ninet_protocols = all" }, { "code": null, "e": 4124, "s": 4003, "text": "Save the file by clicking Ctrl+O and close the file by clicking Ctrl+X.Now restart Postfix using the following command –" }, { "code": null, "e": 4155, "s": 4124, "text": "$ sudo service postfix restart" }, { "code": null, "e": 4226, "s": 4155, "text": "To get the more information about postfix, use the following command –" }, { "code": null, "e": 4240, "s": 4226, "text": "$ man postfix" }, { "code": null, "e": 4280, "s": 4240, "text": "The sample output should be like this –" }, { "code": null, "e": 5142, "s": 4280, "text": "POSTFIX(1) General Commands Manual POSTFIX(1)\n\nNAME\n postfix - Postfix control program\nSYNOPSIS\n postfix [-Dv] [-c config_dir] command\nDESCRIPTION\n This command is reserved for the superuser. To submit mail, use the\n Postfix sendmail(1) command.\n\n The postfix(1) command controls the operation of the Postfix mail sys‐\n tem: start or stop the master(8) daemon, do a health check, and other\n maintenance.\n\n By default, the postfix(1) command sets up a standardized environment\n and runs the postfix-script shell script to do the actual work.\n\n However, when support for multiple Postfix instances is configured,\n postfix(1) executes the command specified with the multi_instance_wrap‐\n per configuration parameter. This command will execute the command for\n each applicable Postfix instance." }, { "code": null, "e": 5217, "s": 5142, "text": "Using the following command to send the mail using Postfix as shown blow –" }, { "code": null, "e": 5486, "s": 5217, "text": "echo \"Tutorials Point originated from the idea that there exists a class of readers who respond better \nto online content and prefer to learn new skills at their own pace from the comforts of their drawing \nrooms.\" | mail -s \"About us\" sairamkrishna@tutorialspoint.com" }, { "code": null, "e": 5591, "s": 5486, "text": "Now check your inbox or spam folder to verify mail.The sample output of above mail should be like this –" }, { "code": null, "e": 5785, "s": 5591, "text": "In the above article, we have learnt about – Learn how to setup Email Services using postfix in Linux. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!" } ]
30 Examples to Master SQL. A comprehensive practical tutorial | by Soner Yıldırım | Towards Data Science
SQL is a programming language that is used to manage data stored in tabular form (i.e. tables) in relational databases. A relational database consists of multiple tables that relate to each other. The relation between tables is formed in the sense of shared columns. There are many different relational database management systems (e.g. MySQL, PostgreSQL, SQL Server). The SQL syntax they adapt might differ slightly. However, the difference is very small so if you learn how to use one, you can easily switch to another one. In this article, we will go over 30 examples that cover the following operations with SQL: Create a database and tables Insert data into tables Delete data from tables Update tables Query tables using a wide variety of select statements There are many alternatives to use SQL in your machine or on the cloud. I’m currently using MySQL on a linux machine through the terminal. Another commonly used alternative is to install MySQL Workbench. We first connect to the MySQL server from the terminal and create a database. ~$ sudo mysql -u root We will be prompted to enter the password. We are now connected to the MySQL server in our machine. The following command creates a database called “retail”. mysql> create database retail;mysql> use retail; We are not in the retail database which does not contain any tables yet. We will first create a table called “customer” using the create table command. mysql> create table customer ( -> cust_id int primary key, -> age int, -> location varchar(20), -> gender varchar(20) -> ); We define the name of the columns and associated data types inside the parenthesis. The cust_id column is specified as the primary key. Primary key is the column that uniquely identifies each row. It is like the index of a pandas dataframe. We will create the second table which is called “orders”. mysql> create table orders ( -> order_id int primary key, -> date date, -> amount decimal(5,2), -> cust_id int, -> foreign key (cust_id) references customer(cust_id) -> on delete cascade -> ); In the beginning, we mentioned that relational tables are related to each other by means of shared columns. A column that relates two tables is a foreign key. Foreign key is what relates a table to another one. Foreign key contains the primary key of another table. The cust_id column in the orders table is a foreign key and related the orders table to the customer table. We specify this condition while creating the table. In the last line, we specify another condition with “on delete cascade” phrase. It tells MySQL what to do when a row in the customer table is deleted. Each row in the orders table belongs to a customer. Each row in the customer table contains a unique customer id and represents a customer. If a row in the customer table is removed, it means we do not have that customer any more. As a result, the orders that belonged to that customer do not have an associated customer id anymore. “On delete cascade” indicates that orders that do not have an associated customer id will also be deleted. The retail database contains two tables now. We can view the tables exist in a database using the show tables command. mysql> show tables;+------------------+| Tables_in_retail |+------------------+| customer || orders |+------------------+ Note: The commands in SQL ends with a semi-colon (“;”). The desc or describe commands provide an overview of the table in terms of column names, data types, and some additional information. mysql> desc orders;+----------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+--------------+------+-----+---------+-------+| order_id | int(11) | NO | PRI | NULL | || date | date | YES | | NULL | || amount | decimal(5,2) | YES | | NULL | || cust_id | int(11) | YES | MUL | NULL | |+----------+--------------+------+-----+---------+-------+ We can modify existing tables. For instance, the alter table command can be used to add a new column or delete an existing column. Let’s add a column to the orders table called “is_sale”. mysql> alter table orders add is_sale varchar(20); We write the column name and data type along with the add keyword. mysql> desc orders;+----------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+--------------+------+-----+---------+-------+| order_id | int(11) | NO | PRI | NULL | || date | date | YES | | NULL | || amount | decimal(5,2) | YES | | NULL | || cust_id | int(11) | YES | MUL | NULL | || is_sale | varchar(20) | YES | | NULL | |+----------+--------------+------+-----+---------+-------+ The is_sale column has been added to the orders table. The alter table can also be used to delete a column with a minor change in the syntax. mysql> alter table orders drop is_sale; The drop keyword is used instead of the add. We also do not have to write the data type to drop a column. We have tables but they do not contain any data. One way to populate tables is the insert statement. mysql> insert into customer values ( -> 1000, 42, 'Austin', 'female' -> ); The specified values are inserted into the columns in the same order. Thus, we need to keep the order consistent. We can insert multiple rows at the same time by separating each row. mysql> insert into customer values -> (1001, 34, 'Austin', 'male'), -> (1002, 37, 'Houston', 'male'), -> (1003, 25, 'Austin', 'female'), -> (1004, 28, 'Houston', 'female'), -> (1005, 22, 'Dallas', 'male'), -> ; I have added some more rows and also populated the orders table in the same way. There are other ways to populate the tables with data. For instance, we can load a csv file using the load data infile or load data local infile statements. The delete from statement can be used to delete existing rows in a table. We need to identify the rows to be deleted by providing a condition. For instance, the statement below will delete the row with an order id of 17. mysql> delete from orders -> where order_id = 17; If we do not specify a condition, all rows in the given table are deleted. We can also update an existing row. Let’s update a row in the orders table. +----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 24.40 | 1001 |+----------+------------+--------+---------+ This is the first row in the orders table. We want to change the order amount to 27.40. mysql> update orders -> set amount = 27.40 -> where order_id = 1;mysql> select * from orders limit 1;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 27.40 | 1001 |+----------+------------+--------+---------+ We write the updated values after the set keyword. The rows to be updates are identified by providing the conditions after the where keyword. If we want to create a table by copying the structure of an existing table, we can use the create table statement with the like keyword. mysql> create table orders_copy like orders;mysql> show tables;+------------------+| Tables_in_retail |+------------------+| customer || orders || orders_copy |+------------------+ The orders_copy table has the same structure as the orders table but does not contain any data. We can also create a copy of an existing table with the data by using the create table and select statements together. mysql> create table new_orders -> select * from orders; It seems like a combination of two separate statements. The first line creates the table and the second line populates it with the data in the orders table. The drop table statement can be used to delete tables in a database. mysql> drop table orders_copy, new_orders;mysql> show tables;+------------------+| Tables_in_retail |+------------------+| customer || orders |+------------------+ We have successfully dropped the tables created in the previous example. We have two relational tables in a database. The following examples will demonstrate how we can retrieve data from these tables using select queries. The simplest query is to view all the columns in a table. mysql> select * from orders -> limit 3;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 27.40 | 1001 || 2 | 2020-10-01 | 36.20 | 1000 || 3 | 2020-10-01 | 65.45 | 1002 |+----------+------------+--------+---------+ The “*” selects all the columns and limit keyword puts a constraint on the number of rows to be displayed. We can select only some of the columns by writing the name of the columns instead of “*”. mysql> select order_id, amount -> from orders -> limit 3;+----------+--------+| order_id | amount |+----------+--------+| 1 | 27.40 || 2 | 36.20 || 3 | 65.45 |+----------+--------+ We can specify a condition for the rows to be selected using the where clause. The following query will return all the orders made on 2020–10–01. mysql> select * from orders -> where date = '2020-10-01';+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 27.40 | 1001 || 2 | 2020-10-01 | 36.20 | 1000 || 3 | 2020-10-01 | 65.45 | 1002 |+----------+------------+--------+---------+ The where clause accepts multiple conditions. Let’s add another condition on the query in the previous example. mysql> select * from orders -> where date = '2020-10-01' and amount > 50;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 3 | 2020-10-01 | 65.45 | 1002 |+----------+------------+--------+---------+ We may want to sort the query results which can be done by using the order by clause. The following query will return the orders on 2020–10–02 and sort them based on the amount. mysql> select * from orders -> where date = '2020-10-02' -> order by amount;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 5 | 2020-10-02 | 18.80 | 1005 || 6 | 2020-10-02 | 21.15 | 1009 || 4 | 2020-10-02 | 34.40 | 1001 || 7 | 2020-10-02 | 34.40 | 1008 || 8 | 2020-10-02 | 41.10 | 1002 |+----------+------------+--------+---------+ The order by clause sorts the rows in ascending order by default. We can change it to descending with the desc keyword. mysql> select * from orders -> where date = '2020-10-02' -> order by amount desc;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 8 | 2020-10-02 | 41.10 | 1002 || 4 | 2020-10-02 | 34.40 | 1001 || 7 | 2020-10-02 | 34.40 | 1008 || 6 | 2020-10-02 | 21.15 | 1009 || 5 | 2020-10-02 | 18.80 | 1005 |+----------+------------+--------+---------+ SQL is a versatile language which can also be used as a data analysis tool. It provides many functions to analyze and transform data while querying from a database. For instance, we can count the number of unique days in the orders table. mysql> select count(distinct(date)) as day_count -> from orders;+-----------+| day_count |+-----------+| 4 |+-----------+ The orders table contain orders in 4 different days. The “as” keyword is used to rename the column in the query result. Otherwise the name of the column would be “count(distinct(date))”. There are 4 different days in the orders table. We can also find out how many orders exist for each day. The group by clause will help us accomplish this task. mysql> select date, count(order_id) as order_count -> from orders -> group by date;+------------+-------------+| date | order_count |+------------+-------------+| 2020-10-01 | 3 || 2020-10-02 | 5 || 2020-10-03 | 6 || 2020-10-04 | 2 |+------------+-------------+ We count the orders and group them by the date column. We will calculate the average order amount in each day and order the results based on average amount in descending order. mysql> select date, avg(amount) -> from orders -> group by date -> order by avg(amount) desc;+------------+-------------+| date | avg(amount) |+------------+-------------+| 2020-10-01 | 43.016667 || 2020-10-04 | 42.150000 || 2020-10-03 | 37.025000 || 2020-10-02 | 29.970000 |+------------+-------------+ We want to modify the query in the previous example and only include days with an average amount higher than 30. mysql> select date, avg(amount) -> from orders -> group by date -> having avg(amount) > 30 -> order by avg(amount) desc;+------------+-------------+| date | avg(amount) |+------------+-------------+| 2020-10-01 | 43.016667 || 2020-10-04 | 42.150000 || 2020-10-03 | 37.025000 |+------------+-------------+ It is important to note that the order of the statements in the query matters. For instance, it gives an error if we put the order by clause before the having clause. We want to find out the maximum order amount for each day. mysql> select date, max(amount) -> from orders -> group by date;+------------+-------------+| date | max(amount) |+------------+-------------+| 2020-10-01 | 65.45 || 2020-10-02 | 41.10 || 2020-10-03 | 80.20 || 2020-10-04 | 50.10 |+------------+-------------+ We want to combine multiple aggregate functions in a select statement. To demonstrate it, let’s elaborate on the previous example. We want to see the difference between the maximum order and minimum order of each customer. We also want to sort the results based on the difference in ascending order and display the first three. mysql> select cust_id, max(amount) - min(amount) as dif -> from orders -> group by cust_id -> order by dif desc -> limit 3;+---------+-------+| cust_id | dif |+---------+-------+| 1007 | 46.00 || 1009 | 28.95 || 1002 | 24.35 |+---------+-------+ The dif column is obtained by substracting the minimum amount from the maximum amount. We are switching to the customer table now. Let’s find out how many female and male customers we have in each city. We need to write both location and gender columns in the group by clause. mysql> select location, gender, count(cust_id) -> from customer -> group by location, gender;+----------+--------+----------------+| location | gender | count(cust_id) |+----------+--------+----------------+| Austin | female | 2 || Austin | male | 1 || Dallas | female | 2 || Dallas | male | 2 || Houston | female | 2 || Houston | male | 1 |+----------+--------+----------------+ The customer and orders tables are related to each other based on the cust_id column. We can query data from both tables using SQL joins. We want to see average order amount for each city in the customer table. mysql> select customer.location, avg(orders.amount) as avg -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;+----------+-----------+| location | avg |+----------+-----------+| Austin | 33.333333 || Dallas | 34.591667 || Houston | 44.450000 |+----------+-----------+ Since we select columns from two different tables, the column names are specified with associated table name. The second, third, and fourth line of the query above joins the customer and orders table based on the cust_id column in each table. Please note that the column names do not have to be the same. Whatever column name we provide with the “on” keyword, the comparison or matching is done based on these columns. We want to see the average age of customers who have an order on 2020–10–03. mysql> select avg(c.age) as avg_age -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where o.date = '2020-10-03';+---------+| avg_age |+---------+| 30.0000 |+---------+ We can use aliases for the table names as well. It comes in handy when we need to type the table names many times. We want to see the location of customer who has the highest amount of order. mysql> select c.location, o.amount -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where o.amount = (select max(amount) from orders) -> ;+----------+--------+| location | amount |+----------+--------+| Dallas | 80.20 |+----------+--------+ We have a nested select statement in this query. The condition on the amount is calculated using a separate select statement from the orders table. This task can be completed in a different way. I have chosen this method to introduce the idea of nested queries. I believe the 30 examples in this article provide a comprehensive introduction to SQL. We have covered the following topics: Creating a database with relational tables Modifying tables Inserting data into tables Deleting data from tables Writing queries to retrieve data from tables There are, of course, more advanced queries and operation that can be done with SQL. It is better to move on to the more advanced operations once you are comfortable working with the basics. Thank you for reading. Please let me know if you have any feedback.
[ { "code": null, "e": 292, "s": 172, "text": "SQL is a programming language that is used to manage data stored in tabular form (i.e. tables) in relational databases." }, { "code": null, "e": 439, "s": 292, "text": "A relational database consists of multiple tables that relate to each other. The relation between tables is formed in the sense of shared columns." }, { "code": null, "e": 698, "s": 439, "text": "There are many different relational database management systems (e.g. MySQL, PostgreSQL, SQL Server). The SQL syntax they adapt might differ slightly. However, the difference is very small so if you learn how to use one, you can easily switch to another one." }, { "code": null, "e": 789, "s": 698, "text": "In this article, we will go over 30 examples that cover the following operations with SQL:" }, { "code": null, "e": 818, "s": 789, "text": "Create a database and tables" }, { "code": null, "e": 842, "s": 818, "text": "Insert data into tables" }, { "code": null, "e": 866, "s": 842, "text": "Delete data from tables" }, { "code": null, "e": 880, "s": 866, "text": "Update tables" }, { "code": null, "e": 935, "s": 880, "text": "Query tables using a wide variety of select statements" }, { "code": null, "e": 1139, "s": 935, "text": "There are many alternatives to use SQL in your machine or on the cloud. I’m currently using MySQL on a linux machine through the terminal. Another commonly used alternative is to install MySQL Workbench." }, { "code": null, "e": 1217, "s": 1139, "text": "We first connect to the MySQL server from the terminal and create a database." }, { "code": null, "e": 1239, "s": 1217, "text": "~$ sudo mysql -u root" }, { "code": null, "e": 1339, "s": 1239, "text": "We will be prompted to enter the password. We are now connected to the MySQL server in our machine." }, { "code": null, "e": 1397, "s": 1339, "text": "The following command creates a database called “retail”." }, { "code": null, "e": 1446, "s": 1397, "text": "mysql> create database retail;mysql> use retail;" }, { "code": null, "e": 1519, "s": 1446, "text": "We are not in the retail database which does not contain any tables yet." }, { "code": null, "e": 1598, "s": 1519, "text": "We will first create a table called “customer” using the create table command." }, { "code": null, "e": 1737, "s": 1598, "text": "mysql> create table customer ( -> cust_id int primary key, -> age int, -> location varchar(20), -> gender varchar(20) -> );" }, { "code": null, "e": 1873, "s": 1737, "text": "We define the name of the columns and associated data types inside the parenthesis. The cust_id column is specified as the primary key." }, { "code": null, "e": 1978, "s": 1873, "text": "Primary key is the column that uniquely identifies each row. It is like the index of a pandas dataframe." }, { "code": null, "e": 2036, "s": 1978, "text": "We will create the second table which is called “orders”." }, { "code": null, "e": 2250, "s": 2036, "text": "mysql> create table orders ( -> order_id int primary key, -> date date, -> amount decimal(5,2), -> cust_id int, -> foreign key (cust_id) references customer(cust_id) -> on delete cascade -> );" }, { "code": null, "e": 2409, "s": 2250, "text": "In the beginning, we mentioned that relational tables are related to each other by means of shared columns. A column that relates two tables is a foreign key." }, { "code": null, "e": 2516, "s": 2409, "text": "Foreign key is what relates a table to another one. Foreign key contains the primary key of another table." }, { "code": null, "e": 2676, "s": 2516, "text": "The cust_id column in the orders table is a foreign key and related the orders table to the customer table. We specify this condition while creating the table." }, { "code": null, "e": 3267, "s": 2676, "text": "In the last line, we specify another condition with “on delete cascade” phrase. It tells MySQL what to do when a row in the customer table is deleted. Each row in the orders table belongs to a customer. Each row in the customer table contains a unique customer id and represents a customer. If a row in the customer table is removed, it means we do not have that customer any more. As a result, the orders that belonged to that customer do not have an associated customer id anymore. “On delete cascade” indicates that orders that do not have an associated customer id will also be deleted." }, { "code": null, "e": 3386, "s": 3267, "text": "The retail database contains two tables now. We can view the tables exist in a database using the show tables command." }, { "code": null, "e": 3526, "s": 3386, "text": "mysql> show tables;+------------------+| Tables_in_retail |+------------------+| customer || orders |+------------------+" }, { "code": null, "e": 3582, "s": 3526, "text": "Note: The commands in SQL ends with a semi-colon (“;”)." }, { "code": null, "e": 3716, "s": 3582, "text": "The desc or describe commands provide an overview of the table in terms of column names, data types, and some additional information." }, { "code": null, "e": 4200, "s": 3716, "text": "mysql> desc orders;+----------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+--------------+------+-----+---------+-------+| order_id | int(11) | NO | PRI | NULL | || date | date | YES | | NULL | || amount | decimal(5,2) | YES | | NULL | || cust_id | int(11) | YES | MUL | NULL | |+----------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 4331, "s": 4200, "text": "We can modify existing tables. For instance, the alter table command can be used to add a new column or delete an existing column." }, { "code": null, "e": 4388, "s": 4331, "text": "Let’s add a column to the orders table called “is_sale”." }, { "code": null, "e": 4439, "s": 4388, "text": "mysql> alter table orders add is_sale varchar(20);" }, { "code": null, "e": 4506, "s": 4439, "text": "We write the column name and data type along with the add keyword." }, { "code": null, "e": 5048, "s": 4506, "text": "mysql> desc orders;+----------+--------------+------+-----+---------+-------+| Field | Type | Null | Key | Default | Extra |+----------+--------------+------+-----+---------+-------+| order_id | int(11) | NO | PRI | NULL | || date | date | YES | | NULL | || amount | decimal(5,2) | YES | | NULL | || cust_id | int(11) | YES | MUL | NULL | || is_sale | varchar(20) | YES | | NULL | |+----------+--------------+------+-----+---------+-------+" }, { "code": null, "e": 5103, "s": 5048, "text": "The is_sale column has been added to the orders table." }, { "code": null, "e": 5190, "s": 5103, "text": "The alter table can also be used to delete a column with a minor change in the syntax." }, { "code": null, "e": 5230, "s": 5190, "text": "mysql> alter table orders drop is_sale;" }, { "code": null, "e": 5336, "s": 5230, "text": "The drop keyword is used instead of the add. We also do not have to write the data type to drop a column." }, { "code": null, "e": 5437, "s": 5336, "text": "We have tables but they do not contain any data. One way to populate tables is the insert statement." }, { "code": null, "e": 5518, "s": 5437, "text": "mysql> insert into customer values ( -> 1000, 42, 'Austin', 'female' -> );" }, { "code": null, "e": 5632, "s": 5518, "text": "The specified values are inserted into the columns in the same order. Thus, we need to keep the order consistent." }, { "code": null, "e": 5701, "s": 5632, "text": "We can insert multiple rows at the same time by separating each row." }, { "code": null, "e": 5931, "s": 5701, "text": "mysql> insert into customer values -> (1001, 34, 'Austin', 'male'), -> (1002, 37, 'Houston', 'male'), -> (1003, 25, 'Austin', 'female'), -> (1004, 28, 'Houston', 'female'), -> (1005, 22, 'Dallas', 'male'), -> ;" }, { "code": null, "e": 6012, "s": 5931, "text": "I have added some more rows and also populated the orders table in the same way." }, { "code": null, "e": 6169, "s": 6012, "text": "There are other ways to populate the tables with data. For instance, we can load a csv file using the load data infile or load data local infile statements." }, { "code": null, "e": 6390, "s": 6169, "text": "The delete from statement can be used to delete existing rows in a table. We need to identify the rows to be deleted by providing a condition. For instance, the statement below will delete the row with an order id of 17." }, { "code": null, "e": 6444, "s": 6390, "text": "mysql> delete from orders -> where order_id = 17;" }, { "code": null, "e": 6519, "s": 6444, "text": "If we do not specify a condition, all rows in the given table are deleted." }, { "code": null, "e": 6595, "s": 6519, "text": "We can also update an existing row. Let’s update a row in the orders table." }, { "code": null, "e": 6816, "s": 6595, "text": "+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 24.40 | 1001 |+----------+------------+--------+---------+" }, { "code": null, "e": 6904, "s": 6816, "text": "This is the first row in the orders table. We want to change the order amount to 27.40." }, { "code": null, "e": 7232, "s": 6904, "text": "mysql> update orders -> set amount = 27.40 -> where order_id = 1;mysql> select * from orders limit 1;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 27.40 | 1001 |+----------+------------+--------+---------+" }, { "code": null, "e": 7374, "s": 7232, "text": "We write the updated values after the set keyword. The rows to be updates are identified by providing the conditions after the where keyword." }, { "code": null, "e": 7511, "s": 7374, "text": "If we want to create a table by copying the structure of an existing table, we can use the create table statement with the like keyword." }, { "code": null, "e": 7715, "s": 7511, "text": "mysql> create table orders_copy like orders;mysql> show tables;+------------------+| Tables_in_retail |+------------------+| customer || orders || orders_copy |+------------------+" }, { "code": null, "e": 7811, "s": 7715, "text": "The orders_copy table has the same structure as the orders table but does not contain any data." }, { "code": null, "e": 7930, "s": 7811, "text": "We can also create a copy of an existing table with the data by using the create table and select statements together." }, { "code": null, "e": 7989, "s": 7930, "text": "mysql> create table new_orders -> select * from orders;" }, { "code": null, "e": 8146, "s": 7989, "text": "It seems like a combination of two separate statements. The first line creates the table and the second line populates it with the data in the orders table." }, { "code": null, "e": 8215, "s": 8146, "text": "The drop table statement can be used to delete tables in a database." }, { "code": null, "e": 8397, "s": 8215, "text": "mysql> drop table orders_copy, new_orders;mysql> show tables;+------------------+| Tables_in_retail |+------------------+| customer || orders |+------------------+" }, { "code": null, "e": 8470, "s": 8397, "text": "We have successfully dropped the tables created in the previous example." }, { "code": null, "e": 8620, "s": 8470, "text": "We have two relational tables in a database. The following examples will demonstrate how we can retrieve data from these tables using select queries." }, { "code": null, "e": 8678, "s": 8620, "text": "The simplest query is to view all the columns in a table." }, { "code": null, "e": 9029, "s": 8678, "text": "mysql> select * from orders -> limit 3;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 27.40 | 1001 || 2 | 2020-10-01 | 36.20 | 1000 || 3 | 2020-10-01 | 65.45 | 1002 |+----------+------------+--------+---------+" }, { "code": null, "e": 9136, "s": 9029, "text": "The “*” selects all the columns and limit keyword puts a constraint on the number of rows to be displayed." }, { "code": null, "e": 9226, "s": 9136, "text": "We can select only some of the columns by writing the name of the columns instead of “*”." }, { "code": null, "e": 9438, "s": 9226, "text": "mysql> select order_id, amount -> from orders -> limit 3;+----------+--------+| order_id | amount |+----------+--------+| 1 | 27.40 || 2 | 36.20 || 3 | 65.45 |+----------+--------+" }, { "code": null, "e": 9584, "s": 9438, "text": "We can specify a condition for the rows to be selected using the where clause. The following query will return all the orders made on 2020–10–01." }, { "code": null, "e": 9953, "s": 9584, "text": "mysql> select * from orders -> where date = '2020-10-01';+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 1 | 2020-10-01 | 27.40 | 1001 || 2 | 2020-10-01 | 36.20 | 1000 || 3 | 2020-10-01 | 65.45 | 1002 |+----------+------------+--------+---------+" }, { "code": null, "e": 10065, "s": 9953, "text": "The where clause accepts multiple conditions. Let’s add another condition on the query in the previous example." }, { "code": null, "e": 10362, "s": 10065, "text": "mysql> select * from orders -> where date = '2020-10-01' and amount > 50;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 3 | 2020-10-01 | 65.45 | 1002 |+----------+------------+--------+---------+" }, { "code": null, "e": 10448, "s": 10362, "text": "We may want to sort the query results which can be done by using the order by clause." }, { "code": null, "e": 10540, "s": 10448, "text": "The following query will return the orders on 2020–10–02 and sort them based on the amount." }, { "code": null, "e": 11019, "s": 10540, "text": "mysql> select * from orders -> where date = '2020-10-02' -> order by amount;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 5 | 2020-10-02 | 18.80 | 1005 || 6 | 2020-10-02 | 21.15 | 1009 || 4 | 2020-10-02 | 34.40 | 1001 || 7 | 2020-10-02 | 34.40 | 1008 || 8 | 2020-10-02 | 41.10 | 1002 |+----------+------------+--------+---------+" }, { "code": null, "e": 11139, "s": 11019, "text": "The order by clause sorts the rows in ascending order by default. We can change it to descending with the desc keyword." }, { "code": null, "e": 11623, "s": 11139, "text": "mysql> select * from orders -> where date = '2020-10-02' -> order by amount desc;+----------+------------+--------+---------+| order_id | date | amount | cust_id |+----------+------------+--------+---------+| 8 | 2020-10-02 | 41.10 | 1002 || 4 | 2020-10-02 | 34.40 | 1001 || 7 | 2020-10-02 | 34.40 | 1008 || 6 | 2020-10-02 | 21.15 | 1009 || 5 | 2020-10-02 | 18.80 | 1005 |+----------+------------+--------+---------+" }, { "code": null, "e": 11788, "s": 11623, "text": "SQL is a versatile language which can also be used as a data analysis tool. It provides many functions to analyze and transform data while querying from a database." }, { "code": null, "e": 11862, "s": 11788, "text": "For instance, we can count the number of unique days in the orders table." }, { "code": null, "e": 11995, "s": 11862, "text": "mysql> select count(distinct(date)) as day_count -> from orders;+-----------+| day_count |+-----------+| 4 |+-----------+" }, { "code": null, "e": 12182, "s": 11995, "text": "The orders table contain orders in 4 different days. The “as” keyword is used to rename the column in the query result. Otherwise the name of the column would be “count(distinct(date))”." }, { "code": null, "e": 12342, "s": 12182, "text": "There are 4 different days in the orders table. We can also find out how many orders exist for each day. The group by clause will help us accomplish this task." }, { "code": null, "e": 12656, "s": 12342, "text": "mysql> select date, count(order_id) as order_count -> from orders -> group by date;+------------+-------------+| date | order_count |+------------+-------------+| 2020-10-01 | 3 || 2020-10-02 | 5 || 2020-10-03 | 6 || 2020-10-04 | 2 |+------------+-------------+" }, { "code": null, "e": 12711, "s": 12656, "text": "We count the orders and group them by the date column." }, { "code": null, "e": 12833, "s": 12711, "text": "We will calculate the average order amount in each day and order the results based on average amount in descending order." }, { "code": null, "e": 13160, "s": 12833, "text": "mysql> select date, avg(amount) -> from orders -> group by date -> order by avg(amount) desc;+------------+-------------+| date | avg(amount) |+------------+-------------+| 2020-10-01 | 43.016667 || 2020-10-04 | 42.150000 || 2020-10-03 | 37.025000 || 2020-10-02 | 29.970000 |+------------+-------------+" }, { "code": null, "e": 13273, "s": 13160, "text": "We want to modify the query in the previous example and only include days with an average amount higher than 30." }, { "code": null, "e": 13602, "s": 13273, "text": "mysql> select date, avg(amount) -> from orders -> group by date -> having avg(amount) > 30 -> order by avg(amount) desc;+------------+-------------+| date | avg(amount) |+------------+-------------+| 2020-10-01 | 43.016667 || 2020-10-04 | 42.150000 || 2020-10-03 | 37.025000 |+------------+-------------+" }, { "code": null, "e": 13769, "s": 13602, "text": "It is important to note that the order of the statements in the query matters. For instance, it gives an error if we put the order by clause before the having clause." }, { "code": null, "e": 13828, "s": 13769, "text": "We want to find out the maximum order amount for each day." }, { "code": null, "e": 14123, "s": 13828, "text": "mysql> select date, max(amount) -> from orders -> group by date;+------------+-------------+| date | max(amount) |+------------+-------------+| 2020-10-01 | 65.45 || 2020-10-02 | 41.10 || 2020-10-03 | 80.20 || 2020-10-04 | 50.10 |+------------+-------------+" }, { "code": null, "e": 14451, "s": 14123, "text": "We want to combine multiple aggregate functions in a select statement. To demonstrate it, let’s elaborate on the previous example. We want to see the difference between the maximum order and minimum order of each customer. We also want to sort the results based on the difference in ascending order and display the first three." }, { "code": null, "e": 14720, "s": 14451, "text": "mysql> select cust_id, max(amount) - min(amount) as dif -> from orders -> group by cust_id -> order by dif desc -> limit 3;+---------+-------+| cust_id | dif |+---------+-------+| 1007 | 46.00 || 1009 | 28.95 || 1002 | 24.35 |+---------+-------+" }, { "code": null, "e": 14807, "s": 14720, "text": "The dif column is obtained by substracting the minimum amount from the maximum amount." }, { "code": null, "e": 14997, "s": 14807, "text": "We are switching to the customer table now. Let’s find out how many female and male customers we have in each city. We need to write both location and gender columns in the group by clause." }, { "code": null, "e": 15477, "s": 14997, "text": "mysql> select location, gender, count(cust_id) -> from customer -> group by location, gender;+----------+--------+----------------+| location | gender | count(cust_id) |+----------+--------+----------------+| Austin | female | 2 || Austin | male | 1 || Dallas | female | 2 || Dallas | male | 2 || Houston | female | 2 || Houston | male | 1 |+----------+--------+----------------+" }, { "code": null, "e": 15615, "s": 15477, "text": "The customer and orders tables are related to each other based on the cust_id column. We can query data from both tables using SQL joins." }, { "code": null, "e": 15688, "s": 15615, "text": "We want to see average order amount for each city in the customer table." }, { "code": null, "e": 16030, "s": 15688, "text": "mysql> select customer.location, avg(orders.amount) as avg -> from customer -> join orders -> on customer.cust_id = orders.cust_id -> group by customer.location;+----------+-----------+| location | avg |+----------+-----------+| Austin | 33.333333 || Dallas | 34.591667 || Houston | 44.450000 |+----------+-----------+" }, { "code": null, "e": 16273, "s": 16030, "text": "Since we select columns from two different tables, the column names are specified with associated table name. The second, third, and fourth line of the query above joins the customer and orders table based on the cust_id column in each table." }, { "code": null, "e": 16449, "s": 16273, "text": "Please note that the column names do not have to be the same. Whatever column name we provide with the “on” keyword, the comparison or matching is done based on these columns." }, { "code": null, "e": 16526, "s": 16449, "text": "We want to see the average age of customers who have an order on 2020–10–03." }, { "code": null, "e": 16725, "s": 16526, "text": "mysql> select avg(c.age) as avg_age -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where o.date = '2020-10-03';+---------+| avg_age |+---------+| 30.0000 |+---------+" }, { "code": null, "e": 16840, "s": 16725, "text": "We can use aliases for the table names as well. It comes in handy when we need to type the table names many times." }, { "code": null, "e": 16917, "s": 16840, "text": "We want to see the location of customer who has the highest amount of order." }, { "code": null, "e": 17194, "s": 16917, "text": "mysql> select c.location, o.amount -> from customer c -> join orders o -> on c.cust_id = o.cust_id -> where o.amount = (select max(amount) from orders) -> ;+----------+--------+| location | amount |+----------+--------+| Dallas | 80.20 |+----------+--------+" }, { "code": null, "e": 17342, "s": 17194, "text": "We have a nested select statement in this query. The condition on the amount is calculated using a separate select statement from the orders table." }, { "code": null, "e": 17456, "s": 17342, "text": "This task can be completed in a different way. I have chosen this method to introduce the idea of nested queries." }, { "code": null, "e": 17581, "s": 17456, "text": "I believe the 30 examples in this article provide a comprehensive introduction to SQL. We have covered the following topics:" }, { "code": null, "e": 17624, "s": 17581, "text": "Creating a database with relational tables" }, { "code": null, "e": 17641, "s": 17624, "text": "Modifying tables" }, { "code": null, "e": 17668, "s": 17641, "text": "Inserting data into tables" }, { "code": null, "e": 17694, "s": 17668, "text": "Deleting data from tables" }, { "code": null, "e": 17739, "s": 17694, "text": "Writing queries to retrieve data from tables" }, { "code": null, "e": 17930, "s": 17739, "text": "There are, of course, more advanced queries and operation that can be done with SQL. It is better to move on to the more advanced operations once you are comfortable working with the basics." } ]
Analyzing Climate Patterns with Self-Organizing Maps (SOMs) | by Haihan Lan | Towards Data Science
In this article, we’ll look at: The Self-Organizing Map (SOM), and how it can be used in dimensionality reduction and unsupervised learning Interpreting the visualizations of a trained SOM for exploratory data analysis Applications of SOMs to clustering climate patterns in the province of British Columbia, Canada Links to my other articles: Tensorflow and Custom Loss functionsRandom forestsSoftmax classification Tensorflow and Custom Loss functions Random forests Softmax classification Back when I was first getting started in learning about neural nets, I came across this curious invention called the Kohonen map, or more commonly called the Self-Organizing Map or SOM in literature. This neural network, inspired by the sensory activation patterns of the human cerebral cortex, trained unsupervised using a simple heuristic method, and was capable of discovering hidden non-linear structure in high dimensional data. Recently I came across a few interesting articles by some climatologists analyzing and predicting weather and climate (a notoriously difficult task) using SOMs, and I thought I’d share with you this interesting unsupervised technique. Basically, an SOM is a discrete, planar grid of neurons — the hidden layer, sometimes called the Kohnen layer — fed by an input layer: Each hidden layer neuron has several ‘neighbor’ neurons (the maximum immediate number of neighbors of a single cell can be six as in the hexagonal grid above, or four for a square grid). We define the ‘distance’ between each neuron and its neighbors as the Euclidean distance between the input-to-hidden layer weights of each neuron. The input-to-hidden layer weight of each hidden neuron is also sometimes called a codebook vector. The distance that we have defined will become important later, as it encodes low-dimensional information about the original dataset. In the diagram above, each hidden layer neuron would have a weight vector with n components (i.e. the input is densely connected to the hidden layer). So how do we train this network? The training procedure is actually quite simple and involves no gradient calculations: Initialize hidden neuron weights to small random values or use PCA weight initializationFeed data row xi to input layerIterate through each neuron in hidden layer and find the Best Matching Unit (BMU), i.e. the neuron that has the smallest Euclidean distance or metric with the data row xiApply a weight update to the BMU and it’s neighboring neurons. The BMU’s neighbor neurons are calculated using a neighborhood function ΦShrink the neighborhood function ΦRepeat steps 2 to 5 until iteration limit reached or convergence (the average codebook vector distance between all neurons and all data is smaller than some threshold) Initialize hidden neuron weights to small random values or use PCA weight initialization Feed data row xi to input layer Iterate through each neuron in hidden layer and find the Best Matching Unit (BMU), i.e. the neuron that has the smallest Euclidean distance or metric with the data row xi Apply a weight update to the BMU and it’s neighboring neurons. The BMU’s neighbor neurons are calculated using a neighborhood function Φ Shrink the neighborhood function Φ Repeat steps 2 to 5 until iteration limit reached or convergence (the average codebook vector distance between all neurons and all data is smaller than some threshold) The above algorithm is called competitive learning, and is quite similar in spirit to other heuristics based algorithms such as genetic algorithms and particle swarm methods. A full description of the algorithm is available here. The basic idea of the SOM is to ‘fill the space’ of the underlying data as illustrated by the figure below: The competitive learning algorithm is typically fast compared to backpropagation on a feedforward networks of similar number of neurons, but can slow down if your SOM grid is very large (104 or more neurons). SOMs belong to a class of techniques called Non-Linear Dimensionality Reduction (NLDR). Dimesionality reduction techniques (PCA, t-SNE, etc.) are typically used for visualization and interpretation, as well as variable selection. SOMs are better suited for the former application, fitted SOMs can be further analyzed to obtain low-dimensional visualizable and interpretable results to present to your boss, scrum master, marketing team, or your significant other. Furthermore, clustering techniques such as K-means can be applied to the fitted SOM grid, and from that robust clusterings of the input can be obtained. Typically K-means on top of SOM performs a lot better than regular K-means and can sometimes discover patterns of non-linear interactions that are hidden. Let’s now play around with some climate data and see what the SOM can do. The original SOMPY repo used for the code examples below is available here. SOMPY is a good starting package for Python, but in case you’re also fluent in R check out the kohonen package, it has some very nice visualization tools (also see here for the tutorial on using the kohonen package for R). The repo containing all the modifications of the SOMPY code for the tasks below with the climate data is here. The main.py script file that runs the code is at https://github.com/hhl60492/SOMPY_robust_clustering/tree/master/sompy/examples. Historic climate data (monthly summaries) from Jan. 2009 to Dec. 2017 of British Columbia (BC), Canada was collected from http://climate.weather.gc.ca/prods_servs/cdn_climate_summary_e.html. Each CSV file contains the monthly summary of a climate data (such as median, min/max monthly temperature, monthly precipitation amount) and the Latitude and Longitude of the weather station that recorded the data . Each unique weather station gives a single row, and there are 300 or so weather stations in each CSV. We’ll keep it simpe for now and use the columns Latitude, Longitude, Median Temperature, Max Temperature, Min Temperature and Precipitation. The columns were extracted and coerced to float types. Rows with any NaNs were dropped. SOMPY automatically calculates the size of the SOM grid by calculating the eigenvalues of the data matrix. The training on 20621 rows of data took about 5 seconds. The first visualization to make note of are the component plane heatmaps. Each heatmap represents the intensity of a single feature or data column as learned by the SOM grid. Note the heatmap is discretized and each ‘block’ in each subfigure is a unique neuron, the neurons have the same position across all subfigures, i.e. the block on the very top left of the latitude subfigure is the same neuron in the longitude subfigure and the monthly median temperature subgfigure and so on. In general similar heatmaps in different component planes represent correlation of features, dissimilarity represents negligible correlation and inversion represents anti-correlation. Also note that the fitted SOM will represent the features across all months of the year for the entire range of years, i.e. the 9 year average, as sequential data from the months of Jan. to Dec. across 9 years was supplied. Using the previous facts and the latitude and longitude information, we can see that: The monthly maximum temperature occurs across a variety of latitudes and longitudes, including lat. 49° N and long. 120 °–124° W; this is a large swath of Southern BC close to the US-Canada border, including the southern tip of Vancouver Island, Metro Vancouver, Fraser Valley, and stretching all the way to the Okanagan The lat. 49° N and long. 120°–124° W area also gets the most precipitation. The size of the regions in the component plane heatmaps of latitude and longitude show that there is a heavy concentration of weather stations in the region of 49°-50° N and 123°–124° W, where there is the highest concentration of population (The following plot of the latitudes and longitudes of all the weather stations in each CSV file seems to confirm this observation) (Note: to verify the geography it’s a good idea to actually extract the lat. and long. data from the fitted SOM in Python and label the cells/neurons in the other component plane heatmaps with them.) Monthly median temperature is correlated with monthly max temperature, and to a lesser extent monthly median temperature. Precipitation seems anti-correlated with monthly median and max temperature (as a local, I can confirm we have way less rain when it is hot and vice versa–the climate of the Pacific Northwest is such that there is tremendous precipitation during the Late Autumn, Winter and Spring seasons when the temperature is low, and little to no precipitation during the Summer when temperature is high). The next visualization we can do is called the U-matrix. The U-matrix is also a heatmap but can be interpreted like a topographic map (a map that shows the elevation contours across a region) across our SOM grid. The ‘hills’ in the U-matrix represent large distances between neighbors and vice versa for valleys. The U-matrix gives us a sense of the landscape of the SOM grid, and what the neighborhoods of the neurons are. It helps us visually see what potential clusterings there are in the SOM grid itself, which is a good sanity check for the result of the K-means clustering which we are going to run on grid. Since K-means is a bit naive on the optimal number of clusters, we’ll use the ‘elbow’ method combined with the Sum of Squared Errors (SSE) to find the optimal number of clusters k. The algorithm for SSE computation is as follows: For k = 2 to k_end:compute K-means on dataset XFor each cluster n:Compute the L2-norm of the vector difference between each element in cluster n and cluster n’s centroid, and add this to the total SSE For k = 2 to k_end: compute K-means on dataset X For each cluster n: Compute the L2-norm of the vector difference between each element in cluster n and cluster n’s centroid, and add this to the total SSE The resulting plot of SSEs vs. different k’s looks something like the following The elbow point can be found analytically by finding the index of the maximum value of the first difference of the above plot, and adding 1. Unfortunately, the K-means algorithm is not too robust and gives different elbow curves for different runs, so bootstrapping and repeating the elbow/SSE plot analysis over many bootstrap samples will give a better estimate for the optimal k. All the code to do this is in the following gist, the cluster() method in the SOMFactory class (in sompy.py) is modified to implement the above. For this particular SOM, the maximum value of the first difference of the SSEs averaged across 20 bootstrap samples was 17 and so the optimal k should be 18. Repeating the runs gives use consistent results for the optimal k now, so that’s great. Running the final K-means with this k gives the following clustering: This resembles the U-matrix plot somewhat, so we are not too far off in terms of the true clustering of the SOM grid. There’s still a couple of things left to do before we can put on our jackets and go home. Let’s see the features of each cluster centroid (in K-means the centroid is representative of the average features in a cluster), predict which weather station belongs in which cluster, and put the clustered weather stations on a map. We use gmplot and the Google Maps API to do map overlays. By the way, gmplot is woefully outdated and requires some patching to make it work with the current Google Maps API, you also need a valid Google Maps API Key in order to access the API. The gist for the gmplot code modifications is here. Centroid 0[ 51.38661738 -125.27254198 7.51493849 16.8132888 -1.17574106 67.95416645]Centroid 1[ 50.61259827 -126.25917862 6.32184038 14.17993615 -1.63282112 340.64034668]Centroid 2[ 50.42396495 -125.2544494 7.2744194 16.09718498 -1.19140013 222.65626168]Centroid 3[ 50.42534148 -126.39001822 6.72726471 14.53652612 -1.31210139 507.65982791]Centroid 4[ 49.89467361 -122.37195052 16.63158605 29.73554202 5.95873865 28.06162618]Centroid 5[ 52.27917741 -121.73550782 -3.83946568 8.19646576 -19.93363911 45.30064963]Centroid 6[ 50.2945556 -125.21241436 9.15306962 18.32174182 0.93638661 119.43331396]Centroid 7[ 50.70282538 -125.32884059 8.00965749 17.614526 -0.77992491 151.77106456]Centroid 8[ 50.31580334 -126.23307623 6.5871719 14.64225657 -1.44068436 660.70782628]Centroid 9[ 50.28874072 -125.06866063 7.49467144 16.55379438 -0.84254229 251.73801799]Centroid 10[ 50.4262205 -126.2629756 6.58541814 14.36302394 -1.36671652 399.90931304]Centroid 11[ 50.35982435 -125.51021147 6.32659523 14.73932271 -1.89873252 294.050496 ]Centroid 12[ 51.24356927 -121.64231971 6.18712464 18.67948989 -5.48058692 36.06758652]Centroid 13[ 50.75675998 -125.60116426 7.48408728 16.37144962 -0.95604598 190.18377378]Centroid 14[ 51.1337961 -124.85444455 7.9966279 17.1295218 -0.56629512 94.65084155]Centroid 15[ 50.12150383 -126.04955706 6.7603695 14.43437023 -1.13385479 461.59884165]Centroid 16[ 50.72982522 -126.73419985 6.88866959 14.84315741 -1.12018377 586.45036101]Centroid 17[ 51.44904147 -122.37356247 12.74453517 26.10130055 1.58123601 50.9674971 ] The components of each centroid correspond to Latitude, Longitude, Median Temperature, Max Temperature, Min Temperature and total Precipitation, across all months of the year. You can play around with the interactive centroids map here: https://github.com/hhl60492/SOMPY_robust_clustering/blob/master/sompy/examples/centroids_map.html (download to your machine and open with a browser). One can further analyze the SOM and overlay for example the cluster that each weather station belongs to on the map (one way would be to average the data for each weather stations across all years 2009–2017 and , or perhaps re-fit the SOM for yearly or monthly data only to see the respective yearly and monthly patterns. As well, unfortunately there is a a heavy distribution bias in the location of the weather stations, so some other features to consider would for example be atmospheric pressure measurements, radar data or physical elevation data which have less geographic bias. To get an idea of how the climatologists are using SOMs in their models, have a look at: http://onlinelibrary.wiley.com/doi/10.1029/2009JD011706/full We have seen how SOMs can be used for data visualization, discovering correlations and patterns in the data, and performing clustering of the data. To extract more complex patterns, you can feed more input features to the SOM, or partition the features across some dimension such as time. Another thing to note: running K-means clustering should be done with bootstrapped ensembles and the cluster labels matched with something like the Hungarian algorithm, so that stable, consistent clusters are found. Anyways, have fun playing around the SOMs and doing the clusterings.
[ { "code": null, "e": 203, "s": 171, "text": "In this article, we’ll look at:" }, { "code": null, "e": 311, "s": 203, "text": "The Self-Organizing Map (SOM), and how it can be used in dimensionality reduction and unsupervised learning" }, { "code": null, "e": 390, "s": 311, "text": "Interpreting the visualizations of a trained SOM for exploratory data analysis" }, { "code": null, "e": 486, "s": 390, "text": "Applications of SOMs to clustering climate patterns in the province of British Columbia, Canada" }, { "code": null, "e": 514, "s": 486, "text": "Links to my other articles:" }, { "code": null, "e": 587, "s": 514, "text": "Tensorflow and Custom Loss functionsRandom forestsSoftmax classification" }, { "code": null, "e": 624, "s": 587, "text": "Tensorflow and Custom Loss functions" }, { "code": null, "e": 639, "s": 624, "text": "Random forests" }, { "code": null, "e": 662, "s": 639, "text": "Softmax classification" }, { "code": null, "e": 1331, "s": 662, "text": "Back when I was first getting started in learning about neural nets, I came across this curious invention called the Kohonen map, or more commonly called the Self-Organizing Map or SOM in literature. This neural network, inspired by the sensory activation patterns of the human cerebral cortex, trained unsupervised using a simple heuristic method, and was capable of discovering hidden non-linear structure in high dimensional data. Recently I came across a few interesting articles by some climatologists analyzing and predicting weather and climate (a notoriously difficult task) using SOMs, and I thought I’d share with you this interesting unsupervised technique." }, { "code": null, "e": 1466, "s": 1331, "text": "Basically, an SOM is a discrete, planar grid of neurons — the hidden layer, sometimes called the Kohnen layer — fed by an input layer:" }, { "code": null, "e": 2183, "s": 1466, "text": "Each hidden layer neuron has several ‘neighbor’ neurons (the maximum immediate number of neighbors of a single cell can be six as in the hexagonal grid above, or four for a square grid). We define the ‘distance’ between each neuron and its neighbors as the Euclidean distance between the input-to-hidden layer weights of each neuron. The input-to-hidden layer weight of each hidden neuron is also sometimes called a codebook vector. The distance that we have defined will become important later, as it encodes low-dimensional information about the original dataset. In the diagram above, each hidden layer neuron would have a weight vector with n components (i.e. the input is densely connected to the hidden layer)." }, { "code": null, "e": 2303, "s": 2183, "text": "So how do we train this network? The training procedure is actually quite simple and involves no gradient calculations:" }, { "code": null, "e": 2930, "s": 2303, "text": "Initialize hidden neuron weights to small random values or use PCA weight initializationFeed data row xi to input layerIterate through each neuron in hidden layer and find the Best Matching Unit (BMU), i.e. the neuron that has the smallest Euclidean distance or metric with the data row xiApply a weight update to the BMU and it’s neighboring neurons. The BMU’s neighbor neurons are calculated using a neighborhood function ΦShrink the neighborhood function ΦRepeat steps 2 to 5 until iteration limit reached or convergence (the average codebook vector distance between all neurons and all data is smaller than some threshold)" }, { "code": null, "e": 3019, "s": 2930, "text": "Initialize hidden neuron weights to small random values or use PCA weight initialization" }, { "code": null, "e": 3051, "s": 3019, "text": "Feed data row xi to input layer" }, { "code": null, "e": 3222, "s": 3051, "text": "Iterate through each neuron in hidden layer and find the Best Matching Unit (BMU), i.e. the neuron that has the smallest Euclidean distance or metric with the data row xi" }, { "code": null, "e": 3359, "s": 3222, "text": "Apply a weight update to the BMU and it’s neighboring neurons. The BMU’s neighbor neurons are calculated using a neighborhood function Φ" }, { "code": null, "e": 3394, "s": 3359, "text": "Shrink the neighborhood function Φ" }, { "code": null, "e": 3562, "s": 3394, "text": "Repeat steps 2 to 5 until iteration limit reached or convergence (the average codebook vector distance between all neurons and all data is smaller than some threshold)" }, { "code": null, "e": 3900, "s": 3562, "text": "The above algorithm is called competitive learning, and is quite similar in spirit to other heuristics based algorithms such as genetic algorithms and particle swarm methods. A full description of the algorithm is available here. The basic idea of the SOM is to ‘fill the space’ of the underlying data as illustrated by the figure below:" }, { "code": null, "e": 4109, "s": 3900, "text": "The competitive learning algorithm is typically fast compared to backpropagation on a feedforward networks of similar number of neurons, but can slow down if your SOM grid is very large (104 or more neurons)." }, { "code": null, "e": 4955, "s": 4109, "text": "SOMs belong to a class of techniques called Non-Linear Dimensionality Reduction (NLDR). Dimesionality reduction techniques (PCA, t-SNE, etc.) are typically used for visualization and interpretation, as well as variable selection. SOMs are better suited for the former application, fitted SOMs can be further analyzed to obtain low-dimensional visualizable and interpretable results to present to your boss, scrum master, marketing team, or your significant other. Furthermore, clustering techniques such as K-means can be applied to the fitted SOM grid, and from that robust clusterings of the input can be obtained. Typically K-means on top of SOM performs a lot better than regular K-means and can sometimes discover patterns of non-linear interactions that are hidden. Let’s now play around with some climate data and see what the SOM can do." }, { "code": null, "e": 5254, "s": 4955, "text": "The original SOMPY repo used for the code examples below is available here. SOMPY is a good starting package for Python, but in case you’re also fluent in R check out the kohonen package, it has some very nice visualization tools (also see here for the tutorial on using the kohonen package for R)." }, { "code": null, "e": 5494, "s": 5254, "text": "The repo containing all the modifications of the SOMPY code for the tasks below with the climate data is here. The main.py script file that runs the code is at https://github.com/hhl60492/SOMPY_robust_clustering/tree/master/sompy/examples." }, { "code": null, "e": 6003, "s": 5494, "text": "Historic climate data (monthly summaries) from Jan. 2009 to Dec. 2017 of British Columbia (BC), Canada was collected from http://climate.weather.gc.ca/prods_servs/cdn_climate_summary_e.html. Each CSV file contains the monthly summary of a climate data (such as median, min/max monthly temperature, monthly precipitation amount) and the Latitude and Longitude of the weather station that recorded the data . Each unique weather station gives a single row, and there are 300 or so weather stations in each CSV." }, { "code": null, "e": 6339, "s": 6003, "text": "We’ll keep it simpe for now and use the columns Latitude, Longitude, Median Temperature, Max Temperature, Min Temperature and Precipitation. The columns were extracted and coerced to float types. Rows with any NaNs were dropped. SOMPY automatically calculates the size of the SOM grid by calculating the eigenvalues of the data matrix." }, { "code": null, "e": 6470, "s": 6339, "text": "The training on 20621 rows of data took about 5 seconds. The first visualization to make note of are the component plane heatmaps." }, { "code": null, "e": 7375, "s": 6470, "text": "Each heatmap represents the intensity of a single feature or data column as learned by the SOM grid. Note the heatmap is discretized and each ‘block’ in each subfigure is a unique neuron, the neurons have the same position across all subfigures, i.e. the block on the very top left of the latitude subfigure is the same neuron in the longitude subfigure and the monthly median temperature subgfigure and so on. In general similar heatmaps in different component planes represent correlation of features, dissimilarity represents negligible correlation and inversion represents anti-correlation. Also note that the fitted SOM will represent the features across all months of the year for the entire range of years, i.e. the 9 year average, as sequential data from the months of Jan. to Dec. across 9 years was supplied. Using the previous facts and the latitude and longitude information, we can see that:" }, { "code": null, "e": 7696, "s": 7375, "text": "The monthly maximum temperature occurs across a variety of latitudes and longitudes, including lat. 49° N and long. 120 °–124° W; this is a large swath of Southern BC close to the US-Canada border, including the southern tip of Vancouver Island, Metro Vancouver, Fraser Valley, and stretching all the way to the Okanagan" }, { "code": null, "e": 7772, "s": 7696, "text": "The lat. 49° N and long. 120°–124° W area also gets the most precipitation." }, { "code": null, "e": 8146, "s": 7772, "text": "The size of the regions in the component plane heatmaps of latitude and longitude show that there is a heavy concentration of weather stations in the region of 49°-50° N and 123°–124° W, where there is the highest concentration of population (The following plot of the latitudes and longitudes of all the weather stations in each CSV file seems to confirm this observation)" }, { "code": null, "e": 8346, "s": 8146, "text": "(Note: to verify the geography it’s a good idea to actually extract the lat. and long. data from the fitted SOM in Python and label the cells/neurons in the other component plane heatmaps with them.)" }, { "code": null, "e": 8468, "s": 8346, "text": "Monthly median temperature is correlated with monthly max temperature, and to a lesser extent monthly median temperature." }, { "code": null, "e": 8862, "s": 8468, "text": "Precipitation seems anti-correlated with monthly median and max temperature (as a local, I can confirm we have way less rain when it is hot and vice versa–the climate of the Pacific Northwest is such that there is tremendous precipitation during the Late Autumn, Winter and Spring seasons when the temperature is low, and little to no precipitation during the Summer when temperature is high)." }, { "code": null, "e": 9175, "s": 8862, "text": "The next visualization we can do is called the U-matrix. The U-matrix is also a heatmap but can be interpreted like a topographic map (a map that shows the elevation contours across a region) across our SOM grid. The ‘hills’ in the U-matrix represent large distances between neighbors and vice versa for valleys." }, { "code": null, "e": 9707, "s": 9175, "text": "The U-matrix gives us a sense of the landscape of the SOM grid, and what the neighborhoods of the neurons are. It helps us visually see what potential clusterings there are in the SOM grid itself, which is a good sanity check for the result of the K-means clustering which we are going to run on grid. Since K-means is a bit naive on the optimal number of clusters, we’ll use the ‘elbow’ method combined with the Sum of Squared Errors (SSE) to find the optimal number of clusters k. The algorithm for SSE computation is as follows:" }, { "code": null, "e": 9908, "s": 9707, "text": "For k = 2 to k_end:compute K-means on dataset XFor each cluster n:Compute the L2-norm of the vector difference between each element in cluster n and cluster n’s centroid, and add this to the total SSE" }, { "code": null, "e": 9928, "s": 9908, "text": "For k = 2 to k_end:" }, { "code": null, "e": 9957, "s": 9928, "text": "compute K-means on dataset X" }, { "code": null, "e": 9977, "s": 9957, "text": "For each cluster n:" }, { "code": null, "e": 10112, "s": 9977, "text": "Compute the L2-norm of the vector difference between each element in cluster n and cluster n’s centroid, and add this to the total SSE" }, { "code": null, "e": 10192, "s": 10112, "text": "The resulting plot of SSEs vs. different k’s looks something like the following" }, { "code": null, "e": 10720, "s": 10192, "text": "The elbow point can be found analytically by finding the index of the maximum value of the first difference of the above plot, and adding 1. Unfortunately, the K-means algorithm is not too robust and gives different elbow curves for different runs, so bootstrapping and repeating the elbow/SSE plot analysis over many bootstrap samples will give a better estimate for the optimal k. All the code to do this is in the following gist, the cluster() method in the SOMFactory class (in sompy.py) is modified to implement the above." }, { "code": null, "e": 11036, "s": 10720, "text": "For this particular SOM, the maximum value of the first difference of the SSEs averaged across 20 bootstrap samples was 17 and so the optimal k should be 18. Repeating the runs gives use consistent results for the optimal k now, so that’s great. Running the final K-means with this k gives the following clustering:" }, { "code": null, "e": 11154, "s": 11036, "text": "This resembles the U-matrix plot somewhat, so we are not too far off in terms of the true clustering of the SOM grid." }, { "code": null, "e": 11776, "s": 11154, "text": "There’s still a couple of things left to do before we can put on our jackets and go home. Let’s see the features of each cluster centroid (in K-means the centroid is representative of the average features in a cluster), predict which weather station belongs in which cluster, and put the clustered weather stations on a map. We use gmplot and the Google Maps API to do map overlays. By the way, gmplot is woefully outdated and requires some patching to make it work with the current Google Maps API, you also need a valid Google Maps API Key in order to access the API. The gist for the gmplot code modifications is here." }, { "code": null, "e": 13495, "s": 11776, "text": "Centroid 0[ 51.38661738 -125.27254198 7.51493849 16.8132888 -1.17574106 67.95416645]Centroid 1[ 50.61259827 -126.25917862 6.32184038 14.17993615 -1.63282112 340.64034668]Centroid 2[ 50.42396495 -125.2544494 7.2744194 16.09718498 -1.19140013 222.65626168]Centroid 3[ 50.42534148 -126.39001822 6.72726471 14.53652612 -1.31210139 507.65982791]Centroid 4[ 49.89467361 -122.37195052 16.63158605 29.73554202 5.95873865 28.06162618]Centroid 5[ 52.27917741 -121.73550782 -3.83946568 8.19646576 -19.93363911 45.30064963]Centroid 6[ 50.2945556 -125.21241436 9.15306962 18.32174182 0.93638661 119.43331396]Centroid 7[ 50.70282538 -125.32884059 8.00965749 17.614526 -0.77992491 151.77106456]Centroid 8[ 50.31580334 -126.23307623 6.5871719 14.64225657 -1.44068436 660.70782628]Centroid 9[ 50.28874072 -125.06866063 7.49467144 16.55379438 -0.84254229 251.73801799]Centroid 10[ 50.4262205 -126.2629756 6.58541814 14.36302394 -1.36671652 399.90931304]Centroid 11[ 50.35982435 -125.51021147 6.32659523 14.73932271 -1.89873252 294.050496 ]Centroid 12[ 51.24356927 -121.64231971 6.18712464 18.67948989 -5.48058692 36.06758652]Centroid 13[ 50.75675998 -125.60116426 7.48408728 16.37144962 -0.95604598 190.18377378]Centroid 14[ 51.1337961 -124.85444455 7.9966279 17.1295218 -0.56629512 94.65084155]Centroid 15[ 50.12150383 -126.04955706 6.7603695 14.43437023 -1.13385479 461.59884165]Centroid 16[ 50.72982522 -126.73419985 6.88866959 14.84315741 -1.12018377 586.45036101]Centroid 17[ 51.44904147 -122.37356247 12.74453517 26.10130055 1.58123601 50.9674971 ]" }, { "code": null, "e": 13671, "s": 13495, "text": "The components of each centroid correspond to Latitude, Longitude, Median Temperature, Max Temperature, Min Temperature and total Precipitation, across all months of the year." }, { "code": null, "e": 13882, "s": 13671, "text": "You can play around with the interactive centroids map here: https://github.com/hhl60492/SOMPY_robust_clustering/blob/master/sompy/examples/centroids_map.html (download to your machine and open with a browser)." }, { "code": null, "e": 14467, "s": 13882, "text": "One can further analyze the SOM and overlay for example the cluster that each weather station belongs to on the map (one way would be to average the data for each weather stations across all years 2009–2017 and , or perhaps re-fit the SOM for yearly or monthly data only to see the respective yearly and monthly patterns. As well, unfortunately there is a a heavy distribution bias in the location of the weather stations, so some other features to consider would for example be atmospheric pressure measurements, radar data or physical elevation data which have less geographic bias." }, { "code": null, "e": 14617, "s": 14467, "text": "To get an idea of how the climatologists are using SOMs in their models, have a look at: http://onlinelibrary.wiley.com/doi/10.1029/2009JD011706/full" } ]
Block swap algorithm for array rotation in C++
The block swap algorithm for array rotation is an efficient algorithm that is used for array rotation. It can do your work in O(n) time complexity. So, in array rotation, we are given an array arr[] of size n and a number k that define the no. of the element to be rotated. Let’s see an example on array rotations − Input − arr[] = {4, 6, 1, 8, 9, 2}, k = 2 (number of rotations.) Output − {1, 8, 9, 2, 4, 6} Explanation − On rotation, we will shift the one element to the last position and shift the next elements to one position. Element at index 0 will be shifted to index n-1. And the rest of the elements are shifted to the previous index. The block swap algorithm is used to perform array rotations perfectly. Step 1 − Divide the array two sub-arrays with k as division point. Let them be X = arr[0...k-1] and Y = arr[k...n-1]. Step 2 − Follow the below steps until the size of X and Y are the same. Step 2.1 − If the size of X > Y, divide X into two portions X1 and X2 such that size of X1 is equal to the size of Y. Then swap the sub-array X1 and Y. This will change the original array formation from X1X2Y to YX2X1. Step 2.2 − If the size of Y > X, divide Y into two portions Y1 and Y2 such that the size of Y2 is equal to the size of X. Then swap the subarray X and Y2. This will change the original array formation from XY1Y2 to Y2Y1X. Step 3 − When the size of X and Y are the same, swap them. This algorithm needs a repetitive call to the same chunk of code. This repetitive call can be achieved using two approaches. They are the recursive approach and iterative approach. we will discuss the approach using programs. Program to illustrate Recursive Approach − #include <iostream> using namespace std; void swapSubArray(int arr[], int start, int end, intk){ int temp; for(int i = 0; i < k; i++){ temp = arr[start + i]; arr[start + i] = arr[end + i]; arr[end + i] = temp; } } void blockSwapAlgo(int arr[], int k, int n) { if(k == 0 || k == n) return; if(k<(n-k)) { swapSubArray(arr, 0, (n-k), k); blockSwapAlgo(arr, k, (n-k)); } else if(k>(n-k)){ swapSubArray(arr, 0, k, (n-k)); blockSwapAlgo((arr+n-k), (2*k-n), k); } else{ swapSubArray(arr, 0, (n-k), k); return; } } int main() { int arr[] = {4, 6, 1, 8, 9, 2}; int size = sizeof(arr) / sizeof(arr[0]); int k = 3; cout<<"Array before rotations :\t"; for(int i = 0; i<size; i++) cout<<arr[i]<<" "; blockSwapAlgo(arr, k, size); cout<<"\nArray after rotating "<<k<<" times :\t"; for(int i = 0; i<size; i++) cout<<arr[i]<<" "; return 0; } Array before rotations : 4 6 1 8 9 2 Array after rotating 3 times : 8 9 2 4 6 1 Program to illustrate iterative Approach − Live Demo #include <iostream> using namespace std; void swapSubArray(int arr[], int start, int end, int k){ int temp; for(int i = 0; i < k; i++){ temp = arr[start + i]; arr[start + i] = arr[end + i]; arr[end + i] = temp; } } void blockSwapAlgoIt(int arr[], int k, int size) { int i, j; if(k == 0 || k == size) return; i = k; j = size - k; while (i != j) { if(i < j){ swapSubArray(arr, k-i, k+j-i, i); j -= i; } else{ swapSubArray(arr, k-i, k, j); i -= j; } } swapSubArray(arr, k-i, k, i); } int main() { int arr[] = {4, 6, 1, 8, 9, 2}; int size = sizeof(arr) / sizeof(arr[0]); int k = 3; cout<<"Array before rotations :\t"; for(int i = 0; i<size; i++) cout<<arr[i]<<" "; blockSwapAlgoIt(arr, k, size); cout<<"\nArray after rotating "<<k<<" times :\t"; for(int i = 0; i<size; i++) cout<<arr[i]<<" "; return 0; } Array before rotations : 4 6 1 8 9 2 Array after rotating 3 times : 8 9 2 4 6 1
[ { "code": null, "e": 1210, "s": 1062, "text": "The block swap algorithm for array rotation is an efficient algorithm that is used for array rotation. It can do your work in O(n) time complexity." }, { "code": null, "e": 1336, "s": 1210, "text": "So, in array rotation, we are given an array arr[] of size n and a number k that define the no. of the element to be rotated." }, { "code": null, "e": 1378, "s": 1336, "text": "Let’s see an example on array rotations −" }, { "code": null, "e": 1387, "s": 1378, "text": "Input −" }, { "code": null, "e": 1444, "s": 1387, "text": "arr[] = {4, 6, 1, 8, 9, 2}, k = 2 (number of rotations.)" }, { "code": null, "e": 1453, "s": 1444, "text": "Output −" }, { "code": null, "e": 1472, "s": 1453, "text": "{1, 8, 9, 2, 4, 6}" }, { "code": null, "e": 1595, "s": 1472, "text": "Explanation − On rotation, we will shift the one element to the last position and shift the next elements to one position." }, { "code": null, "e": 1708, "s": 1595, "text": "Element at index 0 will be shifted to index n-1. And the rest of the elements are shifted to the previous index." }, { "code": null, "e": 1779, "s": 1708, "text": "The block swap algorithm is used to perform array rotations perfectly." }, { "code": null, "e": 1897, "s": 1779, "text": "Step 1 − Divide the array two sub-arrays with k as division point. Let them be X = arr[0...k-1] and Y = arr[k...n-1]." }, { "code": null, "e": 1969, "s": 1897, "text": "Step 2 − Follow the below steps until the size of X and Y are the same." }, { "code": null, "e": 2188, "s": 1969, "text": "Step 2.1 − If the size of X > Y, divide X into two portions X1 and X2 such that size of X1 is equal to the size of Y. Then swap the sub-array X1 and Y. This will change the original array formation from X1X2Y to YX2X1." }, { "code": null, "e": 2410, "s": 2188, "text": "Step 2.2 − If the size of Y > X, divide Y into two portions Y1 and Y2 such that the size of Y2 is equal to the size of X. Then swap the subarray X and Y2. This will change the original array formation from XY1Y2 to Y2Y1X." }, { "code": null, "e": 2469, "s": 2410, "text": "Step 3 − When the size of X and Y are the same, swap them." }, { "code": null, "e": 2695, "s": 2469, "text": "This algorithm needs a repetitive call to the same chunk of code. This repetitive call can be achieved using two approaches. They are the recursive approach and iterative approach. we will discuss the approach using programs." }, { "code": null, "e": 2738, "s": 2695, "text": "Program to illustrate Recursive Approach −" }, { "code": null, "e": 3692, "s": 2738, "text": "#include <iostream>\nusing namespace std;\nvoid swapSubArray(int arr[], int start, int end, intk){\n int temp;\n for(int i = 0; i < k; i++){\n temp = arr[start + i];\n arr[start + i] = arr[end + i];\n arr[end + i] = temp;\n }\n}\nvoid blockSwapAlgo(int arr[], int k, int n) {\n if(k == 0 || k == n)\n return;\n if(k<(n-k)) {\n swapSubArray(arr, 0, (n-k), k);\n blockSwapAlgo(arr, k, (n-k));\n }\n else if(k>(n-k)){\n swapSubArray(arr, 0, k, (n-k));\n blockSwapAlgo((arr+n-k), (2*k-n), k);\n }\n else{\n swapSubArray(arr, 0, (n-k), k);\n return;\n }\n}\nint main() {\n int arr[] = {4, 6, 1, 8, 9, 2};\n int size = sizeof(arr) / sizeof(arr[0]);\n int k = 3;\n cout<<\"Array before rotations :\\t\";\n for(int i = 0; i<size; i++)\n cout<<arr[i]<<\" \";\n blockSwapAlgo(arr, k, size);\n cout<<\"\\nArray after rotating \"<<k<<\" times :\\t\";\n for(int i = 0; i<size; i++)\n cout<<arr[i]<<\" \";\n return 0;\n}" }, { "code": null, "e": 3772, "s": 3692, "text": "Array before rotations : 4 6 1 8 9 2\nArray after rotating 3 times : 8 9 2 4 6 1" }, { "code": null, "e": 3815, "s": 3772, "text": "Program to illustrate iterative Approach −" }, { "code": null, "e": 3826, "s": 3815, "text": " Live Demo" }, { "code": null, "e": 4780, "s": 3826, "text": "#include <iostream>\nusing namespace std;\nvoid swapSubArray(int arr[], int start, int end, int k){\n int temp;\n for(int i = 0; i < k; i++){\n temp = arr[start + i];\n arr[start + i] = arr[end + i];\n arr[end + i] = temp;\n }\n}\nvoid blockSwapAlgoIt(int arr[], int k, int size) {\n int i, j;\n if(k == 0 || k == size)\n return;\n i = k;\n j = size - k;\n while (i != j) {\n if(i < j){\n swapSubArray(arr, k-i, k+j-i, i);\n j -= i;\n }\n else{\n swapSubArray(arr, k-i, k, j);\n i -= j;\n }\n }\n swapSubArray(arr, k-i, k, i);\n}\nint main() {\n int arr[] = {4, 6, 1, 8, 9, 2};\n int size = sizeof(arr) / sizeof(arr[0]);\n int k = 3;\n cout<<\"Array before rotations :\\t\";\n for(int i = 0; i<size; i++)\n cout<<arr[i]<<\" \";\n blockSwapAlgoIt(arr, k, size);\n cout<<\"\\nArray after rotating \"<<k<<\" times :\\t\";\n for(int i = 0; i<size; i++)\n cout<<arr[i]<<\" \";\n return 0;\n}" }, { "code": null, "e": 4860, "s": 4780, "text": "Array before rotations : 4 6 1 8 9 2\nArray after rotating 3 times : 8 9 2 4 6 1" } ]
Choosing a Baseline Accuracy for a Classification Model | by Aaron Lee | Towards Data Science
When you evaluate a new machine learning model and end up with an accuracy number or other metric, you need to know if it is meaningful. Particularly in imbalanced classification models, it can appear that your model isn’t really doing much better than guessing. What accuracy is enough to call your model useful? This article is just to show the simplistic baseline accuracy for your model that I find useful. I created an election model that predicted the voting habits of all 3200+ US counties (Democrat or Republican) using economic metrics. The model had an accuracy of 86%. That sounds great until you realize that 84% of all counties in the United States voted Republican. Those counties happen to be smaller and more rural, so there are lots more of them. Like many datasets, I had a significant class imbalance. You could simply predict all counties to be Republican and get an accuracy of 84%. Was my model really only barely better than guessing Republican for every county? The model baseline we just described has a name. The ZeroR (or Zero Rate) Classifier always classifies to the largest class– in other words, just trivially predicting the most-frequent class. For a two outcome model, it will be right more often than not by just going with the odds. Always selecting the majority group (ZeroR classifier) is insightful as a baseline and is the one you should choose for any classification model. For a machine learning algorithm to demonstrate that it has skill on a problem, it must achieve an accuracy better than this ZeroR value. For highly imbalanced problems (like the voting classification problem), a model accuracy even a little higher than ZeroR could be significant. Either way though, your model must be better than ZeroR to be considered useful on a problem. Now we will put our high school math to work. Another baseline strategy we can use is to see what our accuracy would be if we guessed at the weighted percentages of each class. This value will always be lower than the ZeroR value, so it should not be your lower limit baseline. Instead, it can be used to explain and understand your results in terms of how much value is added by your model. Random Rate Classifier — Applies prior knowledge of class assignments in making a random class assignment. We will look at these two strategies for a few classification problems. Let’s start by looking at a coin flip model. 50% of the outcomes are tails (0), and 50% of the outcomes are heads (1). How do our baseline strategies work out here?: ZeroR — guessing all heads would give us 50% accuracy. Random Rate — we intuitively know that guessing 0.50 heads and 0.50 tails would also give us 50% accuracy. We will be correct on half of the heads predictions and half of the tails predictions. Guessing half heads and half tails for Random Rate Classifier works mathematically this way: Odds of Guessing Heads Correct: 0.50 * 0.50 = 0.25Odds of Guessing Tails Correct: 0.50 * 0.50 = 0.25Baseline = 0.50**2 + 0.50**2 = 0.50 Now let’s look at one that is not 50/50. Let’s say the outcomes are split 75/25. We would now weight the guessing so that we predict the majority outcome 75% of the time. This Random Rate guessing strategy looks like this Odds of Guessing Minority Correct: 0.25 * 0.25 = 0.0625Odds of Guessing Majority Correct: 0.75 * 0.75 = 0.5625Baseline = 0.25**2 + 0.75**2 = 0.625 If we guessed at that rate, we would guess correctly only 62.5% of the time. Any machine learning model that improves on this baseline is adding value, but must also be above the ZeroR 75% threshold to be useful as a predictor. So how did my voting model described at the beginning of this article really do? Well, it is above the ZeroR baseline, so the model is useful. We can also find out what our baseline would be if we guessed at the actual rate, and then compare it to our model accuracy. Odds of Guessing Democratic Correct: 0.16 * 0.16 = 0.0256Odds of Guessing Republican Correct: 0.84 * 0.84 = 0.7056Baseline = 0.16**2 + 0.84**2 = 0.73 So with random weighted guessing, we would only predict 73% of our counties. Our actual accuracy was 86%. This is 13% improvement over the theoretical value of weighted guessing. The model, which didn’t appear that promising, has definitely added significant value. It is also above the ZeroR baseline, so this model is a useful one for this problem. Could you do this for multiclass problems? Sure. I recently made a Twitter sentiment classifier which classified the emotion of a tweet as positive, negative, or no emotion. The classes were imbalanced in the following way: No emotion toward brand or product 0.593Positive emotion 0.328Negative emotion 0.080 The theoretical baseline using our guessing strategy is: 0.593**2 + 0.328**2 + 0.080**2 = 0.465633 Our actual accuracy was 0.81, so machine learning added 34% to our theoretical baseline. That’s significant. More importantly, our accuracy is also well above the ZeroR value of 0.59 if we had predicted ‘no emotion’ for every outcome. Your model has to do better than Zero Rule (ZeroR) to be useful at prediction. No getting around that. You can compare your model to the theoretical baseline of random guessing and use it to evaluate the usefulness of your model . There are other baselines that you might find useful (uniform guessing, random guessing, and One Rule are a few). Check out sklearn.dummy.DummyClassifier which offers an automated solution for the following baseline strategies: “stratified”, “most_frequent”, “prior”, “uniform”, “constant”. When evaluating accuracy for imbalanced classification problems, consider looking at the AUC. Create your baseline before you build your model, and establish the rules for which you will evaluate your final model. The techniques shown here are provide a ‘reality check’ on your model performance, and are understandable and interpretable for a broad audience (I could easily explain this for a non-technical presentation). They helped me in evaluating and understanding my own models, and I hope you might also find them useful too.
[ { "code": null, "e": 485, "s": 171, "text": "When you evaluate a new machine learning model and end up with an accuracy number or other metric, you need to know if it is meaningful. Particularly in imbalanced classification models, it can appear that your model isn’t really doing much better than guessing. What accuracy is enough to call your model useful?" }, { "code": null, "e": 582, "s": 485, "text": "This article is just to show the simplistic baseline accuracy for your model that I find useful." }, { "code": null, "e": 992, "s": 582, "text": "I created an election model that predicted the voting habits of all 3200+ US counties (Democrat or Republican) using economic metrics. The model had an accuracy of 86%. That sounds great until you realize that 84% of all counties in the United States voted Republican. Those counties happen to be smaller and more rural, so there are lots more of them. Like many datasets, I had a significant class imbalance." }, { "code": null, "e": 1157, "s": 992, "text": "You could simply predict all counties to be Republican and get an accuracy of 84%. Was my model really only barely better than guessing Republican for every county?" }, { "code": null, "e": 1206, "s": 1157, "text": "The model baseline we just described has a name." }, { "code": null, "e": 1440, "s": 1206, "text": "The ZeroR (or Zero Rate) Classifier always classifies to the largest class– in other words, just trivially predicting the most-frequent class. For a two outcome model, it will be right more often than not by just going with the odds." }, { "code": null, "e": 1724, "s": 1440, "text": "Always selecting the majority group (ZeroR classifier) is insightful as a baseline and is the one you should choose for any classification model. For a machine learning algorithm to demonstrate that it has skill on a problem, it must achieve an accuracy better than this ZeroR value." }, { "code": null, "e": 1962, "s": 1724, "text": "For highly imbalanced problems (like the voting classification problem), a model accuracy even a little higher than ZeroR could be significant. Either way though, your model must be better than ZeroR to be considered useful on a problem." }, { "code": null, "e": 2354, "s": 1962, "text": "Now we will put our high school math to work. Another baseline strategy we can use is to see what our accuracy would be if we guessed at the weighted percentages of each class. This value will always be lower than the ZeroR value, so it should not be your lower limit baseline. Instead, it can be used to explain and understand your results in terms of how much value is added by your model." }, { "code": null, "e": 2461, "s": 2354, "text": "Random Rate Classifier — Applies prior knowledge of class assignments in making a random class assignment." }, { "code": null, "e": 2533, "s": 2461, "text": "We will look at these two strategies for a few classification problems." }, { "code": null, "e": 2652, "s": 2533, "text": "Let’s start by looking at a coin flip model. 50% of the outcomes are tails (0), and 50% of the outcomes are heads (1)." }, { "code": null, "e": 2699, "s": 2652, "text": "How do our baseline strategies work out here?:" }, { "code": null, "e": 2754, "s": 2699, "text": "ZeroR — guessing all heads would give us 50% accuracy." }, { "code": null, "e": 2948, "s": 2754, "text": "Random Rate — we intuitively know that guessing 0.50 heads and 0.50 tails would also give us 50% accuracy. We will be correct on half of the heads predictions and half of the tails predictions." }, { "code": null, "e": 3041, "s": 2948, "text": "Guessing half heads and half tails for Random Rate Classifier works mathematically this way:" }, { "code": null, "e": 3177, "s": 3041, "text": "Odds of Guessing Heads Correct: 0.50 * 0.50 = 0.25Odds of Guessing Tails Correct: 0.50 * 0.50 = 0.25Baseline = 0.50**2 + 0.50**2 = 0.50" }, { "code": null, "e": 3399, "s": 3177, "text": "Now let’s look at one that is not 50/50. Let’s say the outcomes are split 75/25. We would now weight the guessing so that we predict the majority outcome 75% of the time. This Random Rate guessing strategy looks like this" }, { "code": null, "e": 3546, "s": 3399, "text": "Odds of Guessing Minority Correct: 0.25 * 0.25 = 0.0625Odds of Guessing Majority Correct: 0.75 * 0.75 = 0.5625Baseline = 0.25**2 + 0.75**2 = 0.625" }, { "code": null, "e": 3774, "s": 3546, "text": "If we guessed at that rate, we would guess correctly only 62.5% of the time. Any machine learning model that improves on this baseline is adding value, but must also be above the ZeroR 75% threshold to be useful as a predictor." }, { "code": null, "e": 4042, "s": 3774, "text": "So how did my voting model described at the beginning of this article really do? Well, it is above the ZeroR baseline, so the model is useful. We can also find out what our baseline would be if we guessed at the actual rate, and then compare it to our model accuracy." }, { "code": null, "e": 4192, "s": 4042, "text": "Odds of Guessing Democratic Correct: 0.16 * 0.16 = 0.0256Odds of Guessing Republican Correct: 0.84 * 0.84 = 0.7056Baseline = 0.16**2 + 0.84**2 = 0.73" }, { "code": null, "e": 4543, "s": 4192, "text": "So with random weighted guessing, we would only predict 73% of our counties. Our actual accuracy was 86%. This is 13% improvement over the theoretical value of weighted guessing. The model, which didn’t appear that promising, has definitely added significant value. It is also above the ZeroR baseline, so this model is a useful one for this problem." }, { "code": null, "e": 4592, "s": 4543, "text": "Could you do this for multiclass problems? Sure." }, { "code": null, "e": 4767, "s": 4592, "text": "I recently made a Twitter sentiment classifier which classified the emotion of a tweet as positive, negative, or no emotion. The classes were imbalanced in the following way:" }, { "code": null, "e": 4897, "s": 4767, "text": "No emotion toward brand or product 0.593Positive emotion 0.328Negative emotion 0.080" }, { "code": null, "e": 4954, "s": 4897, "text": "The theoretical baseline using our guessing strategy is:" }, { "code": null, "e": 4996, "s": 4954, "text": "0.593**2 + 0.328**2 + 0.080**2 = 0.465633" }, { "code": null, "e": 5231, "s": 4996, "text": "Our actual accuracy was 0.81, so machine learning added 34% to our theoretical baseline. That’s significant. More importantly, our accuracy is also well above the ZeroR value of 0.59 if we had predicted ‘no emotion’ for every outcome." }, { "code": null, "e": 5334, "s": 5231, "text": "Your model has to do better than Zero Rule (ZeroR) to be useful at prediction. No getting around that." }, { "code": null, "e": 5462, "s": 5334, "text": "You can compare your model to the theoretical baseline of random guessing and use it to evaluate the usefulness of your model ." }, { "code": null, "e": 5576, "s": 5462, "text": "There are other baselines that you might find useful (uniform guessing, random guessing, and One Rule are a few)." }, { "code": null, "e": 5753, "s": 5576, "text": "Check out sklearn.dummy.DummyClassifier which offers an automated solution for the following baseline strategies: “stratified”, “most_frequent”, “prior”, “uniform”, “constant”." }, { "code": null, "e": 5847, "s": 5753, "text": "When evaluating accuracy for imbalanced classification problems, consider looking at the AUC." }, { "code": null, "e": 5967, "s": 5847, "text": "Create your baseline before you build your model, and establish the rules for which you will evaluate your final model." } ]
How to create a Junit report in Cypress?
We can create a Junit report in Cypress. To install the package for the JUnit report, run the command − npm install cypress-junit-reporter --save-dev Implementation in cypress.json { "reporter": "junit", "reporterOptions": { "mochaFile": "cypress/results/results.xml", "toConsole": true } } If we run multiple tests in a run and wish to have a unique report for individual spec files, we have to add [hash] in the mochaFile parameter in cypress.json. Implementation in cypress.json to avoid overriding report { "reporter": "junit", "reporterOptions": { "mochaFile": "cypress/results/results-[hash].xml", "toConsole": true } } To generate a report for all specs in the integration folder of the Cypress project, run the command − npx cypress run --reporter junit After execution is completed, the results folder gets generated within the Cypress project containing reports in xml format.
[ { "code": null, "e": 1166, "s": 1062, "text": "We can create a Junit report in Cypress. To install the package for the JUnit report, run the command −" }, { "code": null, "e": 1215, "s": 1166, "text": " npm install cypress-junit-reporter --save-dev" }, { "code": null, "e": 1246, "s": 1215, "text": "Implementation in cypress.json" }, { "code": null, "e": 1377, "s": 1246, "text": "{\n \"reporter\": \"junit\",\n \"reporterOptions\": {\n \"mochaFile\": \"cypress/results/results.xml\",\n \"toConsole\": true\n }\n}" }, { "code": null, "e": 1537, "s": 1377, "text": "If we run multiple tests in a run and wish to have a unique report for individual spec files, we have to add [hash] in the mochaFile parameter in cypress.json." }, { "code": null, "e": 1595, "s": 1537, "text": "Implementation in cypress.json to avoid overriding report" }, { "code": null, "e": 1733, "s": 1595, "text": "{\n \"reporter\": \"junit\",\n \"reporterOptions\": {\n \"mochaFile\": \"cypress/results/results-[hash].xml\",\n \"toConsole\": true\n }\n}" }, { "code": null, "e": 1836, "s": 1733, "text": "To generate a report for all specs in the integration folder of the Cypress project, run the command −" }, { "code": null, "e": 1872, "s": 1836, "text": " npx cypress run --reporter junit" }, { "code": null, "e": 1997, "s": 1872, "text": "After execution is completed, the results folder gets generated within the Cypress project containing reports in xml format." } ]
Generation of time delay in 8085
In this section we will see how to generate the time delay using 8085 programs. The delay will be used in different places to simulate clocks, or counters or some other area. When the delay subroutine is executed, the microprocessor does not execute other tasks. For the delay we are using the instruction execution times. executing some instructions in a loop, the delay is generated. There are some methods of generating delays. These methods are as follows. Using NOP instructions Using NOP instructions Using 8-bit register as counter Using 8-bit register as counter Using 16-bit register pair as counter. Using 16-bit register pair as counter. Using NOT instructions: One of the main usage of NOP instruction is in delay generation. The NOP instruction is taking four clock pulses to be fetching, decoding and executing. If the 8085 MPU is working on 6MHz clock frequency, then the internal clock frequency is 3MHz. So from that we can easily determine that each clock period is 1/3 of a microsecond. So the NOP will be executed in 1/3 * 4 = 1.333μs. If we use the entire memory with NOP instruction, then 64K NOP instructions will be executed. Then the overall delay will be 216 * 1.333μs = 87359.488μs, though the time is not so large and the program size is also large. So this type of NOP instruction can be used to generate a short time delay for few milliseconds. Using 8-bit register as counter: Counter is another approach to generate a time delay. In this case the program size is smaller. So in this approach we can generate more time delay in less space. The following program will demonstrate the time delay using 8-bit counter. MVI B,FFH LOOP: DCR B JNZ LOOP RET Here the first instruction will be executed once, it will take 7 T-states. DCR C instruction takes 4 T-states. This will be executed 255 (FF) times. The JNZ instruction takes 10 T-states when it jumps (It jumps 254 times), otherwise it will take 7 T-States. And the RET instruction takes 10 T-States. 7 + ((4*255) + (10*254)) + 7 + 10 = 3584. So the time delay will be 3584 * 1/3μs = 1194.66μs. So when we need some small delay, then we can use this technique with some other values in the place of FF. This technique can also be done using some nested loops to get larger delays. The following code is showing how we can get some delay with one loop into some other loops. MVI B,FFH L1: MVI C,FFH L2: DCR C JNZ L2 DCR B JNZ L1 RET From this block, if we calculate the delay, it will be nearly 305μs delay. It extends the time of delay. Using 16-bit register-pair as counter: Instead of using 8-bit counter, we can do that kind of task using 16-bit register pair. Using this method more time delay can be generated. This method can be used to get more than 0.5 seconds delay. Let us see and example. In the above table we have placed the T-States. From that table, if we calculate the time delay, it will be like this: 10 + (6 + 4 + 4 + 10) * 65535H – 3 + 10 = 17 + 24 * 65535H = 1572857. So the time delay will be 1572857 * 1/3μs = 0.52428s. Here we are getting nearly 0.5s delay. In different program, we need 1s delay. For that case, this program can be executed twice. We can call the Delay subroutine twice or use another outer loop for two-time execution.
[ { "code": null, "e": 1237, "s": 1062, "text": "In this section we will see how to generate the time delay using 8085 programs. The delay will be used in different places to simulate clocks, or counters or some other area." }, { "code": null, "e": 1523, "s": 1237, "text": "When the delay subroutine is executed, the microprocessor does not execute other tasks. For the delay we are using the instruction execution times. executing some instructions in a loop, the delay is generated. There are some methods of generating delays. These methods are as follows." }, { "code": null, "e": 1546, "s": 1523, "text": "Using NOP instructions" }, { "code": null, "e": 1569, "s": 1546, "text": "Using NOP instructions" }, { "code": null, "e": 1601, "s": 1569, "text": "Using 8-bit register as counter" }, { "code": null, "e": 1633, "s": 1601, "text": "Using 8-bit register as counter" }, { "code": null, "e": 1672, "s": 1633, "text": "Using 16-bit register pair as counter." }, { "code": null, "e": 1711, "s": 1672, "text": "Using 16-bit register pair as counter." }, { "code": null, "e": 1735, "s": 1711, "text": "Using NOT instructions:" }, { "code": null, "e": 2437, "s": 1735, "text": "One of the main usage of NOP instruction is in delay generation. The NOP instruction is taking four clock pulses to be fetching, decoding and executing. If the 8085 MPU is working on 6MHz clock frequency, then the internal clock frequency is 3MHz. So from that we can easily determine that each clock period is 1/3 of a microsecond. So the NOP will be executed in 1/3 * 4 = 1.333μs. If we use the entire memory with NOP instruction, then 64K NOP instructions will be executed. Then the overall delay will be 216 * 1.333μs = 87359.488μs, though the time is not so large and the program size is also large. So this type of NOP instruction can be used to generate a short time delay for few milliseconds." }, { "code": null, "e": 2470, "s": 2437, "text": "Using 8-bit register as counter:" }, { "code": null, "e": 2708, "s": 2470, "text": "Counter is another approach to generate a time delay. In this case the program size is smaller. So in this approach we can generate more time delay in less space. The following program will demonstrate the time delay using 8-bit counter." }, { "code": null, "e": 2761, "s": 2708, "text": " MVI B,FFH\nLOOP: DCR B\n JNZ LOOP\n RET" }, { "code": null, "e": 3062, "s": 2761, "text": "Here the first instruction will be executed once, it will take 7 T-states. DCR C instruction takes 4 T-states. This will be executed 255 (FF) times. The JNZ instruction takes 10 T-states when it jumps (It jumps 254 times), otherwise it will take 7 T-States. And the RET instruction takes 10 T-States." }, { "code": null, "e": 3264, "s": 3062, "text": "7 + ((4*255) + (10*254)) + 7 + 10 = 3584. So the time delay will be 3584 * 1/3μs = 1194.66μs. So when we need some small delay, then we can use this technique with some other values in the place of FF." }, { "code": null, "e": 3435, "s": 3264, "text": "This technique can also be done using some nested loops to get larger delays. The following code is showing how we can get some delay with one loop into some other loops." }, { "code": null, "e": 3513, "s": 3435, "text": " MVI B,FFH\nL1: MVI C,FFH\nL2: DCR C\n JNZ L2\n DCR B\n JNZ L1\n RET" }, { "code": null, "e": 3618, "s": 3513, "text": "From this block, if we calculate the delay, it will be nearly 305μs delay. It extends the time of delay." }, { "code": null, "e": 3657, "s": 3618, "text": "Using 16-bit register-pair as counter:" }, { "code": null, "e": 3881, "s": 3657, "text": "Instead of using 8-bit counter, we can do that kind of task using 16-bit register pair. Using this method more time delay can be generated. This method can be used to get more than 0.5 seconds delay. Let us see and example." }, { "code": null, "e": 4000, "s": 3881, "text": "In the above table we have placed the T-States. From that table, if we calculate the time delay, it will be like this:" }, { "code": null, "e": 4163, "s": 4000, "text": "10 + (6 + 4 + 4 + 10) * 65535H – 3 + 10 = 17 + 24 * 65535H = 1572857. So the time delay will be 1572857 * 1/3μs = 0.52428s. Here we are getting nearly 0.5s delay." }, { "code": null, "e": 4343, "s": 4163, "text": "In different program, we need 1s delay. For that case, this program can be executed twice. We can call the Delay subroutine twice or use another outer loop for two-time execution." } ]
Search in an almost sorted array
14 Mar, 2022 Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1].For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position.Example : Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40 Output: 2 Output is index of 40 in given array Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90 Output: -1 -1 is returned to indicate element is not present A simple solution is to linearly search the given key in given array. Time complexity of this solution is O(n). We can modify binary search to do it in O(Logn) time. The idea is to compare the key with middle 3 elements, if present then return the index. If not present, then compare the key with middle element to decide whether to go in left half or right half. Comparing with middle element is enough as all the elements after mid+2 must be greater than element mid and all elements before mid-2 must be smaller than mid element.Following is the implementation of this approach. C++ Java Python3 C# PHP Javascript // C++ program to find an element// in an almost sorted array#include <stdio.h> // A recursive binary search based function.// It returns index of x in given array// arr[l..r] is present, otherwise -1int binarySearch(int arr[], int l, int r, int x){if (r >= l){ int mid = l + (r - l) / 2; // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid >= l && arr[mid - 1] == x) return (mid - 1); if (mid <= r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x);} // We reach here when element is not present in arrayreturn -1;} // Driver Codeint main(void){int arr[] = {3, 2, 10, 4, 40};int n = sizeof(arr) / sizeof(arr[0]);int x = 4;int result = binarySearch(arr, 0, n - 1, x);(result == -1) ? printf("Element is not present in array") : printf("Element is present at index %d", result);return 0;} // Java program to find an element// in an almost sorted arrayclass GFG{ // A recursive binary search based function. // It returns index of x in given array // arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid > l && arr[mid - 1] == x) return (mid - 1); if (mid < r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x); } // We reach here when element is // not present in array return -1; } // Driver code public static void main(String args[]) { GFG ob = new GFG(); int arr[] = {3, 2, 10, 4, 40}; int n = arr.length; int x = 4; int result = ob.binarySearch(arr, 0, n - 1, x); if(result == -1) System.out.println("Element is not present in array"); else System.out.println("Element is present at index " + result); }} // This code is contributed by Rajat Mishra # Python 3 program to find an element# in an almost sorted array # A recursive binary search based function.# It returns index of x in given array arr[l..r]# is present, otherwise -1def binarySearch(arr, l, r, x): if (r >= l): mid = int(l + (r - l) / 2) # If the element is present at one # of the middle 3 positions if (arr[mid] == x): return mid if (mid > l and arr[mid - 1] == x): return (mid - 1) if (mid < r and arr[mid + 1] == x): return (mid + 1) # If element is smaller than mid, then # it can only be present in left subarray if (arr[mid] > x): return binarySearch(arr, l, mid - 2, x) # Else the element can only # be present in right subarray return binarySearch(arr, mid + 2, r, x) # We reach here when element # is not present in array return -1 # Driver Codearr = [3, 2, 10, 4, 40]n = len(arr)x = 4result = binarySearch(arr, 0, n - 1, x)if (result == -1): print("Element is not present in array")else: print("Element is present at index", result) # This code is contributed by Smitha Dinesh Semwal. // C# program to find an element// in an almost sorted arrayusing System; class GFG{ // A recursive binary search based function. // It returns index of x in given array // arr[l..r] is present, otherwise -1 int binarySearch(int []arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid > l && arr[mid - 1] == x) return (mid - 1); if (mid < r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x); } // We reach here when element is // not present in array return -1; } // Driver code public static void Main() { GFG ob = new GFG(); int []arr = {3, 2, 10, 4, 40}; int n = arr.Length; int x = 4; int result = ob.binarySearch(arr, 0, n - 1, x); if(result == -1) Console.Write("Element is not present in array"); else Console.Write("Element is present at index " + result); }} // This code is contributed by nitin mittal. <?php// PHP program to find an element// in an almost sorted array // A recursive binary search based function.// It returns index of x in given array// arr[l..r] is present, otherwise -1function binarySearch($arr, $l, $r, $x){ if ($r >= $l) { $mid = $l + ($r - $l) / 2; // If the element is present at // one of the middle 3 positions if ($arr[$mid] == $x) return $mid; if ($mid > $l && $arr[$mid - 1] == $x) return ($mid - 1); if ($mid < $r && $arr[$mid + 1] == $x) return ($mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if ($arr[$mid] > $x) return binarySearch($arr, $l, $mid - 2, $x); // Else the element can only be present // in right subarray return binarySearch($arr, $mid + 2, $r, $x);} // We reach here when element// is not present in arrayreturn -1;} // Driver Code$arr = array(3, 2, 10, 4, 40);$n = sizeof($arr);$x = 4;$result = binarySearch($arr, 0, $n - 1, $x);if($result == -1) echo("Element is not present in array");else echo("Element is present at index $result"); //This code is contributed by nitin mittal?> <script>// Javascript program to find an element// in an almost sorted array // A recursive binary search based function. // It returns index of x in given array // arr[l..r] is present, otherwise -1function binarySearch(arr,l,r,x){ if (r >= l) { let mid = l + Math.floor((r - l) / 2); // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid > l && arr[mid - 1] == x) return (mid - 1); if (mid < r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x); } // We reach here when element is // not present in array return -1;} // Driver codelet arr=[3, 2, 10, 4, 40];let n = arr.length;let x = 4;let result = binarySearch(arr, 0, n - 1, x);if(result == -1) document.write("Element is not present in array<br>");else document.write("Element is present at index " + result+"<br>"); // This code is contributed by unknown2108</script> Output : Element is present at index 3 Time complexity of the above function is O(Logn). Search in an almost sorted array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersSearch in an almost sorted array | 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 / 3:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=xWOoBJUqlbI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above nitin mittal unknown2108 sidharthkar2001 Searching Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Mar, 2022" }, { "code": null, "e": 491, "s": 54, "text": "Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1].For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position.Example : " }, { "code": null, "e": 709, "s": 491, "text": "Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40\nOutput: 2 \nOutput is index of 40 in given array\n\nInput: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90\nOutput: -1\n-1 is returned to indicate element is not present" }, { "code": null, "e": 1292, "s": 709, "text": "A simple solution is to linearly search the given key in given array. Time complexity of this solution is O(n). We can modify binary search to do it in O(Logn) time. The idea is to compare the key with middle 3 elements, if present then return the index. If not present, then compare the key with middle element to decide whether to go in left half or right half. Comparing with middle element is enough as all the elements after mid+2 must be greater than element mid and all elements before mid-2 must be smaller than mid element.Following is the implementation of this approach. " }, { "code": null, "e": 1296, "s": 1292, "text": "C++" }, { "code": null, "e": 1301, "s": 1296, "text": "Java" }, { "code": null, "e": 1309, "s": 1301, "text": "Python3" }, { "code": null, "e": 1312, "s": 1309, "text": "C#" }, { "code": null, "e": 1316, "s": 1312, "text": "PHP" }, { "code": null, "e": 1327, "s": 1316, "text": "Javascript" }, { "code": "// C++ program to find an element// in an almost sorted array#include <stdio.h> // A recursive binary search based function.// It returns index of x in given array// arr[l..r] is present, otherwise -1int binarySearch(int arr[], int l, int r, int x){if (r >= l){ int mid = l + (r - l) / 2; // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid >= l && arr[mid - 1] == x) return (mid - 1); if (mid <= r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x);} // We reach here when element is not present in arrayreturn -1;} // Driver Codeint main(void){int arr[] = {3, 2, 10, 4, 40};int n = sizeof(arr) / sizeof(arr[0]);int x = 4;int result = binarySearch(arr, 0, n - 1, x);(result == -1) ? printf(\"Element is not present in array\") : printf(\"Element is present at index %d\", result);return 0;}", "e": 2568, "s": 1327, "text": null }, { "code": "// Java program to find an element// in an almost sorted arrayclass GFG{ // A recursive binary search based function. // It returns index of x in given array // arr[l..r] is present, otherwise -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid > l && arr[mid - 1] == x) return (mid - 1); if (mid < r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x); } // We reach here when element is // not present in array return -1; } // Driver code public static void main(String args[]) { GFG ob = new GFG(); int arr[] = {3, 2, 10, 4, 40}; int n = arr.length; int x = 4; int result = ob.binarySearch(arr, 0, n - 1, x); if(result == -1) System.out.println(\"Element is not present in array\"); else System.out.println(\"Element is present at index \" + result); }} // This code is contributed by Rajat Mishra", "e": 4114, "s": 2568, "text": null }, { "code": "# Python 3 program to find an element# in an almost sorted array # A recursive binary search based function.# It returns index of x in given array arr[l..r]# is present, otherwise -1def binarySearch(arr, l, r, x): if (r >= l): mid = int(l + (r - l) / 2) # If the element is present at one # of the middle 3 positions if (arr[mid] == x): return mid if (mid > l and arr[mid - 1] == x): return (mid - 1) if (mid < r and arr[mid + 1] == x): return (mid + 1) # If element is smaller than mid, then # it can only be present in left subarray if (arr[mid] > x): return binarySearch(arr, l, mid - 2, x) # Else the element can only # be present in right subarray return binarySearch(arr, mid + 2, r, x) # We reach here when element # is not present in array return -1 # Driver Codearr = [3, 2, 10, 4, 40]n = len(arr)x = 4result = binarySearch(arr, 0, n - 1, x)if (result == -1): print(\"Element is not present in array\")else: print(\"Element is present at index\", result) # This code is contributed by Smitha Dinesh Semwal.", "e": 5303, "s": 4114, "text": null }, { "code": "// C# program to find an element// in an almost sorted arrayusing System; class GFG{ // A recursive binary search based function. // It returns index of x in given array // arr[l..r] is present, otherwise -1 int binarySearch(int []arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid > l && arr[mid - 1] == x) return (mid - 1); if (mid < r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x); } // We reach here when element is // not present in array return -1; } // Driver code public static void Main() { GFG ob = new GFG(); int []arr = {3, 2, 10, 4, 40}; int n = arr.Length; int x = 4; int result = ob.binarySearch(arr, 0, n - 1, x); if(result == -1) Console.Write(\"Element is not present in array\"); else Console.Write(\"Element is present at index \" + result); }} // This code is contributed by nitin mittal.", "e": 6834, "s": 5303, "text": null }, { "code": "<?php// PHP program to find an element// in an almost sorted array // A recursive binary search based function.// It returns index of x in given array// arr[l..r] is present, otherwise -1function binarySearch($arr, $l, $r, $x){ if ($r >= $l) { $mid = $l + ($r - $l) / 2; // If the element is present at // one of the middle 3 positions if ($arr[$mid] == $x) return $mid; if ($mid > $l && $arr[$mid - 1] == $x) return ($mid - 1); if ($mid < $r && $arr[$mid + 1] == $x) return ($mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if ($arr[$mid] > $x) return binarySearch($arr, $l, $mid - 2, $x); // Else the element can only be present // in right subarray return binarySearch($arr, $mid + 2, $r, $x);} // We reach here when element// is not present in arrayreturn -1;} // Driver Code$arr = array(3, 2, 10, 4, 40);$n = sizeof($arr);$x = 4;$result = binarySearch($arr, 0, $n - 1, $x);if($result == -1) echo(\"Element is not present in array\");else echo(\"Element is present at index $result\"); //This code is contributed by nitin mittal?>", "e": 8114, "s": 6834, "text": null }, { "code": "<script>// Javascript program to find an element// in an almost sorted array // A recursive binary search based function. // It returns index of x in given array // arr[l..r] is present, otherwise -1function binarySearch(arr,l,r,x){ if (r >= l) { let mid = l + Math.floor((r - l) / 2); // If the element is present at // one of the middle 3 positions if (arr[mid] == x) return mid; if (mid > l && arr[mid - 1] == x) return (mid - 1); if (mid < r && arr[mid + 1] == x) return (mid + 1); // If element is smaller than mid, then // it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 2, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid + 2, r, x); } // We reach here when element is // not present in array return -1;} // Driver codelet arr=[3, 2, 10, 4, 40];let n = arr.length;let x = 4;let result = binarySearch(arr, 0, n - 1, x);if(result == -1) document.write(\"Element is not present in array<br>\");else document.write(\"Element is present at index \" + result+\"<br>\"); // This code is contributed by unknown2108</script>", "e": 9493, "s": 8114, "text": null }, { "code": null, "e": 9503, "s": 9493, "text": "Output : " }, { "code": null, "e": 9533, "s": 9503, "text": "Element is present at index 3" }, { "code": null, "e": 9584, "s": 9533, "text": "Time complexity of the above function is O(Logn). " }, { "code": null, "e": 10466, "s": 9584, "text": "Search in an almost sorted array | GeeksforGeeks - YouTubeGeeksforGeeks531K subscribersSearch in an almost sorted array | 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 / 3:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=xWOoBJUqlbI\" 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": 10632, "s": 10466, "text": "This article is contributed by Abhishek. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 10645, "s": 10632, "text": "nitin mittal" }, { "code": null, "e": 10657, "s": 10645, "text": "unknown2108" }, { "code": null, "e": 10673, "s": 10657, "text": "sidharthkar2001" }, { "code": null, "e": 10683, "s": 10673, "text": "Searching" }, { "code": null, "e": 10693, "s": 10683, "text": "Searching" } ]
Split an array into chunks in JavaScript
16 May, 2019 We have a large array and we want to split it into chunks. So these are few of the methods to do it. splice()This method adds/removes items to/from an array, and returns the list of removed item(s).Syntax:array.splice(index, number, item1, ....., itemN) Parameters:index:This parameter is required. It specifies the integer at what position to add/remove items, Negative values are helpful to specify the position from the end.number:This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove.item1, ....., itemN:This parameter is optional. This specifies the new item(s) to be added to array.Return value:Returns a new Array, having the removed items. array.splice(index, number, item1, ....., itemN) Parameters: index:This parameter is required. It specifies the integer at what position to add/remove items, Negative values are helpful to specify the position from the end. number:This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove. item1, ....., itemN:This parameter is optional. This specifies the new item(s) to be added to array. Return value:Returns a new Array, having the removed items. slice()This method returns a new array containing the selected elements.This method selects the elements starts from the given start argument, and ends at, but excluding, the given end argument.Syntax:array.slice(start, end) Parameters:start:This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of array. If not used, it acts like “0”end:This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end.Return value:Returns a new Array, having the selected items. array.slice(start, end) Parameters: start:This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of array. If not used, it acts like “0” end:This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end. Return value:Returns a new Array, having the selected items. Example-1:This example uses the slice() method to split the array into chunks of array. This method can be used repeatedly to split array of any size. <!DOCTYPE html><html> <head> <title> JavaScript | Split array into chunks. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var i, j, chunk = 4; var array = [1, 2, 3, 4, 5, 6, 7, 8]; el_up.innerHTML = array; function gfg_Run() { var array1 = array.slice(0, chunk); var array2 = array.slice(chunk, chunk + array.length); el_down.innerHTML = array1 + ' and ' + array2; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Example-2: This example uses the splice() method to split the array into chunks of array. This method removes the items from the original array. This method can be used repeatedly to split array of any size. <!DOCTYPE html><html> <head> <title> JavaScript | Split array into chunks. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 16px;"> </p> <button onclick="gfg_Run()"> click here </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var i, j, chunk = 2; var array = [1, 2, 3, 4, 5, 6, 7, 8]; el_up.innerHTML = array; function gfg_Run() { var array1 = array.splice(0, chunk); var array2 = array.splice(0, chunk); var array3 = array.splice(0, chunk); var array4 = array.splice(0, chunk); el_down.innerHTML = array1 + ' | ' + array2 + ' | ' + array3 + ' | ' + array4; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: javascript-array JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 May, 2019" }, { "code": null, "e": 129, "s": 28, "text": "We have a large array and we want to split it into chunks. So these are few of the methods to do it." }, { "code": null, "e": 725, "s": 129, "text": "splice()This method adds/removes items to/from an array, and returns the list of removed item(s).Syntax:array.splice(index, number, item1, ....., itemN)\nParameters:index:This parameter is required. It specifies the integer at what position to add/remove items, Negative values are helpful to specify the position from the end.number:This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove.item1, ....., itemN:This parameter is optional. This specifies the new item(s) to be added to array.Return value:Returns a new Array, having the removed items." }, { "code": null, "e": 775, "s": 725, "text": "array.splice(index, number, item1, ....., itemN)\n" }, { "code": null, "e": 787, "s": 775, "text": "Parameters:" }, { "code": null, "e": 950, "s": 787, "text": "index:This parameter is required. It specifies the integer at what position to add/remove items, Negative values are helpful to specify the position from the end." }, { "code": null, "e": 1061, "s": 950, "text": "number:This parameter is optional. It specifies the number of items to be removed. 0 means, nothing to remove." }, { "code": null, "e": 1162, "s": 1061, "text": "item1, ....., itemN:This parameter is optional. This specifies the new item(s) to be added to array." }, { "code": null, "e": 1222, "s": 1162, "text": "Return value:Returns a new Array, having the removed items." }, { "code": null, "e": 1962, "s": 1222, "text": "slice()This method returns a new array containing the selected elements.This method selects the elements starts from the given start argument, and ends at, but excluding, the given end argument.Syntax:array.slice(start, end)\nParameters:start:This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of array. If not used, it acts like “0”end:This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end.Return value:Returns a new Array, having the selected items." }, { "code": null, "e": 1987, "s": 1962, "text": "array.slice(start, end)\n" }, { "code": null, "e": 1999, "s": 1987, "text": "Parameters:" }, { "code": null, "e": 2212, "s": 1999, "text": "start:This parameter is optional. It specifies the integer from where to start the selection (first element is at index 0). Negative numbers are used to select from the end of array. If not used, it acts like “0”" }, { "code": null, "e": 2444, "s": 2212, "text": "end:This parameter is optional. It specifies the integer from where to end the selection. If not used, all elements from the start to the end of array will be included in selection. Negative numbers are used to select from the end." }, { "code": null, "e": 2505, "s": 2444, "text": "Return value:Returns a new Array, having the selected items." }, { "code": null, "e": 2656, "s": 2505, "text": "Example-1:This example uses the slice() method to split the array into chunks of array. This method can be used repeatedly to split array of any size." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Split array into chunks. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var i, j, chunk = 4; var array = [1, 2, 3, 4, 5, 6, 7, 8]; el_up.innerHTML = array; function gfg_Run() { var array1 = array.slice(0, chunk); var array2 = array.slice(chunk, chunk + array.length); el_down.innerHTML = array1 + ' and ' + array2; } </script></body> </html>", "e": 3669, "s": 2656, "text": null }, { "code": null, "e": 3677, "s": 3669, "text": "Output:" }, { "code": null, "e": 3708, "s": 3677, "text": "Before clicking on the button:" }, { "code": null, "e": 3738, "s": 3708, "text": "After clicking on the button:" }, { "code": null, "e": 3946, "s": 3738, "text": "Example-2: This example uses the splice() method to split the array into chunks of array. This method removes the items from the original array. This method can be used repeatedly to split array of any size." }, { "code": "<!DOCTYPE html><html> <head> <title> JavaScript | Split array into chunks. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 16px;\"> </p> <button onclick=\"gfg_Run()\"> click here </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var i, j, chunk = 2; var array = [1, 2, 3, 4, 5, 6, 7, 8]; el_up.innerHTML = array; function gfg_Run() { var array1 = array.splice(0, chunk); var array2 = array.splice(0, chunk); var array3 = array.splice(0, chunk); var array4 = array.splice(0, chunk); el_down.innerHTML = array1 + ' | ' + array2 + ' | ' + array3 + ' | ' + array4; } </script></body> </html>", "e": 5104, "s": 3946, "text": null }, { "code": null, "e": 5112, "s": 5104, "text": "Output:" }, { "code": null, "e": 5143, "s": 5112, "text": "Before clicking on the button:" }, { "code": null, "e": 5173, "s": 5143, "text": "After clicking on the button:" }, { "code": null, "e": 5190, "s": 5173, "text": "javascript-array" }, { "code": null, "e": 5201, "s": 5190, "text": "JavaScript" }, { "code": null, "e": 5218, "s": 5201, "text": "Web Technologies" }, { "code": null, "e": 5316, "s": 5218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5377, "s": 5316, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5449, "s": 5377, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5489, "s": 5449, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5531, "s": 5489, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5572, "s": 5531, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5605, "s": 5572, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5667, "s": 5605, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5728, "s": 5667, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5778, "s": 5728, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Whale Optimization Algorithm (WOA)
12 Apr, 2021 The step-by-step procedure to obtain an optimum value (maximum or minimum) of an objective function is called an Optimization Algorithm. Meta-heuristic optimization algorithms are becoming more and more popular in engineering applications because they: rely on rather simple concepts and are easy to implement do not require gradient information can bypass local optima can be utilized in a wide range of problems covering different disciplines. Many scholars and researchers have developed several metaheuristics to address complex/unsolved optimization problems. Example: Particle Swarm Optimization, Grey wolf optimization, Ant colony Optimization, Genetic Algorithms, Cuckoo search algorithm etc. This article aims to introduce a novel meta-heuristic optimization technique called as Whale Optimization algorithm (WOA) Whale optimization algorithm (WOA): A nature inspired meta-heuristic optimization algorithm which mimics the hunting behaviour of humpback whales. The algorithm is inspired by the bubble-net hunting strategy Foraging behavior of Humpback whales is called bubble-net feeding method. Humpback whales prefer to hunt school of krill or small fishes close to the surface. It has been observed that this foraging is done by creating distinctive bubbles along a circle or ‘9’-shaped path as shown in Fig. 1. Two maneuvers associated with bubble net feeding are ‘upward-spirals’ and ‘double-loops’. In ‘upward-spirals’ maneuver humpback whales dive around 12 m down and then start to create bubble in a spiral shape around the prey and swim up toward the surface. ‘double-loops’ maneuver includes three different stages: coral loop, lobtail, and capture loop Figure 1: Bubble-net feeding behaviour of humpback whales. Bubble-net feeding is a unique behaviour that can only be observed in humpback whales. In whale optimization algorithm (WOA) the spiral bubble-net feeding maneuver is mathematically modeled in order to perform optimization WOA simulated hunting behaviour with random or the best search agent to chase the prey WOA uses a spiral to simulate bubble-net attacking mechanism of humpback whales Encircling Prey Current best candidate solution is assumed to be closes to target prey and other solutions update their position towards the best agent Where t indicates the current iteration, and are coefficient vectors, is the position vector of the best solution, and indicates the position vector of a grey wolf Where are random vectors in [0, 1]. Bubble-net attacking method (exploitation phase) In order to mathematically model the bubble-net behaviour of humpback whales, two approaches are designed as follows 1. Shrinking encircling mechanismThis behaviour is achieved by decreasing the value of . a is decreased from 2 to 0 over the course of iterations. This behaviour is achieved by decreasing the value of . a is decreased from 2 to 0 over the course of iterations. 2. Spiral updating position (5) is a random number in [-1, 1] (5) is a random number in [-1, 1] Search for prey: Humpback whales search randomly according to the position of each other Step1: Initialize the whales population Step2: Calculate fitness of each search agent = the best search agent Step3: while( t < maximum number of iterations ) for each search agent: Update if(p<0.5): if(|A|<1): Update current agent by eq. (1) else: Select a random agent update current agent by eq (7) else: update search agent by eq (5) end-for Check if any search agent goes beyond the search space and amend it Calculate fitness of each search agent Update if there is a better solution t = t+1 end-while Step4: return https://www.sciencedirect.com/science/article/pii/S0965997816300163 Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Apr, 2021" }, { "code": null, "e": 165, "s": 28, "text": "The step-by-step procedure to obtain an optimum value (maximum or minimum) of an objective function is called an Optimization Algorithm." }, { "code": null, "e": 281, "s": 165, "text": "Meta-heuristic optimization algorithms are becoming more and more popular in engineering applications because they:" }, { "code": null, "e": 338, "s": 281, "text": "rely on rather simple concepts and are easy to implement" }, { "code": null, "e": 374, "s": 338, "text": "do not require gradient information" }, { "code": null, "e": 398, "s": 374, "text": "can bypass local optima" }, { "code": null, "e": 474, "s": 398, "text": "can be utilized in a wide range of problems covering different disciplines." }, { "code": null, "e": 731, "s": 474, "text": "Many scholars and researchers have developed several metaheuristics to address complex/unsolved optimization problems. Example: Particle Swarm Optimization, Grey wolf optimization, Ant colony Optimization, Genetic Algorithms, Cuckoo search algorithm etc. " }, { "code": null, "e": 853, "s": 731, "text": "This article aims to introduce a novel meta-heuristic optimization technique called as Whale Optimization algorithm (WOA)" }, { "code": null, "e": 1063, "s": 853, "text": "Whale optimization algorithm (WOA): A nature inspired meta-heuristic optimization algorithm which mimics the hunting behaviour of humpback whales. The algorithm is inspired by the bubble-net hunting strategy " }, { "code": null, "e": 1356, "s": 1063, "text": "Foraging behavior of Humpback whales is called bubble-net feeding method. Humpback whales prefer to hunt school of krill or small fishes close to the surface. It has been observed that this foraging is done by creating distinctive bubbles along a circle or ‘9’-shaped path as shown in Fig. 1." }, { "code": null, "e": 1446, "s": 1356, "text": "Two maneuvers associated with bubble net feeding are ‘upward-spirals’ and ‘double-loops’." }, { "code": null, "e": 1611, "s": 1446, "text": "In ‘upward-spirals’ maneuver humpback whales dive around 12 m down and then start to create bubble in a spiral shape around the prey and swim up toward the surface." }, { "code": null, "e": 1706, "s": 1611, "text": "‘double-loops’ maneuver includes three different stages: coral loop, lobtail, and capture loop" }, { "code": null, "e": 1765, "s": 1706, "text": "Figure 1: Bubble-net feeding behaviour of humpback whales." }, { "code": null, "e": 1988, "s": 1765, "text": "Bubble-net feeding is a unique behaviour that can only be observed in humpback whales. In whale optimization algorithm (WOA) the spiral bubble-net feeding maneuver is mathematically modeled in order to perform optimization" }, { "code": null, "e": 2075, "s": 1988, "text": "WOA simulated hunting behaviour with random or the best search agent to chase the prey" }, { "code": null, "e": 2155, "s": 2075, "text": "WOA uses a spiral to simulate bubble-net attacking mechanism of humpback whales" }, { "code": null, "e": 2171, "s": 2155, "text": "Encircling Prey" }, { "code": null, "e": 2307, "s": 2171, "text": "Current best candidate solution is assumed to be closes to target prey and other solutions update their position towards the best agent" }, { "code": null, "e": 2476, "s": 2307, "text": "Where t indicates the current iteration, and are coefficient vectors, is the position vector of the best solution, and indicates the position vector of a grey wolf" }, { "code": null, "e": 2513, "s": 2476, "text": "Where are random vectors in [0, 1]." }, { "code": null, "e": 2562, "s": 2513, "text": "Bubble-net attacking method (exploitation phase)" }, { "code": null, "e": 2679, "s": 2562, "text": "In order to mathematically model the bubble-net behaviour of humpback whales, two approaches are designed as follows" }, { "code": null, "e": 2826, "s": 2679, "text": "1. Shrinking encircling mechanismThis behaviour is achieved by decreasing the value of . a is decreased from 2 to 0 over the course of iterations." }, { "code": null, "e": 2940, "s": 2826, "text": "This behaviour is achieved by decreasing the value of . a is decreased from 2 to 0 over the course of iterations." }, { "code": null, "e": 3007, "s": 2940, "text": "2. Spiral updating position (5) is a random number in [-1, 1]" }, { "code": null, "e": 3017, "s": 3007, "text": " (5)" }, { "code": null, "e": 3048, "s": 3017, "text": " is a random number in [-1, 1]" }, { "code": null, "e": 3065, "s": 3048, "text": "Search for prey:" }, { "code": null, "e": 3137, "s": 3065, "text": "Humpback whales search randomly according to the position of each other" }, { "code": null, "e": 3978, "s": 3137, "text": "Step1: Initialize the whales population \nStep2: Calculate fitness of each search agent\n = the best search agent\nStep3: while( t < maximum number of iterations )\n for each search agent:\n Update \n if(p<0.5):\n if(|A|<1):\n Update current agent by eq. (1) \n else:\n Select a random agent \n update current agent by eq (7)\n else:\n update search agent by eq (5)\n end-for\n Check if any search agent goes beyond the search space and amend it\n \n Calculate fitness of each search agent\n \n Update if there is a better solution\n \n t = t+1\n end-while\n Step4: return \n " }, { "code": null, "e": 4046, "s": 3978, "text": "https://www.sciencedirect.com/science/article/pii/S0965997816300163" }, { "code": null, "e": 4063, "s": 4046, "text": "Machine Learning" }, { "code": null, "e": 4080, "s": 4063, "text": "Machine Learning" } ]
Java atan() method with Examples
08 Apr, 2018 The java.lang.Math.atan() returns the arc tangent of an angle in between -pi/2 through pi/2. If the argument is NaN, then the result is NaN. Note:If the argument is zero, then the result is a zero with the same sign as the argument. Syntax : public static double atan(double a) Parameter : a : the value whose arc tangent is to be returned. Return : This method returns the arc tangent of the argument. Example :To show working of java.lang.Math.atan() method. // Java program to demonstrate working// of java.lang.Math.atan() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = Math.PI; System.out.println(Math.atan(a)); double c = 344.0; double d = 0.0; double e = -0.0; double f = 1.5; System.out.println(Math.atan(c)); // Input positive zero // Output positive zero System.out.println(Math.atan(d)); // Input negative zero // Output negative zero System.out.println(Math.atan(e)); System.out.println(Math.atan(f)); }} Output: 1.2626272556789115 1.5678893582391513 0.0 -0.0 0.982793723247329 Java-Library java-math Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Apr, 2018" }, { "code": null, "e": 169, "s": 28, "text": "The java.lang.Math.atan() returns the arc tangent of an angle in between -pi/2 through pi/2. If the argument is NaN, then the result is NaN." }, { "code": null, "e": 261, "s": 169, "text": "Note:If the argument is zero, then the result is a zero with the same sign as the argument." }, { "code": null, "e": 270, "s": 261, "text": "Syntax :" }, { "code": null, "e": 431, "s": 270, "text": "public static double atan(double a)\nParameter :\na : the value whose arc tangent is to be returned.\nReturn :\nThis method returns the arc tangent of the argument." }, { "code": null, "e": 489, "s": 431, "text": "Example :To show working of java.lang.Math.atan() method." }, { "code": "// Java program to demonstrate working// of java.lang.Math.atan() methodimport java.lang.Math; class Gfg { // driver code public static void main(String args[]) { double a = Math.PI; System.out.println(Math.atan(a)); double c = 344.0; double d = 0.0; double e = -0.0; double f = 1.5; System.out.println(Math.atan(c)); // Input positive zero // Output positive zero System.out.println(Math.atan(d)); // Input negative zero // Output negative zero System.out.println(Math.atan(e)); System.out.println(Math.atan(f)); }}", "e": 1131, "s": 489, "text": null }, { "code": null, "e": 1139, "s": 1131, "text": "Output:" }, { "code": null, "e": 1205, "s": 1139, "text": "1.2626272556789115\n1.5678893582391513\n0.0\n-0.0\n0.982793723247329\n" }, { "code": null, "e": 1218, "s": 1205, "text": "Java-Library" }, { "code": null, "e": 1228, "s": 1218, "text": "java-math" }, { "code": null, "e": 1233, "s": 1228, "text": "Java" }, { "code": null, "e": 1238, "s": 1233, "text": "Java" }, { "code": null, "e": 1336, "s": 1238, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1367, "s": 1336, "text": "How to iterate any Map in Java" }, { "code": null, "e": 1386, "s": 1367, "text": "Interfaces in Java" }, { "code": null, "e": 1416, "s": 1386, "text": "HashMap in Java with Examples" }, { "code": null, "e": 1434, "s": 1416, "text": "ArrayList in Java" }, { "code": null, "e": 1449, "s": 1434, "text": "Stream In Java" }, { "code": null, "e": 1469, "s": 1449, "text": "Collections in Java" }, { "code": null, "e": 1493, "s": 1469, "text": "Singleton Class in Java" }, { "code": null, "e": 1525, "s": 1493, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 1537, "s": 1525, "text": "Set in Java" } ]
TCS Coding Practice Question | Check Odd or Even
07 Jul, 2022 Given a number, the task is to check if this number is Odd or Even using Command Line Arguments. A number is called even if the number is divisible by 2 and is called odd if it is not divisible by 2. Examples: Input: 123 Output: No Input: 588 Output: Yes Approach: Since the number is entered as Command line Argument, there is no need for a dedicated input line Extract the input number from the command line argument This extracted number will be in string type. Convert this number into integer type and store it in a variable, say num Check if this number is completely divided by 2 If completely divisible, the number is Even If not completely divisible, the number is Odd Program: C Java // C program to check// if a number is even or odd// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to the check Even or Oddint isEvenOrOdd(int num){ return (num % 2);} // Driver codeint main(int argc, char* argv[]){ int num, res = 0; // Check if the length of args array is 1 if (argc == 1) printf("No command line arguments found.\n"); else { // Get the command line argument and // Convert it from string type to integer type // using function "atoi( argument)" num = atoi(argv[1]); // Check if it is even or odd res = isEvenOrOdd(num); // Check if res is 0 or 1 if (res == 0) // Print Even printf("Even\n"); else // Print Odd printf("Odd\n"); } return 0;} // Java program to check// if a number is even or odd// using command line arguments class GFG { // Function to the check Even or Odd public static int isEvenOrOdd(int num) { return (num % 2); } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num = Integer.parseInt(args[0]); // Get the command line argument // and check if it is even or odd int res = isEvenOrOdd(num); // Check if res is 0 or 1 if (res == 0) // Print Even System.out.println("Even\n"); else // Print Odd System.out.println("Odd\n"); } else System.out.println("No command line " + "arguments found."); }} Output: In C: In Java: Time Complexity: O(1)Auxiliary Space: O(1) jayanth_mkv TCS TCS-coding-questions C++ Programs Java Programs Placements TCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shallow Copy and Deep Copy in C++ C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++? C++ Program for QuickSort delete keyword in C++ Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jul, 2022" }, { "code": null, "e": 255, "s": 53, "text": "Given a number, the task is to check if this number is Odd or Even using Command Line Arguments. A number is called even if the number is divisible by 2 and is called odd if it is not divisible by 2. " }, { "code": null, "e": 265, "s": 255, "text": "Examples:" }, { "code": null, "e": 311, "s": 265, "text": "Input: 123\nOutput: No\n\nInput: 588\nOutput: Yes" }, { "code": null, "e": 321, "s": 311, "text": "Approach:" }, { "code": null, "e": 419, "s": 321, "text": "Since the number is entered as Command line Argument, there is no need for a dedicated input line" }, { "code": null, "e": 475, "s": 419, "text": "Extract the input number from the command line argument" }, { "code": null, "e": 521, "s": 475, "text": "This extracted number will be in string type." }, { "code": null, "e": 595, "s": 521, "text": "Convert this number into integer type and store it in a variable, say num" }, { "code": null, "e": 643, "s": 595, "text": "Check if this number is completely divided by 2" }, { "code": null, "e": 687, "s": 643, "text": "If completely divisible, the number is Even" }, { "code": null, "e": 734, "s": 687, "text": "If not completely divisible, the number is Odd" }, { "code": null, "e": 744, "s": 734, "text": "Program: " }, { "code": null, "e": 746, "s": 744, "text": "C" }, { "code": null, "e": 751, "s": 746, "text": "Java" }, { "code": "// C program to check// if a number is even or odd// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to the check Even or Oddint isEvenOrOdd(int num){ return (num % 2);} // Driver codeint main(int argc, char* argv[]){ int num, res = 0; // Check if the length of args array is 1 if (argc == 1) printf(\"No command line arguments found.\\n\"); else { // Get the command line argument and // Convert it from string type to integer type // using function \"atoi( argument)\" num = atoi(argv[1]); // Check if it is even or odd res = isEvenOrOdd(num); // Check if res is 0 or 1 if (res == 0) // Print Even printf(\"Even\\n\"); else // Print Odd printf(\"Odd\\n\"); } return 0;}", "e": 1595, "s": 751, "text": null }, { "code": "// Java program to check// if a number is even or odd// using command line arguments class GFG { // Function to the check Even or Odd public static int isEvenOrOdd(int num) { return (num % 2); } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num = Integer.parseInt(args[0]); // Get the command line argument // and check if it is even or odd int res = isEvenOrOdd(num); // Check if res is 0 or 1 if (res == 0) // Print Even System.out.println(\"Even\\n\"); else // Print Odd System.out.println(\"Odd\\n\"); } else System.out.println(\"No command line \" + \"arguments found.\"); }}", "e": 2613, "s": 1595, "text": null }, { "code": null, "e": 2621, "s": 2613, "text": "Output:" }, { "code": null, "e": 2628, "s": 2621, "text": "In C: " }, { "code": null, "e": 2638, "s": 2628, "text": "In Java: " }, { "code": null, "e": 2681, "s": 2638, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 2693, "s": 2681, "text": "jayanth_mkv" }, { "code": null, "e": 2697, "s": 2693, "text": "TCS" }, { "code": null, "e": 2718, "s": 2697, "text": "TCS-coding-questions" }, { "code": null, "e": 2731, "s": 2718, "text": "C++ Programs" }, { "code": null, "e": 2745, "s": 2731, "text": "Java Programs" }, { "code": null, "e": 2756, "s": 2745, "text": "Placements" }, { "code": null, "e": 2760, "s": 2756, "text": "TCS" }, { "code": null, "e": 2858, "s": 2760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2892, "s": 2858, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 2952, "s": 2892, "text": "C++ Program to check if a given String is Palindrome or not" }, { "code": null, "e": 3026, "s": 2952, "text": "How to find the minimum and maximum element of a Vector using STL in C++?" }, { "code": null, "e": 3052, "s": 3026, "text": "C++ Program for QuickSort" }, { "code": null, "e": 3074, "s": 3052, "text": "delete keyword in C++" }, { "code": null, "e": 3102, "s": 3074, "text": "Initializing a List in Java" }, { "code": null, "e": 3128, "s": 3102, "text": "Java Programming Examples" }, { "code": null, "e": 3172, "s": 3128, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 3206, "s": 3172, "text": "Convert Double to Integer in Java" } ]
How to print all files within a directory using Python?
29 May, 2021 In this article, we will learn “How to print all files within a directory using Python?”. To do this task we are using the os module in Python. So, let’s discuss some concepts related to that. The os module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the os module is one of the standard packages and comes pre-installed with Python. For this article, the following methods from the os module will be required: 1. os.startfile(): This method prints the contents of a given file. Syntax: os.startfile(path, operation=’open’) Parameters: path – String containing the path to a given file operation – A string containing one of the following ‘command verbs’‘print’ – Prints the file pertaining to path‘edit’ – Opens the file in the default text-editor for editing‘properties’ – Opens the properties window of the given file‘find’ – Initiates a search starting from directory mentioned in the path‘open’ – Opens the application/file pertaining to the path. If the given file is not an executable file, its associated application is opened ‘print’ – Prints the file pertaining to path ‘edit’ – Opens the file in the default text-editor for editing ‘properties’ – Opens the properties window of the given file ‘find’ – Initiates a search starting from directory mentioned in the path ‘open’ – Opens the application/file pertaining to the path. If the given file is not an executable file, its associated application is opened 2. os.listdir(): This method lists all the files and directories within a given directory. For more detailed coverage of this method consisting of examples and use-cases, please refer here. Syntax: os.listdir(path=’.’) Parameters: path – String containing the path of the directory containing the files to be printed Returns: A list containing the names of all the sub -directories and files present in the corresponding directory. 3. os.path.isfile(): As we can only print the given folder’s subdirectories, we’ll use this method to check if a given entity is either a file or a directory. For more detailed coverage of this method consisting of examples and use cases, please refer here. Syntax: os.path.isfile(path) Parameters: path – String containing the path of the entity being checked Returns: True if path corresponds to a file, else returns False Note: Aside from the above modules, you’ll also need a fully functional printer connected to your PC! Implementation The line of code “time.sleep(5)” of the given script is completely optional and is just there to avoid any un-necessary glitching or overlapping of the operations in consecutive files. For reading more about the time.sleep() method, please refer to here. Python # Import librariesimport osimport time # Insert the directory path in herepath = '' # Extracting all the contents in the directory corresponding to pathl_files = os.listdir(path) # Iterating over all the filesfor file in l_files: # Instantiating the path of the file file_path = f'{path}\\{file}' # Checking whether the given file is a directory or not if os.path.isfile(file_path): try: # Printing the file pertaining to file_path os.startfile(file_path, 'print') print(f'Printing {file}') # Sleeping the program for 5 seconds so as to account the # steady processing of the print operation. time.sleep(5) except: # Catching if any error occurs and alerting the user print(f'ALERT: {file} could not be printed! Please check\ the associated softwares, or the file type.') else: print(f'ALERT: {file} is not a file, so can not be printed!') print('Task finished!') Output: The demo was done on a Windows 10 machine. The environment is as follows: Path of the directory containing files being printed: “Local Disk (D):/Files” Files in the given directory:Dir – A sample subdirectoryFile_a.pdf – A sample .pdf fileFile_b.txt – A sample .txt fileFile_c.docx – A sample .docx file Dir – A sample subdirectory File_a.pdf – A sample .pdf file File_b.txt – A sample .txt file File_c.docx – A sample .docx file Note: Since os.startfile() is only available in Windows operating system, so macOS and Linux users might experience some issues while running the script given in the article. sumitgumber28 python-file-handling python-utility Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 54, "s": 26, "text": "\n29 May, 2021" }, { "code": null, "e": 247, "s": 54, "text": "In this article, we will learn “How to print all files within a directory using Python?”. To do this task we are using the os module in Python. So, let’s discuss some concepts related to that." }, { "code": null, "e": 510, "s": 247, "text": "The os module is one of the most popular Python modules for automating the systems calls and operations of an operating system. With a rich set of methods and an easy-to-use API, the os module is one of the standard packages and comes pre-installed with Python. " }, { "code": null, "e": 587, "s": 510, "text": "For this article, the following methods from the os module will be required:" }, { "code": null, "e": 655, "s": 587, "text": "1. os.startfile(): This method prints the contents of a given file." }, { "code": null, "e": 700, "s": 655, "text": "Syntax: os.startfile(path, operation=’open’)" }, { "code": null, "e": 712, "s": 700, "text": "Parameters:" }, { "code": null, "e": 762, "s": 712, "text": "path – String containing the path to a given file" }, { "code": null, "e": 1211, "s": 762, "text": "operation – A string containing one of the following ‘command verbs’‘print’ – Prints the file pertaining to path‘edit’ – Opens the file in the default text-editor for editing‘properties’ – Opens the properties window of the given file‘find’ – Initiates a search starting from directory mentioned in the path‘open’ – Opens the application/file pertaining to the path. If the given file is not an executable file, its associated application is opened" }, { "code": null, "e": 1256, "s": 1211, "text": "‘print’ – Prints the file pertaining to path" }, { "code": null, "e": 1319, "s": 1256, "text": "‘edit’ – Opens the file in the default text-editor for editing" }, { "code": null, "e": 1380, "s": 1319, "text": "‘properties’ – Opens the properties window of the given file" }, { "code": null, "e": 1454, "s": 1380, "text": "‘find’ – Initiates a search starting from directory mentioned in the path" }, { "code": null, "e": 1596, "s": 1454, "text": "‘open’ – Opens the application/file pertaining to the path. If the given file is not an executable file, its associated application is opened" }, { "code": null, "e": 1786, "s": 1596, "text": "2. os.listdir(): This method lists all the files and directories within a given directory. For more detailed coverage of this method consisting of examples and use-cases, please refer here." }, { "code": null, "e": 1815, "s": 1786, "text": "Syntax: os.listdir(path=’.’)" }, { "code": null, "e": 1828, "s": 1815, "text": "Parameters: " }, { "code": null, "e": 1914, "s": 1828, "text": "path – String containing the path of the directory containing the files to be printed" }, { "code": null, "e": 2029, "s": 1914, "text": "Returns: A list containing the names of all the sub -directories and files present in the corresponding directory." }, { "code": null, "e": 2287, "s": 2029, "text": "3. os.path.isfile(): As we can only print the given folder’s subdirectories, we’ll use this method to check if a given entity is either a file or a directory. For more detailed coverage of this method consisting of examples and use cases, please refer here." }, { "code": null, "e": 2316, "s": 2287, "text": "Syntax: os.path.isfile(path)" }, { "code": null, "e": 2328, "s": 2316, "text": "Parameters:" }, { "code": null, "e": 2390, "s": 2328, "text": "path – String containing the path of the entity being checked" }, { "code": null, "e": 2454, "s": 2390, "text": "Returns: True if path corresponds to a file, else returns False" }, { "code": null, "e": 2556, "s": 2454, "text": "Note: Aside from the above modules, you’ll also need a fully functional printer connected to your PC!" }, { "code": null, "e": 2571, "s": 2556, "text": "Implementation" }, { "code": null, "e": 2826, "s": 2571, "text": "The line of code “time.sleep(5)” of the given script is completely optional and is just there to avoid any un-necessary glitching or overlapping of the operations in consecutive files. For reading more about the time.sleep() method, please refer to here." }, { "code": null, "e": 2833, "s": 2826, "text": "Python" }, { "code": "# Import librariesimport osimport time # Insert the directory path in herepath = '' # Extracting all the contents in the directory corresponding to pathl_files = os.listdir(path) # Iterating over all the filesfor file in l_files: # Instantiating the path of the file file_path = f'{path}\\\\{file}' # Checking whether the given file is a directory or not if os.path.isfile(file_path): try: # Printing the file pertaining to file_path os.startfile(file_path, 'print') print(f'Printing {file}') # Sleeping the program for 5 seconds so as to account the # steady processing of the print operation. time.sleep(5) except: # Catching if any error occurs and alerting the user print(f'ALERT: {file} could not be printed! Please check\\ the associated softwares, or the file type.') else: print(f'ALERT: {file} is not a file, so can not be printed!') print('Task finished!')", "e": 3837, "s": 2833, "text": null }, { "code": null, "e": 3849, "s": 3841, "text": "Output:" }, { "code": null, "e": 3925, "s": 3851, "text": "The demo was done on a Windows 10 machine. The environment is as follows:" }, { "code": null, "e": 4005, "s": 3927, "text": "Path of the directory containing files being printed: “Local Disk (D):/Files”" }, { "code": null, "e": 4157, "s": 4005, "text": "Files in the given directory:Dir – A sample subdirectoryFile_a.pdf – A sample .pdf fileFile_b.txt – A sample .txt fileFile_c.docx – A sample .docx file" }, { "code": null, "e": 4185, "s": 4157, "text": "Dir – A sample subdirectory" }, { "code": null, "e": 4217, "s": 4185, "text": "File_a.pdf – A sample .pdf file" }, { "code": null, "e": 4249, "s": 4217, "text": "File_b.txt – A sample .txt file" }, { "code": null, "e": 4283, "s": 4249, "text": "File_c.docx – A sample .docx file" }, { "code": null, "e": 4460, "s": 4285, "text": "Note: Since os.startfile() is only available in Windows operating system, so macOS and Linux users might experience some issues while running the script given in the article." }, { "code": null, "e": 4476, "s": 4462, "text": "sumitgumber28" }, { "code": null, "e": 4497, "s": 4476, "text": "python-file-handling" }, { "code": null, "e": 4512, "s": 4497, "text": "python-utility" }, { "code": null, "e": 4536, "s": 4512, "text": "Technical Scripter 2020" }, { "code": null, "e": 4543, "s": 4536, "text": "Python" }, { "code": null, "e": 4562, "s": 4543, "text": "Technical Scripter" }, { "code": null, "e": 4660, "s": 4562, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4692, "s": 4660, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4719, "s": 4692, "text": "Python Classes and Objects" }, { "code": null, "e": 4740, "s": 4719, "text": "Python OOPs Concepts" }, { "code": null, "e": 4763, "s": 4740, "text": "Introduction To PYTHON" }, { "code": null, "e": 4794, "s": 4763, "text": "Python | os.path.join() method" }, { "code": null, "e": 4850, "s": 4794, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4892, "s": 4850, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4934, "s": 4892, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4973, "s": 4934, "text": "Python | Get unique values from a list" } ]
MongoDB NOT operator ( $not )
22 Apr, 2020 MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don’t contain the field. You can use this operator in methods like find(), update(), etc. according to your requirements. Always use the $not operator with other operators because it cannot check the fields and documents independently and only affects other operators. You can use the $not operator with regular expressions. This operation of this operator is consistent with the behavior of other operators, but it may give some unexpected results with some data types like arrays. Syntax: { field: { $not: { operator-expression } } } In the following examples, we are working with: Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs. In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000. db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty() In this example, we are retrieving only those employee’s documents whose age is not equal to 24. db.contributor.find({"personal.age": {$not: {$eq: 24}}}).pretty() In this example, we are retrieving only those employee’s documents that does not match the given array. db.contributor.find({language: {$not: {$in: ["Java", "Perl"]}}}).pretty() MongoDB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Copying Files to and from Docker Containers Basics of API Testing Using Postman Markov Decision Process Getting Started with System Design Principal Component Analysis with Python How to create a REST API using Java Spring Boot Monolithic vs Microservices architecture Mounting a Volume Inside Docker Container Fuzzy Logic | Introduction
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 468, "s": 28, "text": "MongoDB provides different types of logical query operators and $not operator is one of them. This operator is used to perform logical NOT operation on the specified operator expressions and select or retrieve only those documents that do not match the given operator expression. It also includes those documents that don’t contain the field. You can use this operator in methods like find(), update(), etc. according to your requirements." }, { "code": null, "e": 615, "s": 468, "text": "Always use the $not operator with other operators because it cannot check the fields and documents independently and only affects other operators." }, { "code": null, "e": 671, "s": 615, "text": "You can use the $not operator with regular expressions." }, { "code": null, "e": 829, "s": 671, "text": "This operation of this operator is consistent with the behavior of other operators, but it may give some unexpected results with some data types like arrays." }, { "code": null, "e": 837, "s": 829, "text": "Syntax:" }, { "code": null, "e": 882, "s": 837, "text": "{ field: { $not: { operator-expression } } }" }, { "code": null, "e": 930, "s": 882, "text": "In the following examples, we are working with:" }, { "code": null, "e": 1081, "s": 930, "text": "Database: GeeksforGeeksCollection: contributorDocument: three documents that contain the details of the contributors in the form of field-value pairs." }, { "code": null, "e": 1187, "s": 1081, "text": "In this example, we are retrieving only those employee’s documents whose salary is not greater than 2000." }, { "code": "db.contributor.find({salary: {$not: {$gt: 2000}}}).pretty()", "e": 1247, "s": 1187, "text": null }, { "code": null, "e": 1344, "s": 1247, "text": "In this example, we are retrieving only those employee’s documents whose age is not equal to 24." }, { "code": "db.contributor.find({\"personal.age\": {$not: {$eq: 24}}}).pretty()", "e": 1410, "s": 1344, "text": null }, { "code": null, "e": 1514, "s": 1410, "text": "In this example, we are retrieving only those employee’s documents that does not match the given array." }, { "code": "db.contributor.find({language: {$not: {$in: [\"Java\", \"Perl\"]}}}).pretty()", "e": 1588, "s": 1514, "text": null }, { "code": null, "e": 1596, "s": 1588, "text": "MongoDB" }, { "code": null, "e": 1622, "s": 1596, "text": "Advanced Computer Subject" }, { "code": null, "e": 1720, "s": 1622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1756, "s": 1720, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 1800, "s": 1756, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 1836, "s": 1800, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 1860, "s": 1836, "text": "Markov Decision Process" }, { "code": null, "e": 1895, "s": 1860, "text": "Getting Started with System Design" }, { "code": null, "e": 1936, "s": 1895, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 1984, "s": 1936, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 2025, "s": 1984, "text": "Monolithic vs Microservices architecture" }, { "code": null, "e": 2067, "s": 2025, "text": "Mounting a Volume Inside Docker Container" } ]
Count numbers have all 1s together in binary representation
24 Jun, 2022 Given an integer n, the task is to count the total lucky numbers smaller than or equal to n. A number is said to be lucky if it has all contagious number of 1’s in binary representation from the beginning. For example 1, 3, 7, 15 are lucky numbers, and 2, 5 and 9 are not lucky numbers.Examples: Input :n = 7 Output :3 1, 3 and 7 are lucky numbers Input :n = 17 Output :4 Approach:one approach is that first we find out the binary representation of each number and than check for contagious number of 1’s for each number, but this approach is time consuming and can give tle if the constraints are two large, Efficient approach can be find out by observing the numbers, we can say that every ith lucky number can be found by the formula 2i-1, and by iterating a loop upto number less than equal to n we can find out the total lucky numbers.Below is the implementation of above approach CPP Java Python C# PHP Javascript #include <bits/stdc++.h>using namespace std; int countLuckyNum(int n){ int count = 0, i = 1; while (1) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count;} // Driver codeint main(){ int n = 7; cout << countLuckyNum(n); return 0;} import java.util.*;import java.lang.*;import java.io.*; public class GFG { // Function to return the count of lucky number static int countLuckyNum(int n) { int count = 0, i = 1; while (true) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count; } // Driver code public static void main(String[] args) { int n = 7; System.out.println(countLuckyNum(n)); }} # python3 code of above problem # function to count the lucky number def countLuckyNum(n): count, i = 0, 1 while True: if n>= 2**i-1: count+= 1 else: break i+= 1; return count # driver coden = 7 print(countLuckyNum(n)) // C# implementation of the approachusing System; public class GFG { // Function to return the count of lucky number static int countLuckyNum(int n) { int count = 0, i = 1; while (true) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count; } // Driver code public static void Main() { int n = 7; Console.WriteLine(countLuckyNum(n)); }} <?php// PHP implementation of the approach // Function to count the lucky numberfunction countLuckyNum($n) { $count = 0; $i = 1; while(1) { if ($n >= ((1 << $i) - 1)) $count += 1; else break; $i += 1; } return $count; } // Driver code $n = 7;echo countLuckyNum($n) ; ?> <script> // Function to return the count of lucky number function countLuckyNum(n) { var count = 0, i = 1; while (true) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count; } // Driver code var n = 7; document.write(countLuckyNum(n)); // This code is contributed by aashish1995</script> output:3 Time Complexity: O(logn) Auxiliary Space: O(1) aashish1995 souravmahato348 binary-representation Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal Find total no of collisions taking place between the balls in which initial direction of each ball is given Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Segment Tree | Set 1 (Sum of given range) Program to print prime numbers from 1 to N. Fizz Buzz Implementation Merge two sorted arrays with O(1) extra space Median of two sorted arrays of same size
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2022" }, { "code": null, "e": 326, "s": 28, "text": "Given an integer n, the task is to count the total lucky numbers smaller than or equal to n. A number is said to be lucky if it has all contagious number of 1’s in binary representation from the beginning. For example 1, 3, 7, 15 are lucky numbers, and 2, 5 and 9 are not lucky numbers.Examples: " }, { "code": null, "e": 404, "s": 326, "text": "Input :n = 7 \nOutput :3\n1, 3 and 7 are lucky numbers\n\nInput :n = 17\nOutput :4" }, { "code": null, "e": 922, "s": 406, "text": "Approach:one approach is that first we find out the binary representation of each number and than check for contagious number of 1’s for each number, but this approach is time consuming and can give tle if the constraints are two large, Efficient approach can be find out by observing the numbers, we can say that every ith lucky number can be found by the formula 2i-1, and by iterating a loop upto number less than equal to n we can find out the total lucky numbers.Below is the implementation of above approach " }, { "code": null, "e": 926, "s": 922, "text": "CPP" }, { "code": null, "e": 931, "s": 926, "text": "Java" }, { "code": null, "e": 938, "s": 931, "text": "Python" }, { "code": null, "e": 941, "s": 938, "text": "C#" }, { "code": null, "e": 945, "s": 941, "text": "PHP" }, { "code": null, "e": 956, "s": 945, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; int countLuckyNum(int n){ int count = 0, i = 1; while (1) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count;} // Driver codeint main(){ int n = 7; cout << countLuckyNum(n); return 0;}", "e": 1269, "s": 956, "text": null }, { "code": "import java.util.*;import java.lang.*;import java.io.*; public class GFG { // Function to return the count of lucky number static int countLuckyNum(int n) { int count = 0, i = 1; while (true) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count; } // Driver code public static void main(String[] args) { int n = 7; System.out.println(countLuckyNum(n)); }}", "e": 1772, "s": 1269, "text": null }, { "code": "# python3 code of above problem # function to count the lucky number def countLuckyNum(n): count, i = 0, 1 while True: if n>= 2**i-1: count+= 1 else: break i+= 1; return count # driver coden = 7 print(countLuckyNum(n))", "e": 2057, "s": 1772, "text": null }, { "code": "// C# implementation of the approachusing System; public class GFG { // Function to return the count of lucky number static int countLuckyNum(int n) { int count = 0, i = 1; while (true) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count; } // Driver code public static void Main() { int n = 7; Console.WriteLine(countLuckyNum(n)); }}", "e": 2540, "s": 2057, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to count the lucky numberfunction countLuckyNum($n) { $count = 0; $i = 1; while(1) { if ($n >= ((1 << $i) - 1)) $count += 1; else break; $i += 1; } return $count; } // Driver code $n = 7;echo countLuckyNum($n) ; ?>", "e": 2883, "s": 2540, "text": null }, { "code": "<script> // Function to return the count of lucky number function countLuckyNum(n) { var count = 0, i = 1; while (true) { if (n >= ((1 << i) - 1)) count++; else break; i++; } return count; } // Driver code var n = 7; document.write(countLuckyNum(n)); // This code is contributed by aashish1995</script>", "e": 3298, "s": 2883, "text": null }, { "code": null, "e": 3307, "s": 3298, "text": "output:3" }, { "code": null, "e": 3332, "s": 3307, "text": "Time Complexity: O(logn)" }, { "code": null, "e": 3354, "s": 3332, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3366, "s": 3354, "text": "aashish1995" }, { "code": null, "e": 3382, "s": 3366, "text": "souravmahato348" }, { "code": null, "e": 3404, "s": 3382, "text": "binary-representation" }, { "code": null, "e": 3417, "s": 3404, "text": "Mathematical" }, { "code": null, "e": 3430, "s": 3417, "text": "Mathematical" }, { "code": null, "e": 3528, "s": 3430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3560, "s": 3528, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 3654, "s": 3560, "text": "Find a number X such that (X XOR A) is minimum and the count of set bits in X and B are equal" }, { "code": null, "e": 3762, "s": 3654, "text": "Find total no of collisions taking place between the balls in which initial direction of each ball is given" }, { "code": null, "e": 3833, "s": 3762, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 3866, "s": 3833, "text": "Program to multiply two matrices" }, { "code": null, "e": 3908, "s": 3866, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 3952, "s": 3908, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 3977, "s": 3952, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 4023, "s": 3977, "text": "Merge two sorted arrays with O(1) extra space" } ]
C# | Overloading of Indexers
23 Jan, 2019 Like functions, Indexers can also be overloaded. In C#, we can have multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters. It is quite similar to method overloading. Example 1: In the below program int and float types are used to overload the indexer. Here, “Hello” word is assigned using the int indexer whereas the float parameter is used to give the value “Geeks” to the string. // C# Program to illustrate // the overloading of indexersusing System; namespace HelloGeeksApp { class HelloGeeks { // private array of // strings with size 2 private string[] word = new string[2]; // this indexer gets executed // when Obj[0]gets executed public string this[int flag] { // using get accessor get { string temp = word[flag]; return temp; } // using set accessor set { word[flag] = value; } } // this is an Overloaded indexer // which will execute when // Obj[1.0f] gets executed public string this[float flag] { // using get accessor get { string temp = word[1]; return temp; } // using set accessor set { // it will set value of // the private string // assigned in main word[1] = value; } } // Main Methodstatic void Main(string[] args){ HelloGeeks Obj = new HelloGeeks(); Obj[0] = "Hello"; // Value of word[0] Obj[1.0f] = " Geeks"; // Value of word[1] Console.WriteLine(Obj[0] + Obj[1.0f]);}}} Hello Geeks Example 2: In the below program, we are using only get accessor in overloaded indexer which enables the read-only mode. Means we can’t modify the given value. Here int and string types are used to overload the indexer. public string this[string flag] contain only get accessor which enables the read-only mode. // C# program to illustrate the concept// of indexer overloading by taking // only get accessor in overloaded indexerusing System; namespace Geeks { class G4G { // private array of // strings with size 2 private string[] str = new string[2]; // this indexer gets called // when Obj[0] gets executed public string this[int flag] { // using get accessor get { string temp = str[flag]; return temp; } // using set accessor set { str[flag] = value; } } // this indexer gets called // when Obj["GFG"] gets executed public string this[string flag] { // using get accessor get { return " C# Indexers Overloading."; // read only mode } } // Driver Code static void Main(string[] args){ G4G Obj = new G4G(); Obj[0] = "This is"; // Value of str[0] Console.WriteLine(Obj[0] + Obj["GFG"]);}}} This is C# Indexers Overloading. Note: The indexer overloading cannot be done by just changing the return type of the get block. CSharp-Indexers & Properties Picked Technical Scripter 2018 C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jan, 2019" }, { "code": null, "e": 358, "s": 28, "text": "Like functions, Indexers can also be overloaded. In C#, we can have multiple indexers in a single class. To overload an indexer, declare it with multiple parameters and each parameter should have a different data type. Indexers are overloaded by passing 2 different types of parameters. It is quite similar to method overloading." }, { "code": null, "e": 574, "s": 358, "text": "Example 1: In the below program int and float types are used to overload the indexer. Here, “Hello” word is assigned using the int indexer whereas the float parameter is used to give the value “Geeks” to the string." }, { "code": "// C# Program to illustrate // the overloading of indexersusing System; namespace HelloGeeksApp { class HelloGeeks { // private array of // strings with size 2 private string[] word = new string[2]; // this indexer gets executed // when Obj[0]gets executed public string this[int flag] { // using get accessor get { string temp = word[flag]; return temp; } // using set accessor set { word[flag] = value; } } // this is an Overloaded indexer // which will execute when // Obj[1.0f] gets executed public string this[float flag] { // using get accessor get { string temp = word[1]; return temp; } // using set accessor set { // it will set value of // the private string // assigned in main word[1] = value; } } // Main Methodstatic void Main(string[] args){ HelloGeeks Obj = new HelloGeeks(); Obj[0] = \"Hello\"; // Value of word[0] Obj[1.0f] = \" Geeks\"; // Value of word[1] Console.WriteLine(Obj[0] + Obj[1.0f]);}}}", "e": 1872, "s": 574, "text": null }, { "code": null, "e": 1885, "s": 1872, "text": "Hello Geeks\n" }, { "code": null, "e": 2196, "s": 1885, "text": "Example 2: In the below program, we are using only get accessor in overloaded indexer which enables the read-only mode. Means we can’t modify the given value. Here int and string types are used to overload the indexer. public string this[string flag] contain only get accessor which enables the read-only mode." }, { "code": "// C# program to illustrate the concept// of indexer overloading by taking // only get accessor in overloaded indexerusing System; namespace Geeks { class G4G { // private array of // strings with size 2 private string[] str = new string[2]; // this indexer gets called // when Obj[0] gets executed public string this[int flag] { // using get accessor get { string temp = str[flag]; return temp; } // using set accessor set { str[flag] = value; } } // this indexer gets called // when Obj[\"GFG\"] gets executed public string this[string flag] { // using get accessor get { return \" C# Indexers Overloading.\"; // read only mode } } // Driver Code static void Main(string[] args){ G4G Obj = new G4G(); Obj[0] = \"This is\"; // Value of str[0] Console.WriteLine(Obj[0] + Obj[\"GFG\"]);}}}", "e": 3218, "s": 2196, "text": null }, { "code": null, "e": 3252, "s": 3218, "text": "This is C# Indexers Overloading.\n" }, { "code": null, "e": 3348, "s": 3252, "text": "Note: The indexer overloading cannot be done by just changing the return type of the get block." }, { "code": null, "e": 3377, "s": 3348, "text": "CSharp-Indexers & Properties" }, { "code": null, "e": 3384, "s": 3377, "text": "Picked" }, { "code": null, "e": 3408, "s": 3384, "text": "Technical Scripter 2018" }, { "code": null, "e": 3411, "s": 3408, "text": "C#" }, { "code": null, "e": 3430, "s": 3411, "text": "Technical Scripter" } ]
Rabin-Karp Algorithm for Pattern Searching
25 Jun, 2022 Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m. Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12 The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match. Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.1) Pattern itself. 2) All the substrings of the text of length m. Since we need to efficiently calculate hash values for all the substrings of size m of text, we must have a hash function which has the following property. Hash at the next shift must be efficiently computable from the current hash value and next character in text or we can say hash(txt[s+1 .. s+m]) must be efficiently computable from hash(txt[s .. s+m-1]) and txt[s+m] i.e., hash(txt[s+1 .. s+m])= rehash(txt[s+m], hash(txt[s .. s+m-1])) and rehash must be O(1) operation.The hash function suggested by Rabin and Karp calculates an integer value. The integer value for a string is the numeric value of a string. 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. For example, if all possible characters are from 1 to 10, the numeric value of “122” will be 122. The number of possible characters is higher than 10 (256 in general) and pattern length can be large. So the numeric values cannot be practically stored as an integer. Therefore, the numeric value is calculated using modular arithmetic to make sure that the hash values can be stored in an integer variable (can fit in memory words). To do rehashing, we need to take off the most significant digit and add the new least significant digit for in hash value. Rehashing is done using the following formula. hash( txt[s+1 .. s+m] ) = ( d ( hash( txt[s .. s+m-1]) – txt[s]*h ) + txt[s + m] ) mod q hash( txt[s .. s+m-1] ) : Hash value at shift s. hash( txt[s+1 .. s+m] ) : Hash value at next shift (or shift s+1) d: Number of characters in the alphabet q: A prime number h: d^(m-1) How does the above expression work? This is simple mathematics, we compute decimal value of current window from previous window. For example pattern length is 3 and string is “23456” You compute the value of first window (which is “234”) as 234. How will you compute value of next window “345”? You will do (234 – 2*100)*10 + 5 and get 345. C++ C Java Python3 C# PHP Javascript /* Following program is a C++ implementation of Rabin Karp Algorithm given in the CLRS book */#include <bits/stdc++.h>using namespace std; // d is the number of characters in the input alphabet #define d 256 /* pat -> pattern txt -> text q -> A prime number */void search(char pat[], char txt[], int q) { int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat[i]) % q; t = (d * t + txt[i]) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) { break; } } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) cout<<"Pattern found at index "<< i<<endl; } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt[i]*h) + txt[i+M])%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver code */int main() { char txt[] = "GEEKS FOR GEEKS"; char pat[] = "GEEK"; //we mod to avoid overflowing of value but we should take as big q as possible to avoid the collison int q =INT_MAX; // Function Call search(pat, txt, q); return 0; } // This is code is contributed by rathbhupendra /* Following program is a C implementation of Rabin KarpAlgorithm given in the CLRS book */#include<stdio.h>#include<string.h> // d is the number of characters in the input alphabet#define d 256 /* pat -> pattern txt -> text q -> A prime number*/void search(char pat[], char txt[], int q){ int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat[i])%q; t = (d*t + txt[i])%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) printf("Pattern found at index %d \n", i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt[i]*h) + txt[i+M])%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } }} /* Driver Code */int main(){ char txt[] = "GEEKS FOR GEEKS"; char pat[] = "GEEK"; // A prime number int q = 101; // function call search(pat, txt, q); return 0;} // Following program is a Java implementation // of Rabin Karp Algorithm given in the CLRS book public class Main { // d is the number of characters in the input alphabet public final static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat.charAt(i))%q; t = (d*t + txt.charAt(i))%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt.charAt(i+j) != pat.charAt(j)) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) System.out.println("Pattern found at index " + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver Code */ public static void main(String[] args) { String txt = "GEEKS FOR GEEKS"; String pat = "GEEK"; // A prime number int q = 101; // Function Call search(pat, txt, q); }} // This code is contributed by nuclode # Following program is the python implementation of# Rabin Karp Algorithm given in CLRS book # d is the number of characters in the input alphabetd = 256 # pat -> pattern# txt -> text# q -> A prime number def search(pat, txt, q): M = len(pat) N = len(txt) i = 0 j = 0 p = 0 # hash value for pattern t = 0 # hash value for txt h = 1 # The value of h would be "pow(d, M-1)%q" for i in range(M-1): h = (h*d)%q # Calculate the hash value of pattern and first window # of text for i in range(M): p = (d*p + ord(pat[i]))%q t = (d*t + ord(txt[i]))%q # Slide the pattern over text one by one for i in range(N-M+1): # Check the hash values of current window of text and # pattern if the hash values match then only check # for characters one by one if p==t: # Check for characters one by one for j in range(M): if txt[i+j] != pat[j]: break else: j+=1 # if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if j==M: print ("Pattern found at index " + str(i)) # Calculate hash value for next window of text: Remove # leading digit, add trailing digit if i < N-M: t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%q # We might get negative values of t, converting it to # positive if t < 0: t = t+q # Driver Codetxt = "GEEKS FOR GEEKS"pat = "GEEK" # A prime numberq = 101 # Function Callsearch(pat,txt,q) # This code is contributed by Bhavya Jain // Following program is a C# implementation // of Rabin Karp Algorithm given in the CLRS book using System;public class GFG { // d is the number of characters in the input alphabet public readonly static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.Length; int N = txt.Length; int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be "pow(d, M-1)%q" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat[i])%q; t = (d*t + txt[i])%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) Console.WriteLine("Pattern found at index " + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt[i]*h) + txt[i+M])%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver Code */ public static void Main() { String txt = "GEEKS FOR GEEKS"; String pat = "GEEK"; // A prime number int q = 101; // Function Call search(pat, txt, q); } } // This code is contributed by PrinciRaj19992 <?php// Following program is a PHP // implementation of Rabin Karp// Algorithm given in the CLRS book // d is the number of characters// in the input alphabet$d = 256; /* pat -> pattern txt -> text q -> A prime number*/function search($pat, $txt, $q){ $M = strlen($pat); $N = strlen($txt); $i; $j; $p = 0; // hash value // for pattern $t = 0; // hash value // for txt $h = 1; $d =1; // The value of h would // be "pow(d, M-1)%q" for ($i = 0; $i < $M - 1; $i++) $h = ($h * $d) % $q; // Calculate the hash value // of pattern and first // window of text for ($i = 0; $i < $M; $i++) { $p = ($d * $p + $pat[$i]) % $q; $t = ($d * $t + $txt[$i]) % $q; } // Slide the pattern over // text one by one for ($i = 0; $i <= $N - $M; $i++) { // Check the hash values of // current window of text // and pattern. If the hash // values match then only // check for characters one // by one if ($p == $t) { // Check for characters // one by one for ($j = 0; $j < $M; $j++) { if ($txt[$i + $j] != $pat[$j]) break; } // if p == t and pat[0...M-1] = // txt[i, i+1, ...i+M-1] if ($j == $M) echo "Pattern found at index ", $i, "\n"; } // Calculate hash value for // next window of text: // Remove leading digit, // add trailing digit if ($i < $N - $M) { $t = ($d * ($t - $txt[$i] * $h) + $txt[$i + $M]) % $q; // We might get negative // value of t, converting // it to positive if ($t < 0) $t = ($t + $q); } }} // Driver Code$txt = "GEEKS FOR GEEKS";$pat = "GEEK"; // A prime number$q = 101; // Function Callsearch($pat, $txt, $q); // This code is contributed// by ajit?> <script> // Following program is a Javascript implementation // of Rabin Karp Algorithm given in the CLRS book // d is the number of characters in// the input alphabet let d = 256; /* pat -> pattern txt -> text q -> A prime number */function search(pat, txt, q) { let M = pat.length; let N = txt.length; let i, j; // Hash value for pattern let p = 0; // Hash value for txt let t = 0; let h = 1; // The value of h would be "pow(d, M-1)%q" for(i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and // first window of text for(i = 0; i < M; i++) { p = (d * p + pat[i].charCodeAt()) % q; t = (d * t + txt[i].charCodeAt()) % q; } // Slide the pattern over text one by one for(i = 0; i <= N - M; i++) { // Check the hash values of current // window of text and pattern. If the // hash values match then only // check for characters one by one if (p == t) { /* Check for characters one by one */ for(j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = // txt[i, i+1, ...i+M-1] if (j == M) document.write("Pattern found at index " + i + "<br/>"); } // Calculate hash value for next window // of text: Remove leading digit, add // trailing digit if (i < N - M) { t = (d * (t - txt[i].charCodeAt() * h) + txt[i + M].charCodeAt()) % q; // We might get negative value of t, // converting it to positive if (t < 0) t = (t + q); } } } // Driver codelet txt = "GEEKS FOR GEEKS";let pat = "GEEK"; // A prime numberlet q = 101; // Function Callsearch(pat, txt, q); // This code is contributed by target_2 </script> Pattern found at index 0 Pattern found at index 10 Time Complexity:The average and best-case running time of the Rabin-Karp algorithm is O(n+m), but its worst-case time is O(nm). Worst case of Rabin-Karp algorithm occurs when all characters of pattern and text are same as the hash values of all the substrings of txt[] match with hash value of pat[]. For example pat[] = “AAA” and txt[] = “AAAAAAA”. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References:http://net.pku.edu.cn/~course/cs101/2007/resource/Intro2Algorithm/book6/chap34.htmhttp://www.cs.princeton.edu/courses/archive/fall04/cos226/lectures/string.4up.pdfhttp://en.wikipedia.org/wiki/Rabin-Karp_string_search_algorithmRelated Posts: Searching for Patterns | Set 1 (Naive Pattern Searching) Searching for Patterns | Set 2 (KMP Algorithm) Hao Lee jit_t princiraj1992 rathbhupendra KoushikChowdhury sebibek target_2 architgwl2000 chindaliyalavan amartyaghoshgfg simmytarika5 tylerstown23 parasjaggi20 Modular Arithmetic Pattern Searching Modular Arithmetic Pattern Searching Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jun, 2022" }, { "code": null, "e": 228, "s": 54, "text": "Given a text txt[0..n-1] and a pattern pat[0..m-1], write a function search(char pat[], char txt[]) that prints all occurrences of pat[] in txt[]. You may assume that n > m." }, { "code": null, "e": 239, "s": 228, "text": "Examples: " }, { "code": null, "e": 495, "s": 239, "text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12" }, { "code": null, "e": 1133, "s": 495, "text": "The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match. Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings.1) Pattern itself. 2) All the substrings of the text of length m. " }, { "code": null, "e": 1749, "s": 1133, "text": "Since we need to efficiently calculate hash values for all the substrings of size m of text, we must have a hash function which has the following property. Hash at the next shift must be efficiently computable from the current hash value and next character in text or we can say hash(txt[s+1 .. s+m]) must be efficiently computable from hash(txt[s .. s+m-1]) and txt[s+m] i.e., hash(txt[s+1 .. s+m])= rehash(txt[s+m], hash(txt[s .. s+m-1])) and rehash must be O(1) operation.The hash function suggested by Rabin and Karp calculates an integer value. The integer value for a string is the numeric value of a string. " }, { "code": null, "e": 1758, "s": 1749, "text": "Chapters" }, { "code": null, "e": 1785, "s": 1758, "text": "descriptions off, selected" }, { "code": null, "e": 1835, "s": 1785, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1858, "s": 1835, "text": "captions off, selected" }, { "code": null, "e": 1866, "s": 1858, "text": "English" }, { "code": null, "e": 1890, "s": 1866, "text": "This is a modal window." }, { "code": null, "e": 1959, "s": 1890, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1981, "s": 1959, "text": "End of dialog window." }, { "code": null, "e": 2584, "s": 1981, "text": "For example, if all possible characters are from 1 to 10, the numeric value of “122” will be 122. The number of possible characters is higher than 10 (256 in general) and pattern length can be large. So the numeric values cannot be practically stored as an integer. Therefore, the numeric value is calculated using modular arithmetic to make sure that the hash values can be stored in an integer variable (can fit in memory words). To do rehashing, we need to take off the most significant digit and add the new least significant digit for in hash value. Rehashing is done using the following formula. " }, { "code": null, "e": 2857, "s": 2584, "text": "hash( txt[s+1 .. s+m] ) = ( d ( hash( txt[s .. s+m-1]) – txt[s]*h ) + txt[s + m] ) mod q hash( txt[s .. s+m-1] ) : Hash value at shift s. hash( txt[s+1 .. s+m] ) : Hash value at next shift (or shift s+1) d: Number of characters in the alphabet q: A prime number h: d^(m-1)" }, { "code": null, "e": 2894, "s": 2857, "text": "How does the above expression work? " }, { "code": null, "e": 3200, "s": 2894, "text": "This is simple mathematics, we compute decimal value of current window from previous window. For example pattern length is 3 and string is “23456” You compute the value of first window (which is “234”) as 234. How will you compute value of next window “345”? You will do (234 – 2*100)*10 + 5 and get 345." }, { "code": null, "e": 3204, "s": 3200, "text": "C++" }, { "code": null, "e": 3206, "s": 3204, "text": "C" }, { "code": null, "e": 3211, "s": 3206, "text": "Java" }, { "code": null, "e": 3219, "s": 3211, "text": "Python3" }, { "code": null, "e": 3222, "s": 3219, "text": "C#" }, { "code": null, "e": 3226, "s": 3222, "text": "PHP" }, { "code": null, "e": 3237, "s": 3226, "text": "Javascript" }, { "code": "/* Following program is a C++ implementation of Rabin Karp Algorithm given in the CLRS book */#include <bits/stdc++.h>using namespace std; // d is the number of characters in the input alphabet #define d 256 /* pat -> pattern txt -> text q -> A prime number */void search(char pat[], char txt[], int q) { int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be \"pow(d, M-1)%q\" for (i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d * p + pat[i]) % q; t = (d * t + txt[i]) % q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) { break; } } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) cout<<\"Pattern found at index \"<< i<<endl; } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt[i]*h) + txt[i+M])%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver code */int main() { char txt[] = \"GEEKS FOR GEEKS\"; char pat[] = \"GEEK\"; //we mod to avoid overflowing of value but we should take as big q as possible to avoid the collison int q =INT_MAX; // Function Call search(pat, txt, q); return 0; } // This is code is contributed by rathbhupendra", "e": 5409, "s": 3237, "text": null }, { "code": "/* Following program is a C implementation of Rabin KarpAlgorithm given in the CLRS book */#include<stdio.h>#include<string.h> // d is the number of characters in the input alphabet#define d 256 /* pat -> pattern txt -> text q -> A prime number*/void search(char pat[], char txt[], int q){ int M = strlen(pat); int N = strlen(txt); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be \"pow(d, M-1)%q\" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat[i])%q; t = (d*t + txt[i])%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) printf(\"Pattern found at index %d \\n\", i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt[i]*h) + txt[i+M])%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } }} /* Driver Code */int main(){ char txt[] = \"GEEKS FOR GEEKS\"; char pat[] = \"GEEK\"; // A prime number int q = 101; // function call search(pat, txt, q); return 0;}", "e": 7267, "s": 5409, "text": null }, { "code": "// Following program is a Java implementation // of Rabin Karp Algorithm given in the CLRS book public class Main { // d is the number of characters in the input alphabet public final static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.length(); int N = txt.length(); int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be \"pow(d, M-1)%q\" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat.charAt(i))%q; t = (d*t + txt.charAt(i))%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt.charAt(i+j) != pat.charAt(j)) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) System.out.println(\"Pattern found at index \" + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver Code */ public static void main(String[] args) { String txt = \"GEEKS FOR GEEKS\"; String pat = \"GEEK\"; // A prime number int q = 101; // Function Call search(pat, txt, q); }} // This code is contributed by nuclode", "e": 9551, "s": 7267, "text": null }, { "code": "# Following program is the python implementation of# Rabin Karp Algorithm given in CLRS book # d is the number of characters in the input alphabetd = 256 # pat -> pattern# txt -> text# q -> A prime number def search(pat, txt, q): M = len(pat) N = len(txt) i = 0 j = 0 p = 0 # hash value for pattern t = 0 # hash value for txt h = 1 # The value of h would be \"pow(d, M-1)%q\" for i in range(M-1): h = (h*d)%q # Calculate the hash value of pattern and first window # of text for i in range(M): p = (d*p + ord(pat[i]))%q t = (d*t + ord(txt[i]))%q # Slide the pattern over text one by one for i in range(N-M+1): # Check the hash values of current window of text and # pattern if the hash values match then only check # for characters one by one if p==t: # Check for characters one by one for j in range(M): if txt[i+j] != pat[j]: break else: j+=1 # if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if j==M: print (\"Pattern found at index \" + str(i)) # Calculate hash value for next window of text: Remove # leading digit, add trailing digit if i < N-M: t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%q # We might get negative values of t, converting it to # positive if t < 0: t = t+q # Driver Codetxt = \"GEEKS FOR GEEKS\"pat = \"GEEK\" # A prime numberq = 101 # Function Callsearch(pat,txt,q) # This code is contributed by Bhavya Jain", "e": 11186, "s": 9551, "text": null }, { "code": "// Following program is a C# implementation // of Rabin Karp Algorithm given in the CLRS book using System;public class GFG { // d is the number of characters in the input alphabet public readonly static int d = 256; /* pat -> pattern txt -> text q -> A prime number */ static void search(String pat, String txt, int q) { int M = pat.Length; int N = txt.Length; int i, j; int p = 0; // hash value for pattern int t = 0; // hash value for txt int h = 1; // The value of h would be \"pow(d, M-1)%q\" for (i = 0; i < M-1; i++) h = (h*d)%q; // Calculate the hash value of pattern and first // window of text for (i = 0; i < M; i++) { p = (d*p + pat[i])%q; t = (d*t + txt[i])%q; } // Slide the pattern over text one by one for (i = 0; i <= N - M; i++) { // Check the hash values of current window of text // and pattern. If the hash values match then only // check for characters one by one if ( p == t ) { /* Check for characters one by one */ for (j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] if (j == M) Console.WriteLine(\"Pattern found at index \" + i); } // Calculate hash value for next window of text: Remove // leading digit, add trailing digit if ( i < N-M ) { t = (d*(t - txt[i]*h) + txt[i+M])%q; // We might get negative value of t, converting it // to positive if (t < 0) t = (t + q); } } } /* Driver Code */ public static void Main() { String txt = \"GEEKS FOR GEEKS\"; String pat = \"GEEK\"; // A prime number int q = 101; // Function Call search(pat, txt, q); } } // This code is contributed by PrinciRaj19992", "e": 13485, "s": 11186, "text": null }, { "code": "<?php// Following program is a PHP // implementation of Rabin Karp// Algorithm given in the CLRS book // d is the number of characters// in the input alphabet$d = 256; /* pat -> pattern txt -> text q -> A prime number*/function search($pat, $txt, $q){ $M = strlen($pat); $N = strlen($txt); $i; $j; $p = 0; // hash value // for pattern $t = 0; // hash value // for txt $h = 1; $d =1; // The value of h would // be \"pow(d, M-1)%q\" for ($i = 0; $i < $M - 1; $i++) $h = ($h * $d) % $q; // Calculate the hash value // of pattern and first // window of text for ($i = 0; $i < $M; $i++) { $p = ($d * $p + $pat[$i]) % $q; $t = ($d * $t + $txt[$i]) % $q; } // Slide the pattern over // text one by one for ($i = 0; $i <= $N - $M; $i++) { // Check the hash values of // current window of text // and pattern. If the hash // values match then only // check for characters one // by one if ($p == $t) { // Check for characters // one by one for ($j = 0; $j < $M; $j++) { if ($txt[$i + $j] != $pat[$j]) break; } // if p == t and pat[0...M-1] = // txt[i, i+1, ...i+M-1] if ($j == $M) echo \"Pattern found at index \", $i, \"\\n\"; } // Calculate hash value for // next window of text: // Remove leading digit, // add trailing digit if ($i < $N - $M) { $t = ($d * ($t - $txt[$i] * $h) + $txt[$i + $M]) % $q; // We might get negative // value of t, converting // it to positive if ($t < 0) $t = ($t + $q); } }} // Driver Code$txt = \"GEEKS FOR GEEKS\";$pat = \"GEEK\"; // A prime number$q = 101; // Function Callsearch($pat, $txt, $q); // This code is contributed// by ajit?>", "e": 15579, "s": 13485, "text": null }, { "code": "<script> // Following program is a Javascript implementation // of Rabin Karp Algorithm given in the CLRS book // d is the number of characters in// the input alphabet let d = 256; /* pat -> pattern txt -> text q -> A prime number */function search(pat, txt, q) { let M = pat.length; let N = txt.length; let i, j; // Hash value for pattern let p = 0; // Hash value for txt let t = 0; let h = 1; // The value of h would be \"pow(d, M-1)%q\" for(i = 0; i < M - 1; i++) h = (h * d) % q; // Calculate the hash value of pattern and // first window of text for(i = 0; i < M; i++) { p = (d * p + pat[i].charCodeAt()) % q; t = (d * t + txt[i].charCodeAt()) % q; } // Slide the pattern over text one by one for(i = 0; i <= N - M; i++) { // Check the hash values of current // window of text and pattern. If the // hash values match then only // check for characters one by one if (p == t) { /* Check for characters one by one */ for(j = 0; j < M; j++) { if (txt[i+j] != pat[j]) break; } // if p == t and pat[0...M-1] = // txt[i, i+1, ...i+M-1] if (j == M) document.write(\"Pattern found at index \" + i + \"<br/>\"); } // Calculate hash value for next window // of text: Remove leading digit, add // trailing digit if (i < N - M) { t = (d * (t - txt[i].charCodeAt() * h) + txt[i + M].charCodeAt()) % q; // We might get negative value of t, // converting it to positive if (t < 0) t = (t + q); } } } // Driver codelet txt = \"GEEKS FOR GEEKS\";let pat = \"GEEK\"; // A prime numberlet q = 101; // Function Callsearch(pat, txt, q); // This code is contributed by target_2 </script>", "e": 17656, "s": 15579, "text": null }, { "code": null, "e": 17708, "s": 17656, "text": "Pattern found at index 0\nPattern found at index 10\n" }, { "code": null, "e": 18059, "s": 17708, "text": "Time Complexity:The average and best-case running time of the Rabin-Karp algorithm is O(n+m), but its worst-case time is O(nm). Worst case of Rabin-Karp algorithm occurs when all characters of pattern and text are same as the hash values of all the substrings of txt[] match with hash value of pat[]. For example pat[] = “AAA” and txt[] = “AAAAAAA”. " }, { "code": null, "e": 18540, "s": 18059, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.References:http://net.pku.edu.cn/~course/cs101/2007/resource/Intro2Algorithm/book6/chap34.htmhttp://www.cs.princeton.edu/courses/archive/fall04/cos226/lectures/string.4up.pdfhttp://en.wikipedia.org/wiki/Rabin-Karp_string_search_algorithmRelated Posts: Searching for Patterns | Set 1 (Naive Pattern Searching) Searching for Patterns | Set 2 (KMP Algorithm) " }, { "code": null, "e": 18554, "s": 18546, "text": "Hao Lee" }, { "code": null, "e": 18560, "s": 18554, "text": "jit_t" }, { "code": null, "e": 18574, "s": 18560, "text": "princiraj1992" }, { "code": null, "e": 18588, "s": 18574, "text": "rathbhupendra" }, { "code": null, "e": 18605, "s": 18588, "text": "KoushikChowdhury" }, { "code": null, "e": 18613, "s": 18605, "text": "sebibek" }, { "code": null, "e": 18622, "s": 18613, "text": "target_2" }, { "code": null, "e": 18636, "s": 18622, "text": "architgwl2000" }, { "code": null, "e": 18652, "s": 18636, "text": "chindaliyalavan" }, { "code": null, "e": 18668, "s": 18652, "text": "amartyaghoshgfg" }, { "code": null, "e": 18681, "s": 18668, "text": "simmytarika5" }, { "code": null, "e": 18694, "s": 18681, "text": "tylerstown23" }, { "code": null, "e": 18707, "s": 18694, "text": "parasjaggi20" }, { "code": null, "e": 18726, "s": 18707, "text": "Modular Arithmetic" }, { "code": null, "e": 18744, "s": 18726, "text": "Pattern Searching" }, { "code": null, "e": 18763, "s": 18744, "text": "Modular Arithmetic" }, { "code": null, "e": 18781, "s": 18763, "text": "Pattern Searching" } ]
Python program to Reverse a range in list - GeeksforGeeks
07 Apr, 2021 Given a List, our task is to write a Python program to reverse a range in the list. Example: Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 3, 9 Output : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11] Explanation : 8, 9, 2, 10, 12, 7 are reversed in list to 7, 12, 10, 2, 9, 8. Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 8, 9 Output : [6, 3, 1, 8, 9, 2, 10, 7, 12, 4, 11] Explanation : 12, 7 are reversed in list to 7, 12. Method #1 : Using reverse() + loop In this example, sublist is extracted and reversed using reverse(). The loop is used next to replace range elements with reversed elements. Python3 # Python3 code to demonstrate working of# Reversing a range# Using reverse() + loop # initializing listtest_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11] # printing original listprint("The original list is : " + str(test_list)) # initializing range strt, end = 3, 9 # reversing list and assigning the rangetemp = test_list[strt:end]temp.reverse()for idx in range(strt, end): test_list[idx] = temp[idx - strt] # printing resultprint("Range reversed range list : " + str(test_list)) Output: The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11] Range reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11] Method #2 : Using list split() + slicing The compact approach to solve this problem is to perform a reversal of range list using list split way of reversing slicing only the required range. Python3 # Python3 code to demonstrate working of# Reversing a range# Using list split + slicing # initializing listtest_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11] # printing original listprint("The original list is : " + str(test_list)) # initializing range strt, end = 3, 9 # Third arg. of split with -1 performs reverse test_list[strt:end] = test_list[strt:end][::-1] # printing resultprint("Range reversed range list : " + str(test_list)) Output: The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11] Range reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11] Python list-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 Selecting rows in pandas DataFrame based on conditions How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n07 Apr, 2021" }, { "code": null, "e": 24376, "s": 24292, "text": "Given a List, our task is to write a Python program to reverse a range in the list." }, { "code": null, "e": 24385, "s": 24376, "text": "Example:" }, { "code": null, "e": 24459, "s": 24385, "text": "Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 3, 9" }, { "code": null, "e": 24505, "s": 24459, "text": "Output : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]" }, { "code": null, "e": 24582, "s": 24505, "text": "Explanation : 8, 9, 2, 10, 12, 7 are reversed in list to 7, 12, 10, 2, 9, 8." }, { "code": null, "e": 24656, "s": 24582, "text": "Input : test_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11], str, end = 8, 9" }, { "code": null, "e": 24702, "s": 24656, "text": "Output : [6, 3, 1, 8, 9, 2, 10, 7, 12, 4, 11]" }, { "code": null, "e": 24753, "s": 24702, "text": "Explanation : 12, 7 are reversed in list to 7, 12." }, { "code": null, "e": 24788, "s": 24753, "text": "Method #1 : Using reverse() + loop" }, { "code": null, "e": 24929, "s": 24788, "text": "In this example, sublist is extracted and reversed using reverse(). The loop is used next to replace range elements with reversed elements. " }, { "code": null, "e": 24937, "s": 24929, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Reversing a range# Using reverse() + loop # initializing listtest_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing range strt, end = 3, 9 # reversing list and assigning the rangetemp = test_list[strt:end]temp.reverse()for idx in range(strt, end): test_list[idx] = temp[idx - strt] # printing resultprint(\"Range reversed range list : \" + str(test_list))", "e": 25445, "s": 24937, "text": null }, { "code": null, "e": 25453, "s": 25445, "text": "Output:" }, { "code": null, "e": 25578, "s": 25453, "text": "The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]\nRange reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]" }, { "code": null, "e": 25619, "s": 25578, "text": "Method #2 : Using list split() + slicing" }, { "code": null, "e": 25769, "s": 25619, "text": "The compact approach to solve this problem is to perform a reversal of range list using list split way of reversing slicing only the required range. " }, { "code": null, "e": 25777, "s": 25769, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Reversing a range# Using list split + slicing # initializing listtest_list = [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing range strt, end = 3, 9 # Third arg. of split with -1 performs reverse test_list[strt:end] = test_list[strt:end][::-1] # printing resultprint(\"Range reversed range list : \" + str(test_list))", "e": 26230, "s": 25777, "text": null }, { "code": null, "e": 26238, "s": 26230, "text": "Output:" }, { "code": null, "e": 26363, "s": 26238, "text": "The original list is : [6, 3, 1, 8, 9, 2, 10, 12, 7, 4, 11]\nRange reversed range list : [6, 3, 1, 7, 12, 10, 2, 9, 8, 4, 11]" }, { "code": null, "e": 26384, "s": 26363, "text": "Python list-programs" }, { "code": null, "e": 26391, "s": 26384, "text": "Python" }, { "code": null, "e": 26407, "s": 26391, "text": "Python Programs" }, { "code": null, "e": 26505, "s": 26407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26514, "s": 26505, "text": "Comments" }, { "code": null, "e": 26527, "s": 26514, "text": "Old Comments" }, { "code": null, "e": 26559, "s": 26527, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26615, "s": 26559, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26670, "s": 26615, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26712, "s": 26670, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26754, "s": 26712, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26776, "s": 26754, "text": "Defaultdict in Python" }, { "code": null, "e": 26822, "s": 26776, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26861, "s": 26822, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26899, "s": 26861, "text": "Python | Convert a list to dictionary" } ]
How do we display a text area in HTML?
Use the <textarea> tag to show a text area. The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows. The following are the attributes − You can try to run the following code to display a text area in HTML − <!DOCTYPE html> <html> <head> <title>HTML textarea Tag</title> </head> <body> <form action = "/cgi-bin/hello_get.cgi" method = "get"> Enter subjects <br /> <textarea rows = "5" cols = "50" name = "description"> </textarea> <input type = "submit" value = "submit" /> </form> </body> </html>
[ { "code": null, "e": 1249, "s": 1062, "text": "Use the <textarea> tag to show a text area. The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows." }, { "code": null, "e": 1284, "s": 1249, "text": "The following are the attributes −" }, { "code": null, "e": 1355, "s": 1284, "text": "You can try to run the following code to display a text area in HTML −" }, { "code": null, "e": 1722, "s": 1355, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML textarea Tag</title>\n </head>\n <body>\n <form action = \"/cgi-bin/hello_get.cgi\" method = \"get\">\n Enter subjects\n <br />\n\n <textarea rows = \"5\" cols = \"50\" name = \"description\">\n </textarea>\n\n <input type = \"submit\" value = \"submit\" />\n </form>\n </body>\n</html>" } ]
What is the use of ‘Using’ statement in C#?
The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically. Let us see an example wherein “A” would print first since the SystemResource is allocated first. Live Demo using System; using System.Text; class Demo { static void Main() { using (SystemResource res = new SystemResource()) { Console.WriteLine("A"); } Console.WriteLine("B"); } } class SystemResource : IDisposable { public void Dispose() { Console.WriteLine("C"); } } A C B
[ { "code": null, "e": 1240, "s": 1062, "text": "The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations." }, { "code": null, "e": 1322, "s": 1240, "text": "The main goal is to manage resources and release all the resources automatically." }, { "code": null, "e": 1419, "s": 1322, "text": "Let us see an example wherein “A” would print first since the SystemResource is allocated first." }, { "code": null, "e": 1430, "s": 1419, "text": " Live Demo" }, { "code": null, "e": 1739, "s": 1430, "text": "using System;\nusing System.Text;\n\nclass Demo {\n static void Main() {\n using (SystemResource res = new SystemResource()) {\n Console.WriteLine(\"A\");\n }\n Console.WriteLine(\"B\");\n }\n}\n\nclass SystemResource : IDisposable {\n public void Dispose() {\n Console.WriteLine(\"C\");\n }\n}" }, { "code": null, "e": 1745, "s": 1739, "text": "A\nC\nB" } ]
How to preload all Angular Bundles ? - GeeksforGeeks
05 Jun, 2020 Introduction to pre-loading: The introduction of the Lazy Loading feature in Angular greatly improved the performance of the application. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times. But, the main problem with lazy loading was that when the user navigates(or reaches) the lazy-loadable section of the application, the router has to fetch the required modules from the server, which can take time. So, even though the initial loading time for application is reduced ultimately the user will have to wait for some time till router fetches that specific module. To solve this issue, Angular came up with the concept of preloading. With this feature, the lazy-loadable modules are preloaded and thus the user doesn’t have to wait for it to be fetched. This preloading takes place when the user is interacting with the application that is already loaded during lazy-loading. Approach: Basic Approach is to set preloading Strategyas that we need. We need to specify that we will be preloading all the modules by explicitly mentioning in app-routing.module.ts abstract class PreloadingStrategy {abstract preload(route: Route, fn: () => Observable): Observable} Steps: To preload all the modules, simply follow the steps below: Add an import statement for PreloadAllModules from app-routing.module.tsSyntax:import { NgModule } from ‘@angular/core’;import { RouterModule, Routes, PreloadAllModules } from ‘@angular/router’; import { NgModule } from ‘@angular/core’;import { RouterModule, Routes, PreloadAllModules } from ‘@angular/router’; While setting up the RouterModule in app-routing.module.ts, pass the router options including the preloadingStrategy to the forRoot() function.This will tell the router to set the preloading strategy to preload all the modules.Syntax:@NgModule({imports:[RouterModule.forRoot(appRoutes, { preloadingStrategy : PreloadAllModules})],exports:[RouterModule]}) @NgModule({imports:[RouterModule.forRoot(appRoutes, { preloadingStrategy : PreloadAllModules})],exports:[RouterModule] }) Now run ngserve in Angular CLI to rebuild your app. Open http://localhost:4200. Right Click to inspect elements(or Ctrl+Shift+I) and go to Network tab to see the result.Syntax:ng serve ng serve Example: Here is an example of what app-routing.module.ts that will look like this. import { NgModule } from '@angular/core';import { RouterModule, Routes, PreloadAllModules } from '@angular/router'; import { ListComponent } from './list/list.component';import { DetailComponent } from './detail/detail.component';import { AppComponent } from './app.component';import { PageComponent } from './page/page.component';import { NewComponent } from './new/new.component'; const appRoutes: Routes = [ { path: '', redirectTo: '/contact', pathMatch: 'full' }, { path: 'contact', component: ListComponent }, { path: 'details/:id', component: DetailComponent }, { path: 'new', component: NewComponent }, { path: 'not-found', component: PageComponent }, { path: '**', redirectTo: '/not-found' }] @NgModule({ imports: [RouterModule.forRoot(appRoutes, { preloadingStrategy: PreloadAllModules })], exports: [RouterModule] })export class AppRoutingModule { } Output: AngularJS-Misc Picked AngularJS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 10 Angular Libraries For Web Developers Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (focus) Event Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25109, "s": 25081, "text": "\n05 Jun, 2020" }, { "code": null, "e": 25556, "s": 25109, "text": "Introduction to pre-loading: The introduction of the Lazy Loading feature in Angular greatly improved the performance of the application. Lazy loading helps keep initial bundle sizes smaller, which in turn helps decrease load times. But, the main problem with lazy loading was that when the user navigates(or reaches) the lazy-loadable section of the application, the router has to fetch the required modules from the server, which can take time." }, { "code": null, "e": 26029, "s": 25556, "text": "So, even though the initial loading time for application is reduced ultimately the user will have to wait for some time till router fetches that specific module. To solve this issue, Angular came up with the concept of preloading. With this feature, the lazy-loadable modules are preloaded and thus the user doesn’t have to wait for it to be fetched. This preloading takes place when the user is interacting with the application that is already loaded during lazy-loading." }, { "code": null, "e": 26212, "s": 26029, "text": "Approach: Basic Approach is to set preloading Strategyas that we need. We need to specify that we will be preloading all the modules by explicitly mentioning in app-routing.module.ts" }, { "code": null, "e": 26313, "s": 26212, "text": "abstract class PreloadingStrategy {abstract preload(route: Route, fn: () => Observable): Observable}" }, { "code": null, "e": 26379, "s": 26313, "text": "Steps: To preload all the modules, simply follow the steps below:" }, { "code": null, "e": 26574, "s": 26379, "text": "Add an import statement for PreloadAllModules from app-routing.module.tsSyntax:import { NgModule } from ‘@angular/core’;import { RouterModule, Routes, PreloadAllModules } from ‘@angular/router’;" }, { "code": null, "e": 26690, "s": 26574, "text": "import { NgModule } from ‘@angular/core’;import { RouterModule, Routes, PreloadAllModules } from ‘@angular/router’;" }, { "code": null, "e": 27045, "s": 26690, "text": "While setting up the RouterModule in app-routing.module.ts, pass the router options including the preloadingStrategy to the forRoot() function.This will tell the router to set the preloading strategy to preload all the modules.Syntax:@NgModule({imports:[RouterModule.forRoot(appRoutes, { preloadingStrategy : PreloadAllModules})],exports:[RouterModule]})" }, { "code": null, "e": 27164, "s": 27045, "text": "@NgModule({imports:[RouterModule.forRoot(appRoutes, { preloadingStrategy : PreloadAllModules})],exports:[RouterModule]" }, { "code": null, "e": 27167, "s": 27164, "text": "})" }, { "code": null, "e": 27352, "s": 27167, "text": "Now run ngserve in Angular CLI to rebuild your app. Open http://localhost:4200. Right Click to inspect elements(or Ctrl+Shift+I) and go to Network tab to see the result.Syntax:ng serve" }, { "code": null, "e": 27361, "s": 27352, "text": "ng serve" }, { "code": null, "e": 27445, "s": 27361, "text": "Example: Here is an example of what app-routing.module.ts that will look like this." }, { "code": "import { NgModule } from '@angular/core';import { RouterModule, Routes, PreloadAllModules } from '@angular/router'; import { ListComponent } from './list/list.component';import { DetailComponent } from './detail/detail.component';import { AppComponent } from './app.component';import { PageComponent } from './page/page.component';import { NewComponent } from './new/new.component'; const appRoutes: Routes = [ { path: '', redirectTo: '/contact', pathMatch: 'full' }, { path: 'contact', component: ListComponent }, { path: 'details/:id', component: DetailComponent }, { path: 'new', component: NewComponent }, { path: 'not-found', component: PageComponent }, { path: '**', redirectTo: '/not-found' }] @NgModule({ imports: [RouterModule.forRoot(appRoutes, { preloadingStrategy: PreloadAllModules })], exports: [RouterModule] })export class AppRoutingModule { }", "e": 28404, "s": 27445, "text": null }, { "code": null, "e": 28412, "s": 28404, "text": "Output:" }, { "code": null, "e": 28427, "s": 28412, "text": "AngularJS-Misc" }, { "code": null, "e": 28434, "s": 28427, "text": "Picked" }, { "code": null, "e": 28444, "s": 28434, "text": "AngularJS" }, { "code": null, "e": 28461, "s": 28444, "text": "Web Technologies" }, { "code": null, "e": 28488, "s": 28461, "text": "Web technologies Questions" }, { "code": null, "e": 28586, "s": 28488, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28630, "s": 28586, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28665, "s": 28630, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 28689, "s": 28665, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 28742, "s": 28689, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 28767, "s": 28742, "text": "Angular 10 (focus) Event" }, { "code": null, "e": 28809, "s": 28767, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28842, "s": 28809, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28885, "s": 28842, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28947, "s": 28885, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to compare two images using Java OpenCV library?
To compare two images − Read Both of them using the Image.IO.read() method. Read Both of them using the Image.IO.read() method. Get the height and width of both of them to make sure they are equal. Get the height and width of both of them to make sure they are equal. Get the pixel values and, get the RGB values of both of the images. Get the pixel values and, get the RGB values of both of the images. Get the sum of the differences between the RGB values of these two images. Get the sum of the differences between the RGB values of these two images. Calculate the percentage of the difference using the following formula − Calculate the percentage of the difference using the following formula − Average = difference/weight*height*3; Percentage = (Average/255)*100; import java.awt.Color; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.File; public class ComparingImages { public static void main(String[] args) throws Exception { BufferedImage img1 = ImageIO.read(new File("D:\\Images\\test1.jpg")); BufferedImage img2 = ImageIO.read(new File("D:\\Images\\test2.jpg")); int w1 = img1.getWidth(); int w2 = img2.getWidth(); int h1 = img1.getHeight(); int h2 = img2.getHeight(); if ((w1!=w2)||(h1!=h2)) { System.out.println("Both images should have same dimwnsions"); } else { long diff = 0; for (int j = 0; j < h1; j++) { for (int i = 0; i < w1; i++) { //Getting the RGB values of a pixel int pixel1 = img1.getRGB(i, j); Color color1 = new Color(pixel1, true); int r1 = color1.getRed(); int g1 = color1.getGreen(); int b1 = color1.getBlue(); int pixel2 = img2.getRGB(i, j); Color color2 = new Color(pixel2, true); int r2 = color2.getRed(); int g2 = color2.getGreen(); int b2= color2.getBlue(); //sum of differences of RGB values of the two images long data = Math.abs(r1-r2)+Math.abs(g1-g2)+ Math.abs(b1-b2); diff = diff+data; } } double avg = diff/(w1*h1*3); double percentage = (avg/255)*100; System.out.println("Difference: "+percentage); } } } Difference: 92.54901960784314
[ { "code": null, "e": 1086, "s": 1062, "text": "To compare two images −" }, { "code": null, "e": 1138, "s": 1086, "text": "Read Both of them using the Image.IO.read() method." }, { "code": null, "e": 1190, "s": 1138, "text": "Read Both of them using the Image.IO.read() method." }, { "code": null, "e": 1260, "s": 1190, "text": "Get the height and width of both of them to make sure they are equal." }, { "code": null, "e": 1330, "s": 1260, "text": "Get the height and width of both of them to make sure they are equal." }, { "code": null, "e": 1398, "s": 1330, "text": "Get the pixel values and, get the RGB values of both of the images." }, { "code": null, "e": 1466, "s": 1398, "text": "Get the pixel values and, get the RGB values of both of the images." }, { "code": null, "e": 1541, "s": 1466, "text": "Get the sum of the differences between the RGB values of these two images." }, { "code": null, "e": 1616, "s": 1541, "text": "Get the sum of the differences between the RGB values of these two images." }, { "code": null, "e": 1689, "s": 1616, "text": "Calculate the percentage of the difference using the following formula −" }, { "code": null, "e": 1762, "s": 1689, "text": "Calculate the percentage of the difference using the following formula −" }, { "code": null, "e": 1832, "s": 1762, "text": "Average = difference/weight*height*3;\nPercentage = (Average/255)*100;" }, { "code": null, "e": 3405, "s": 1832, "text": "import java.awt.Color;\nimport java.awt.image.BufferedImage;\nimport javax.imageio.ImageIO;\nimport java.io.File;\npublic class ComparingImages {\n public static void main(String[] args) throws Exception {\n BufferedImage img1 = ImageIO.read(new File(\"D:\\\\Images\\\\test1.jpg\"));\n BufferedImage img2 = ImageIO.read(new File(\"D:\\\\Images\\\\test2.jpg\"));\n int w1 = img1.getWidth();\n int w2 = img2.getWidth();\n int h1 = img1.getHeight();\n int h2 = img2.getHeight();\n if ((w1!=w2)||(h1!=h2)) {\n System.out.println(\"Both images should have same dimwnsions\");\n } else {\n long diff = 0;\n for (int j = 0; j < h1; j++) {\n for (int i = 0; i < w1; i++) {\n //Getting the RGB values of a pixel\n int pixel1 = img1.getRGB(i, j);\n Color color1 = new Color(pixel1, true);\n int r1 = color1.getRed();\n int g1 = color1.getGreen();\n int b1 = color1.getBlue();\n int pixel2 = img2.getRGB(i, j);\n Color color2 = new Color(pixel2, true);\n int r2 = color2.getRed();\n int g2 = color2.getGreen();\n int b2= color2.getBlue();\n //sum of differences of RGB values of the two images\n long data = Math.abs(r1-r2)+Math.abs(g1-g2)+ Math.abs(b1-b2);\n diff = diff+data;\n }\n }\n double avg = diff/(w1*h1*3);\n double percentage = (avg/255)*100;\n System.out.println(\"Difference: \"+percentage);\n }\n }\n}" }, { "code": null, "e": 3435, "s": 3405, "text": "Difference: 92.54901960784314" } ]
Count ways to reach end from start stone with at most K jumps at each step - GeeksforGeeks
24 Nov, 2021 Given N stones in a row from left to right. From each stone, you can jump to at most K stones. The task is to find the total number of ways to reach from sth stone to Nth stone.Examples: Input: N = 5, s = 2, K = 2 Output: Total Ways = 3 Explanation: Assume s1, s2, s3, s4, s5 be the stones. The possible paths from 2nd stone to 5th stone: s2 -> s3 -> s4 -> s5 s2 -> s4 -> s5 s2 -> s3 -> s5 Hence total number of ways = 3Input: N = 8, s = 1, K = 3 Output: Total Ways = 44 Approach: Let assume dp[i] be the number of ways to reach ith stone.Since there are atmost K jumps, So the ith stone can be reach by all it’s previous K stones.Iterate for all possible K jumps and keep adding this possible combination to the array dp[].Then the total number of possible ways to reach Nth node from sth stone will be dp[N-1].For Example: Let assume dp[i] be the number of ways to reach ith stone. Since there are atmost K jumps, So the ith stone can be reach by all it’s previous K stones. Iterate for all possible K jumps and keep adding this possible combination to the array dp[]. Then the total number of possible ways to reach Nth node from sth stone will be dp[N-1]. For Example: Let N = 5, s = 2, K = 2, then we have to reach Nth stone from sth stone. Let dp[N+1] is the array that stores the number of paths to reach the Nth Node from sth stone. Initially, dp[] = { 0, 0, 0, 0, 0, 0 } and dp[s] = 1, then dp[] = { 0, 0, 1, 0, 0, 0 } To reach the 3rd, There is only 1 way with at most 2 jumps i.e., from stone 2(with jump = 1). Update dp[3] = dp[2] dp[] = { 0, 0, 1, 1, 0, 0 }To reach the 4th stone, The two ways with at most 2 jumps i.e., from stone 2(with jump = 2) and stone 3(jump = 1). Update dp[4] = dp[3] + dp[2] dp[] = { 0, 0, 1, 1, 2, 0 }To reach the 5th stone, The two ways with at most 2 jumps i.e., from stone 3(with jump = 2) and stone 4(with jump = 1). Update dp[5] = dp[4] + dp[3] dp[] = { 0, 0, 1, 1, 2, 3 }Now dp[N] = 3 is the number of ways to reach Nth stone from sth stone. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find total no.of ways// to reach nth step#include "bits/stdc++.h"using namespace std; // Function which returns total no.of ways// to reach nth step from sth stepsint TotalWays(int n, int s, int k){ // Initialize dp array with 0s. vector<int> dp(n,0); // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (int i = s; i < n; i++) { // starting range for counting ranges int idx = max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (int j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1];} // Driver Codeint main(){ // no of steps int n = 5; // Atmost steps allowed int k = 2; // starting range int s = 2; cout << "Total Ways = " << TotalWays(n, s, k);} // Java program to find total no.of ways// to reach nth stepclass GFG{ // Function which returns total no.of ways// to reach nth step from sth stepsstatic int TotalWays(int n, int s, int k){ // Initialize dp array int []dp = new int[n]; // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (int i = s; i < n; i++) { // starting range for counting ranges int idx = Math.max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (int j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1];} // Driver Codepublic static void main(String[] args){ // no of steps int n = 5; // Atmost steps allowed int k = 2; // starting range int s = 2; System.out.print("Total Ways = " + TotalWays(n, s, k));}} // This code is contributed by sapnasingh4991 # Python 3 program to find total no.of ways# to reach nth step # Function which returns total no.of ways# to reach nth step from sth stepsdef TotalWays(n, s, k): # Initialize dp array dp = [0]*n # Initialize (s-1)th index to 1 dp[s - 1] = 1 # Iterate a loop from s to n for i in range(s, n): # starting range for counting ranges idx = max(s - 1, i - k) # Calculate Maximum moves to # Reach ith step for j in range( idx, i) : dp[i] += dp[j] # For nth step return dp[n-1] return dp[n - 1] # Driver Codeif __name__ == "__main__": # no of steps n = 5 # Atmost steps allowed k = 2 # starting range s = 2 print("Total Ways = ", TotalWays(n, s, k)) # This code is contributed by chitranayal // C# program to find total no.of ways// to reach nth stepusing System; class GFG{ // Function which returns total no.of ways // to reach nth step from sth steps static int TotalWays(int n, int s, int k) { // Initialize dp array int []dp = new int[n]; // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (int i = s; i < n; i++) { // starting range for counting ranges int idx = Math.Max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (int j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1]; } // Driver Code public static void Main(string[] args) { // no of steps int n = 5; // Atmost steps allowed int k = 2; // starting range int s = 2; Console.Write("Total Ways = "+ TotalWays(n, s, k)); }} // This code is contributed by Yash_R <script>// Javascript program to find total no.of ways// to reach nth step // Function which returns total no.of ways// to reach nth step from sth stepsfunction TotalWays(n, s, k){ // Initialize dp array let dp = new Array(n); // filling all the elements with 0 dp.fill(0); // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (let i = s; i < n; i++) { // starting range for counting ranges let idx = Math.max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (let j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1];} // Driver Code // no of steps let n = 5; // Atmost steps allowed let k = 2; // starting range let s = 2; document.write("Total Ways = " + TotalWays(n, s, k)); // This code is contributed by _saurabh_jaiswal</script> Total Ways = 3 Time Complexity: O(N2), where N is the number of stones.Auxiliary Space: O(N) ukasp sapnasingh4991 Yash_R _saurabh_jaiswal pankajsharmagfg ashutoshsinghgeeksforgeeks Algorithms Arrays Dynamic Programming Arrays Dynamic Programming 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 How to write a Pseudo Code? Playfair Cipher with Examples Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24780, "s": 24752, "text": "\n24 Nov, 2021" }, { "code": null, "e": 24969, "s": 24780, "text": "Given N stones in a row from left to right. From each stone, you can jump to at most K stones. The task is to find the total number of ways to reach from sth stone to Nth stone.Examples: " }, { "code": null, "e": 25255, "s": 24969, "text": "Input: N = 5, s = 2, K = 2 Output: Total Ways = 3 Explanation: Assume s1, s2, s3, s4, s5 be the stones. The possible paths from 2nd stone to 5th stone: s2 -> s3 -> s4 -> s5 s2 -> s4 -> s5 s2 -> s3 -> s5 Hence total number of ways = 3Input: N = 8, s = 1, K = 3 Output: Total Ways = 44 " }, { "code": null, "e": 25269, "s": 25257, "text": "Approach: " }, { "code": null, "e": 25615, "s": 25269, "text": "Let assume dp[i] be the number of ways to reach ith stone.Since there are atmost K jumps, So the ith stone can be reach by all it’s previous K stones.Iterate for all possible K jumps and keep adding this possible combination to the array dp[].Then the total number of possible ways to reach Nth node from sth stone will be dp[N-1].For Example: " }, { "code": null, "e": 25674, "s": 25615, "text": "Let assume dp[i] be the number of ways to reach ith stone." }, { "code": null, "e": 25767, "s": 25674, "text": "Since there are atmost K jumps, So the ith stone can be reach by all it’s previous K stones." }, { "code": null, "e": 25861, "s": 25767, "text": "Iterate for all possible K jumps and keep adding this possible combination to the array dp[]." }, { "code": null, "e": 25950, "s": 25861, "text": "Then the total number of possible ways to reach Nth node from sth stone will be dp[N-1]." }, { "code": null, "e": 25965, "s": 25950, "text": "For Example: " }, { "code": null, "e": 26782, "s": 25965, "text": "Let N = 5, s = 2, K = 2, then we have to reach Nth stone from sth stone. Let dp[N+1] is the array that stores the number of paths to reach the Nth Node from sth stone. Initially, dp[] = { 0, 0, 0, 0, 0, 0 } and dp[s] = 1, then dp[] = { 0, 0, 1, 0, 0, 0 } To reach the 3rd, There is only 1 way with at most 2 jumps i.e., from stone 2(with jump = 1). Update dp[3] = dp[2] dp[] = { 0, 0, 1, 1, 0, 0 }To reach the 4th stone, The two ways with at most 2 jumps i.e., from stone 2(with jump = 2) and stone 3(jump = 1). Update dp[4] = dp[3] + dp[2] dp[] = { 0, 0, 1, 1, 2, 0 }To reach the 5th stone, The two ways with at most 2 jumps i.e., from stone 3(with jump = 2) and stone 4(with jump = 1). Update dp[5] = dp[4] + dp[3] dp[] = { 0, 0, 1, 1, 2, 3 }Now dp[N] = 3 is the number of ways to reach Nth stone from sth stone. " }, { "code": null, "e": 26838, "s": 26786, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26842, "s": 26838, "text": "C++" }, { "code": null, "e": 26847, "s": 26842, "text": "Java" }, { "code": null, "e": 26855, "s": 26847, "text": "Python3" }, { "code": null, "e": 26858, "s": 26855, "text": "C#" }, { "code": null, "e": 26869, "s": 26858, "text": "Javascript" }, { "code": "// C++ program to find total no.of ways// to reach nth step#include \"bits/stdc++.h\"using namespace std; // Function which returns total no.of ways// to reach nth step from sth stepsint TotalWays(int n, int s, int k){ // Initialize dp array with 0s. vector<int> dp(n,0); // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (int i = s; i < n; i++) { // starting range for counting ranges int idx = max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (int j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1];} // Driver Codeint main(){ // no of steps int n = 5; // Atmost steps allowed int k = 2; // starting range int s = 2; cout << \"Total Ways = \" << TotalWays(n, s, k);}", "e": 27745, "s": 26869, "text": null }, { "code": "// Java program to find total no.of ways// to reach nth stepclass GFG{ // Function which returns total no.of ways// to reach nth step from sth stepsstatic int TotalWays(int n, int s, int k){ // Initialize dp array int []dp = new int[n]; // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (int i = s; i < n; i++) { // starting range for counting ranges int idx = Math.max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (int j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1];} // Driver Codepublic static void main(String[] args){ // no of steps int n = 5; // Atmost steps allowed int k = 2; // starting range int s = 2; System.out.print(\"Total Ways = \" + TotalWays(n, s, k));}} // This code is contributed by sapnasingh4991", "e": 28685, "s": 27745, "text": null }, { "code": "# Python 3 program to find total no.of ways# to reach nth step # Function which returns total no.of ways# to reach nth step from sth stepsdef TotalWays(n, s, k): # Initialize dp array dp = [0]*n # Initialize (s-1)th index to 1 dp[s - 1] = 1 # Iterate a loop from s to n for i in range(s, n): # starting range for counting ranges idx = max(s - 1, i - k) # Calculate Maximum moves to # Reach ith step for j in range( idx, i) : dp[i] += dp[j] # For nth step return dp[n-1] return dp[n - 1] # Driver Codeif __name__ == \"__main__\": # no of steps n = 5 # Atmost steps allowed k = 2 # starting range s = 2 print(\"Total Ways = \", TotalWays(n, s, k)) # This code is contributed by chitranayal", "e": 29472, "s": 28685, "text": null }, { "code": "// C# program to find total no.of ways// to reach nth stepusing System; class GFG{ // Function which returns total no.of ways // to reach nth step from sth steps static int TotalWays(int n, int s, int k) { // Initialize dp array int []dp = new int[n]; // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (int i = s; i < n; i++) { // starting range for counting ranges int idx = Math.Max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (int j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1]; } // Driver Code public static void Main(string[] args) { // no of steps int n = 5; // Atmost steps allowed int k = 2; // starting range int s = 2; Console.Write(\"Total Ways = \"+ TotalWays(n, s, k)); }} // This code is contributed by Yash_R", "e": 30568, "s": 29472, "text": null }, { "code": "<script>// Javascript program to find total no.of ways// to reach nth step // Function which returns total no.of ways// to reach nth step from sth stepsfunction TotalWays(n, s, k){ // Initialize dp array let dp = new Array(n); // filling all the elements with 0 dp.fill(0); // Initialize (s-1)th index to 1 dp[s - 1] = 1; // Iterate a loop from s to n for (let i = s; i < n; i++) { // starting range for counting ranges let idx = Math.max(s - 1, i - k); // Calculate Maximum moves to // Reach ith step for (let j = idx; j < i; j++) { dp[i] += dp[j]; } } // For nth step return dp[n-1] return dp[n - 1];} // Driver Code // no of steps let n = 5; // Atmost steps allowed let k = 2; // starting range let s = 2; document.write(\"Total Ways = \" + TotalWays(n, s, k)); // This code is contributed by _saurabh_jaiswal</script>", "e": 31510, "s": 30568, "text": null }, { "code": null, "e": 31525, "s": 31510, "text": "Total Ways = 3" }, { "code": null, "e": 31606, "s": 31527, "text": "Time Complexity: O(N2), where N is the number of stones.Auxiliary Space: O(N) " }, { "code": null, "e": 31612, "s": 31606, "text": "ukasp" }, { "code": null, "e": 31627, "s": 31612, "text": "sapnasingh4991" }, { "code": null, "e": 31634, "s": 31627, "text": "Yash_R" }, { "code": null, "e": 31651, "s": 31634, "text": "_saurabh_jaiswal" }, { "code": null, "e": 31667, "s": 31651, "text": "pankajsharmagfg" }, { "code": null, "e": 31694, "s": 31667, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 31705, "s": 31694, "text": "Algorithms" }, { "code": null, "e": 31712, "s": 31705, "text": "Arrays" }, { "code": null, "e": 31732, "s": 31712, "text": "Dynamic Programming" }, { "code": null, "e": 31739, "s": 31732, "text": "Arrays" }, { "code": null, "e": 31759, "s": 31739, "text": "Dynamic Programming" }, { "code": null, "e": 31770, "s": 31759, "text": "Algorithms" }, { "code": null, "e": 31868, "s": 31770, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31877, "s": 31868, "text": "Comments" }, { "code": null, "e": 31890, "s": 31877, "text": "Old Comments" }, { "code": null, "e": 31939, "s": 31890, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 31964, "s": 31939, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 31991, "s": 31964, "text": "Introduction to Algorithms" }, { "code": null, "e": 32019, "s": 31991, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 32049, "s": 32019, "text": "Playfair Cipher with Examples" }, { "code": null, "e": 32064, "s": 32049, "text": "Arrays in Java" }, { "code": null, "e": 32080, "s": 32064, "text": "Arrays in C/C++" }, { "code": null, "e": 32107, "s": 32080, "text": "Program for array rotation" }, { "code": null, "e": 32155, "s": 32107, "text": "Stack Data Structure (Introduction and Program)" } ]
Assembly - Constants
There are several directives provided by NASM that define constants. We have already used the EQU directive in previous chapters. We will particularly discuss three directives − EQU %assign %define The EQU directive is used for defining constants. The syntax of the EQU directive is as follows − CONSTANT_NAME EQU expression For example, TOTAL_STUDENTS equ 50 You can then use this constant value in your code, like − mov ecx, TOTAL_STUDENTS cmp eax, TOTAL_STUDENTS The operand of an EQU statement can be an expression − LENGTH equ 20 WIDTH equ 10 AREA equ length * width Above code segment would define AREA as 200. The following example illustrates the use of the EQU directive − SYS_EXIT equ 1 SYS_WRITE equ 4 STDIN equ 0 STDOUT equ 1 section .text global _start ;must be declared for using gcc _start: ;tell linker entry point mov eax, SYS_WRITE mov ebx, STDOUT mov ecx, msg1 mov edx, len1 int 0x80 mov eax, SYS_WRITE mov ebx, STDOUT mov ecx, msg2 mov edx, len2 int 0x80 mov eax, SYS_WRITE mov ebx, STDOUT mov ecx, msg3 mov edx, len3 int 0x80 mov eax,SYS_EXIT ;system call number (sys_exit) int 0x80 ;call kernel section .data msg1 db 'Hello, programmers!',0xA,0xD len1 equ $ - msg1 msg2 db 'Welcome to the world of,', 0xA,0xD len2 equ $ - msg2 msg3 db 'Linux assembly programming! ' len3 equ $- msg3 When the above code is compiled and executed, it produces the following result − Hello, programmers! Welcome to the world of, Linux assembly programming! The %assign directive can be used to define numeric constants like the EQU directive. This directive allows redefinition. For example, you may define the constant TOTAL as − %assign TOTAL 10 Later in the code, you can redefine it as − %assign TOTAL 20 This directive is case-sensitive. The %define directive allows defining both numeric and string constants. This directive is similar to the #define in C. For example, you may define the constant PTR as − %define PTR [EBP+4] The above code replaces PTR by [EBP+4]. This directive also allows redefinition and it is case-sensitive. 46 Lectures 2 hours Frahaan Hussain 23 Lectures 12 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2263, "s": 2085, "text": "There are several directives provided by NASM that define constants. We have already used the EQU directive in previous chapters. We will particularly discuss three directives −" }, { "code": null, "e": 2267, "s": 2263, "text": "EQU" }, { "code": null, "e": 2275, "s": 2267, "text": "%assign" }, { "code": null, "e": 2283, "s": 2275, "text": "%define" }, { "code": null, "e": 2381, "s": 2283, "text": "The EQU directive is used for defining constants. The syntax of the EQU directive is as follows −" }, { "code": null, "e": 2411, "s": 2381, "text": "CONSTANT_NAME EQU expression\n" }, { "code": null, "e": 2424, "s": 2411, "text": "For example," }, { "code": null, "e": 2447, "s": 2424, "text": "TOTAL_STUDENTS equ 50\n" }, { "code": null, "e": 2505, "s": 2447, "text": "You can then use this constant value in your code, like −" }, { "code": null, "e": 2558, "s": 2505, "text": "mov ecx, TOTAL_STUDENTS \ncmp eax, TOTAL_STUDENTS" }, { "code": null, "e": 2613, "s": 2558, "text": "The operand of an EQU statement can be an expression −" }, { "code": null, "e": 2667, "s": 2613, "text": "LENGTH equ 20\nWIDTH equ 10\nAREA equ length * width" }, { "code": null, "e": 2712, "s": 2667, "text": "Above code segment would define AREA as 200." }, { "code": null, "e": 2777, "s": 2712, "text": "The following example illustrates the use of the EQU directive −" }, { "code": null, "e": 3614, "s": 2777, "text": "SYS_EXIT equ 1\nSYS_WRITE equ 4\nSTDIN equ 0\nSTDOUT equ 1\nsection\t .text\n global _start ;must be declared for using gcc\n\t\n_start: ;tell linker entry point\n mov eax, SYS_WRITE \n mov ebx, STDOUT \n mov ecx, msg1 \n mov edx, len1 \n int 0x80 \n\t\n mov eax, SYS_WRITE \n mov ebx, STDOUT \n mov ecx, msg2 \n mov edx, len2 \n int 0x80 \n\t\n mov eax, SYS_WRITE \n mov ebx, STDOUT \n mov ecx, msg3 \n mov edx, len3 \n int 0x80\n \n mov eax,SYS_EXIT ;system call number (sys_exit)\n int 0x80 ;call kernel\n\nsection\t .data\nmsg1 db\t'Hello, programmers!',0xA,0xD \t\nlen1 equ $ - msg1\t\t\t\n\nmsg2 db 'Welcome to the world of,', 0xA,0xD \nlen2 equ $ - msg2 \n\nmsg3 db 'Linux assembly programming! '\nlen3 equ $- msg3" }, { "code": null, "e": 3695, "s": 3614, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 3769, "s": 3695, "text": "Hello, programmers!\nWelcome to the world of,\nLinux assembly programming!\n" }, { "code": null, "e": 3943, "s": 3769, "text": "The %assign directive can be used to define numeric constants like the EQU directive. This directive allows redefinition. For example, you may define the constant TOTAL as −" }, { "code": null, "e": 3961, "s": 3943, "text": "%assign TOTAL 10\n" }, { "code": null, "e": 4005, "s": 3961, "text": "Later in the code, you can redefine it as −" }, { "code": null, "e": 4025, "s": 4005, "text": "%assign TOTAL 20\n" }, { "code": null, "e": 4059, "s": 4025, "text": "This directive is case-sensitive." }, { "code": null, "e": 4229, "s": 4059, "text": "The %define directive allows defining both numeric and string constants. This directive is similar to the #define in C. For example, you may define the constant PTR as −" }, { "code": null, "e": 4250, "s": 4229, "text": "%define PTR [EBP+4]\n" }, { "code": null, "e": 4290, "s": 4250, "text": "The above code replaces PTR by [EBP+4]." }, { "code": null, "e": 4356, "s": 4290, "text": "This directive also allows redefinition and it is case-sensitive." }, { "code": null, "e": 4389, "s": 4356, "text": "\n 46 Lectures \n 2 hours \n" }, { "code": null, "e": 4406, "s": 4389, "text": " Frahaan Hussain" }, { "code": null, "e": 4440, "s": 4406, "text": "\n 23 Lectures \n 12 hours \n" }, { "code": null, "e": 4448, "s": 4440, "text": " Uplatz" }, { "code": null, "e": 4455, "s": 4448, "text": " Print" }, { "code": null, "e": 4466, "s": 4455, "text": " Add Notes" } ]
How to automate voxel modelling of 3D point cloud with python | Towards Data Science
What if we had a quick way to transform point clouds captured from reality into 3D meshes? And what if these 3D meshes were a voxel-based assembly? Is this something that makes sense? How can this help you for creative or professional purposes? 🤔 Let us dive in with a small lego story before exploring the python automation tips and tricks 😎. Well, If your childhood was cradled by Lego (nowadays Minecraft), then it should not be too hard to corrupt you 😊. Do you remember how fun it is to assemble these tiny blocks to form 3D representations that we can use to create new stories or simulate our favorite movies? No, my goal is not to push you to buy a huge stack of Lego but rather appeal to the coolness of these simplistic physical blocks. And how much we can do with them. But what is the actual link with the current voxel talk? Well, simply put, voxels are the 3D analog of 2D pixels (some say 3D pixels, but that sounds weird). It is a simple way to structure a 3D dataset that is unordered initially (like point clouds). You then get this assembly of primitive blocks that can easily be linked to lego assemblies. The primary difference — apart from the physical vs. digital property 😊 — is that voxels only play with one type of base element (a cube 🧊), whereas Legos let you play with various pieces of different dimensions. But if we adopt a multi-scale vision and reasoning theoretically, as put by Dassault Systèmes, Spatial Corp in Source: voxels are the perfect modeling technique for replicating reality and can go far beyond what we take them for. Indeed, our 3D world is made of stuff that super tiny voxels could approximate in vast quantities. Thus, if you have a high enough density coupled with the proper rendering techniques: you can use voxels to replicate real-world objects that would be impossible to differentiate from the real thing — in both appearance and behavior. And this is a significant benefit compared to raw point clouds: you get a behavioral possibility to simulate real-world physics that would be either impossible or hair-loss techniques with other modeling methods 😆. 💡 Hint: If you want to understand better how to represent 3D data and the technical differences between each approach, I encourage you to read the article below. towardsdatascience.com Now that you are a true corrupted voxel 🥑, it is time to get your hands dirty and learn how to quickly turn 3D point cloud into voxel assemblies in an automated fashion. Ready? learngeodata.eu Disclaimer: there is no one and unique direction when coding to solve an identified problem. The solution that I will give you relies on some clever tricks using open3d and the function stack available. But if you want to rely on a minimal number of libraries, you can also follow the article below and adapt the voxel sampling strategy to a voxel creation strategy. towardsdatascience.com In this tutorial, we will rely on only three functional libraries: laspy (pip install laspy), open3d (conda install -c open3d-admin open3d) and numpy (conda install numpy), with a python version 3.8. For this, these three simple lines: import laspy as lpimport numpy as npimport open3d as o3d 🤓 Note: The current experiments run using Python 3.8.12, laspy version: 2.0.3, numpy version 1.21.2 and open3d version 0.11.2. That way, if debugging is needed, you have some first checks to make :). Perfect, all is left now is to identify a point cloud that we would like voxelized. Luckily, I created one pretty nice for you, that you can retrieve from my drive folder: Download the dataset (.las), or visualize in your web browser using Flyvast. Once set up, we can start loading the data in our environment. 💡 Hint: If you are starting from scratch and want to follow a recipe to be up and running on Python within 5 minutes, I propose that you follow the article below that gives all the details for setting up your environment. If you do not want to install anything, you can also run it all on the cloud using the Google Colab notebook I provide at the end of the article. towardsdatascience.com First, we create two variables to handle the input path (that you should adapt to your case) and the dataname, as follows: input_path=”C:/DATA/”dataname=”heerlen_table.las” Now, it is time to load the data in our program. We first store the point cloud as a laspy.lasdata.LasData in a point_cloud variable. point_cloud=lp.read(input_path+dataname) Then, to use the data stored in the point_cloud variable, we will transform it into the open3d point cloud format. If you remember from previous tutorials, we separate what color is from the spatial coordinates (X, Y, and Z). pcd = o3d.geometry.PointCloud()pcd.points = o3d.utility.Vector3dVector(np.vstack((point_cloud.x, point_cloud.y, point_cloud.z)).transpose())pcd.colors = o3d.utility.Vector3dVector(np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose()/65535) 🤓 Note: If you look closely, you can see a weird 65535. This is because, in the laspy format, the colors are integers coded in a 16 Bit Unsigned fashions, which means that numbers range from 0 to +65535, that we want to scale to an [0,1] Interval. How crazy these maths hun 😆? We have a point cloud, and we want to fit an assembly of voxel cubes to approximate it. For this, we actually generate voxels only in parts where there are points on an established 3D grid. To get the voxel unit, we first need to compute the bounding box of the point cloud which delimit the spatial extent of our dataset. only then can we discretize the bounding box into an assembly of small 3D cubes: the voxels. In our case, we will simply compute the voxel size by giving a relative value linked to the initial bounding box to “generalize” the approach if you switch the input point cloud. For this, you can see below that we extract the bounding box of the point cloud, we take the maximum edge, and we decide to set up the voxel size to 0.5% of its value (this is absolutely arbitrary). Finally, we round up the obtained value to 4 digits without suffering from imprecise calculation thereafter. v_size=round(max(pcd.get_max_bound()-pcd.get_min_bound())*0.005,4)voxel_grid=o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,voxel_size=v_size) 🤓 Note: This is perhaps one of the most borderline code line that I wrote, but it gives a good example of what can be achieved with quick empirical statements. A lot can be improved there, especially concerning rounding errors and arbitrary thresholds.😉 Now that we have our voxel unit defined, we will actually switch to a much more efficient “representation” linked to the spatial information, but more efficient: a binary table (False or True, 0 or 1). For this, the first trick, using open3d, will be to generate the voxel grid using this command line: voxel_grid=o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,voxel_size=v_size) Awesome, you now are the owner of a voxel representation of your point cloud, which you can visualize (if outside jupyter environments) with: o3d.visualization.draw_geometries([voxel_grid]) This is great! But if we stopped there, we would be stuck in a minimal scope of utilization. Indeed, there you would be limited to using the open3d library to play with the voxel structure, with a limited number of functions, that, depending on your need, will or not fit your application. Therefore, let us dive into the process of creating a 3D mesh from this data structure 😆, that we can export in an open format (.ply or .obj) and load into other pieces of software among which MeshLab, Blender, CloudCompare, MagickaVoxels, Unity, Unreal Engine and more. Now that we have the voxel_grid, we will extract the filled voxels for having the possibility to use them as separate entities later. voxels=voxel_grid.get_voxels() If we would check what our new voxels variable looks like; we get a list containing open3d.cpu.pybind.geometry.Voxel types that hold the voxel information: Voxel with grid_index: (19, 81, 57), color: (0.330083, 0.277348, 0.22266). Okay, we will translate this into an assembly of 3D cubic meshes (8 vertices and 12 triangles describing the six faces). See the trick that we are trying to achieve 🙃? So first, let us initialize our triangle mesh entity that will hold this cube assembly: vox_mesh=o3d.geometry.TriangleMesh() Now, we will iterate over all voxels with for v in voxels, and for each voxel, we will generate a cube of size one, stored in the variable cube. We then paint it with the voxel color at hand, and we finally position the voxel on the grid using the index provided by the method grid_index. Finally, we add our newly colored and positioned cube to the mesh entity with vox_mesh+=cube. for v in voxels: cube=o3d.geometry.TriangleMesh.create_box(width=1, height=1, depth=1) cube.paint_uniform_color(v.color) cube.translate(v.grid_index, relative=False) vox_mesh+=cube 🤓 Note: The translation method takes as an argument whether or not the translation should be done relative to the first argument given (the position). In our case, because we set it to False, the first argument v.grid_index acts as the absolute coordinates in our system. We now have a 3D mesh object ready for the I/O operation... or almost. Indeed, we are yet in an arbitrary system with arbitrary integer units. To situate ourselves in the initial frame of reference imposed by the input point cloud, we must apply a rigid transformation (translation, rotation, and scale) to get back to the original position. For clarity, I decompose this ambition into three code lines. 🤓 First, we relatively translate the 3D mesh (voxel assembly) by half the voxel unit. This is explained by the fact that when we created our initial voxel grid, the reference was the lowest left point of the voxel instead of the barycenter (which is positioned at [0.5,0.5,0.5] relatively in the unit cube). vox_mesh.translate([0.5,0.5,0.5], relative=True) Then, we scale our model by the voxel size, to transform each cube unit into its real size. This makes use of the scale method that takes two arguments. The first is the scaling factor, and the second is the center used when scaling. vox_mesh.scale(voxel_size, [0,0,0]) Finally, we need to translate our voxel assembly to its true original position by translating using the voxel grid origin relatively. vox_mesh.translate(voxel_grid.origin, relative=True) Great, now we have our final cube assembly positioned correctly. An optional command is to merge close vertices. Whenever we generate a cube, we can be in a configuration where one of the corner vertices is overlapping another cube-corner vertice. Thus, it is better to clean that up while preserving the topology. vox_mesh.merge_close_vertices(0.0000001) And finally, 🥁 the last element in our pipeline is to simply export our .ply (or .obj depending on the extension you prefer) file to the folder of choice in your OS browser. o3d.io.write_triangle_mesh(input_path+”voxel_mesh_h.ply”, vox_mesh) From there, you are free to use the output file in the software of your choosing. If, when importing, you get a rotated file, you can also add the following lines to your python code and change the exported variable to vox_mesh.transform(T): T=np.array([[1, 0, 0, 0],[0, 0, 1, 0],[0, -1, 0, 0],[0, 0, 0, 1]])o3d.io.write_triangle_mesh(input_path+”4_vox_mesh_r.ply”, vox_mesh.transform(T)) What this does, is simply creating a transform matrix T, that defines a rotation counterclockwise around the Y-axis, which usually shows inverted Z and Y-axis in some software afterward. This way, if that happens to you, you will have another trick up your sleeve. You can access the code directly in your browser with this Google Colab notebook. Do you remember that we praised the versatility and simplicity of voxels at the beginning of our article? Well, I wanted to give you a bit of visual context as well. You will see below what can be achieved by playing on their representation. What is interesting with voxels is that you get an ordered structure that you can better handle. Of course, this is just a foretaste of what you will be able to do very shortly. 😉 You just learned how to import point clouds, turn them into a voxel grid, trick the system into making them 3D meshes, and then export them fully automatedly! Well done! Interestingly, having the ability to use voxels in Python will also permit to grasp better the relationships and topology of any point cloud scene, as shown in [2]. To extend the learning journey outcomes, future articles will deep dive into voxel processing, point cloud file formats, 3D data structures, semantic and instance segmentation [2–4], animation as well as deep learning [1]. We will look into managing big point cloud data as defined in the article below. towardsdatascience.com My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy. learngeodata.eu 1. Poux, F., & J.-J Ponciano. (2020). Self-Learning Ontology For Instance Segmentation Of 3d Indoor Point Cloud. ISPRS Int. Arch. of Pho. & Rem. XLIII-B2, 309–316; https://doi.org/10.5194/isprs-archives-XLIII-B2–2020–309–2020 2. Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213 3. Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412 4. Poux, F., Neuville, R., Van Wersch, L., Nys, G.-A., & Billen, R. (2017). 3D Point Clouds in Archaeology: Advances in Acquisition, Processing and Knowledge Integration Applied to Quasi-Planar Objects. Geosciences, 7(4), 96. https://doi.org/10.3390/GEOSCIENCES7040096
[ { "code": null, "e": 419, "s": 172, "text": "What if we had a quick way to transform point clouds captured from reality into 3D meshes? And what if these 3D meshes were a voxel-based assembly? Is this something that makes sense? How can this help you for creative or professional purposes? 🤔" }, { "code": null, "e": 516, "s": 419, "text": "Let us dive in with a small lego story before exploring the python automation tips and tricks 😎." }, { "code": null, "e": 789, "s": 516, "text": "Well, If your childhood was cradled by Lego (nowadays Minecraft), then it should not be too hard to corrupt you 😊. Do you remember how fun it is to assemble these tiny blocks to form 3D representations that we can use to create new stories or simulate our favorite movies?" }, { "code": null, "e": 953, "s": 789, "text": "No, my goal is not to push you to buy a huge stack of Lego but rather appeal to the coolness of these simplistic physical blocks. And how much we can do with them." }, { "code": null, "e": 1631, "s": 953, "text": "But what is the actual link with the current voxel talk? Well, simply put, voxels are the 3D analog of 2D pixels (some say 3D pixels, but that sounds weird). It is a simple way to structure a 3D dataset that is unordered initially (like point clouds). You then get this assembly of primitive blocks that can easily be linked to lego assemblies. The primary difference — apart from the physical vs. digital property 😊 — is that voxels only play with one type of base element (a cube 🧊), whereas Legos let you play with various pieces of different dimensions. But if we adopt a multi-scale vision and reasoning theoretically, as put by Dassault Systèmes, Spatial Corp in Source:" }, { "code": null, "e": 1742, "s": 1631, "text": "voxels are the perfect modeling technique for replicating reality and can go far beyond what we take them for." }, { "code": null, "e": 1927, "s": 1742, "text": "Indeed, our 3D world is made of stuff that super tiny voxels could approximate in vast quantities. Thus, if you have a high enough density coupled with the proper rendering techniques:" }, { "code": null, "e": 2075, "s": 1927, "text": "you can use voxels to replicate real-world objects that would be impossible to differentiate from the real thing — in both appearance and behavior." }, { "code": null, "e": 2290, "s": 2075, "text": "And this is a significant benefit compared to raw point clouds: you get a behavioral possibility to simulate real-world physics that would be either impossible or hair-loss techniques with other modeling methods 😆." }, { "code": null, "e": 2452, "s": 2290, "text": "💡 Hint: If you want to understand better how to represent 3D data and the technical differences between each approach, I encourage you to read the article below." }, { "code": null, "e": 2475, "s": 2452, "text": "towardsdatascience.com" }, { "code": null, "e": 2652, "s": 2475, "text": "Now that you are a true corrupted voxel 🥑, it is time to get your hands dirty and learn how to quickly turn 3D point cloud into voxel assemblies in an automated fashion. Ready?" }, { "code": null, "e": 2668, "s": 2652, "text": "learngeodata.eu" }, { "code": null, "e": 3035, "s": 2668, "text": "Disclaimer: there is no one and unique direction when coding to solve an identified problem. The solution that I will give you relies on some clever tricks using open3d and the function stack available. But if you want to rely on a minimal number of libraries, you can also follow the article below and adapt the voxel sampling strategy to a voxel creation strategy." }, { "code": null, "e": 3058, "s": 3035, "text": "towardsdatascience.com" }, { "code": null, "e": 3294, "s": 3058, "text": "In this tutorial, we will rely on only three functional libraries: laspy (pip install laspy), open3d (conda install -c open3d-admin open3d) and numpy (conda install numpy), with a python version 3.8. For this, these three simple lines:" }, { "code": null, "e": 3351, "s": 3294, "text": "import laspy as lpimport numpy as npimport open3d as o3d" }, { "code": null, "e": 3551, "s": 3351, "text": "🤓 Note: The current experiments run using Python 3.8.12, laspy version: 2.0.3, numpy version 1.21.2 and open3d version 0.11.2. That way, if debugging is needed, you have some first checks to make :)." }, { "code": null, "e": 3800, "s": 3551, "text": "Perfect, all is left now is to identify a point cloud that we would like voxelized. Luckily, I created one pretty nice for you, that you can retrieve from my drive folder: Download the dataset (.las), or visualize in your web browser using Flyvast." }, { "code": null, "e": 3863, "s": 3800, "text": "Once set up, we can start loading the data in our environment." }, { "code": null, "e": 4231, "s": 3863, "text": "💡 Hint: If you are starting from scratch and want to follow a recipe to be up and running on Python within 5 minutes, I propose that you follow the article below that gives all the details for setting up your environment. If you do not want to install anything, you can also run it all on the cloud using the Google Colab notebook I provide at the end of the article." }, { "code": null, "e": 4254, "s": 4231, "text": "towardsdatascience.com" }, { "code": null, "e": 4377, "s": 4254, "text": "First, we create two variables to handle the input path (that you should adapt to your case) and the dataname, as follows:" }, { "code": null, "e": 4427, "s": 4377, "text": "input_path=”C:/DATA/”dataname=”heerlen_table.las”" }, { "code": null, "e": 4561, "s": 4427, "text": "Now, it is time to load the data in our program. We first store the point cloud as a laspy.lasdata.LasData in a point_cloud variable." }, { "code": null, "e": 4602, "s": 4561, "text": "point_cloud=lp.read(input_path+dataname)" }, { "code": null, "e": 4828, "s": 4602, "text": "Then, to use the data stored in the point_cloud variable, we will transform it into the open3d point cloud format. If you remember from previous tutorials, we separate what color is from the spatial coordinates (X, Y, and Z)." }, { "code": null, "e": 5093, "s": 4828, "text": "pcd = o3d.geometry.PointCloud()pcd.points = o3d.utility.Vector3dVector(np.vstack((point_cloud.x, point_cloud.y, point_cloud.z)).transpose())pcd.colors = o3d.utility.Vector3dVector(np.vstack((point_cloud.red, point_cloud.green, point_cloud.blue)).transpose()/65535)" }, { "code": null, "e": 5370, "s": 5093, "text": "🤓 Note: If you look closely, you can see a weird 65535. This is because, in the laspy format, the colors are integers coded in a 16 Bit Unsigned fashions, which means that numbers range from 0 to +65535, that we want to scale to an [0,1] Interval. How crazy these maths hun 😆?" }, { "code": null, "e": 5560, "s": 5370, "text": "We have a point cloud, and we want to fit an assembly of voxel cubes to approximate it. For this, we actually generate voxels only in parts where there are points on an established 3D grid." }, { "code": null, "e": 5786, "s": 5560, "text": "To get the voxel unit, we first need to compute the bounding box of the point cloud which delimit the spatial extent of our dataset. only then can we discretize the bounding box into an assembly of small 3D cubes: the voxels." }, { "code": null, "e": 6273, "s": 5786, "text": "In our case, we will simply compute the voxel size by giving a relative value linked to the initial bounding box to “generalize” the approach if you switch the input point cloud. For this, you can see below that we extract the bounding box of the point cloud, we take the maximum edge, and we decide to set up the voxel size to 0.5% of its value (this is absolutely arbitrary). Finally, we round up the obtained value to 4 digits without suffering from imprecise calculation thereafter." }, { "code": null, "e": 6420, "s": 6273, "text": "v_size=round(max(pcd.get_max_bound()-pcd.get_min_bound())*0.005,4)voxel_grid=o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,voxel_size=v_size)" }, { "code": null, "e": 6674, "s": 6420, "text": "🤓 Note: This is perhaps one of the most borderline code line that I wrote, but it gives a good example of what can be achieved with quick empirical statements. A lot can be improved there, especially concerning rounding errors and arbitrary thresholds.😉" }, { "code": null, "e": 6977, "s": 6674, "text": "Now that we have our voxel unit defined, we will actually switch to a much more efficient “representation” linked to the spatial information, but more efficient: a binary table (False or True, 0 or 1). For this, the first trick, using open3d, will be to generate the voxel grid using this command line:" }, { "code": null, "e": 7058, "s": 6977, "text": "voxel_grid=o3d.geometry.VoxelGrid.create_from_point_cloud(pcd,voxel_size=v_size)" }, { "code": null, "e": 7200, "s": 7058, "text": "Awesome, you now are the owner of a voxel representation of your point cloud, which you can visualize (if outside jupyter environments) with:" }, { "code": null, "e": 7248, "s": 7200, "text": "o3d.visualization.draw_geometries([voxel_grid])" }, { "code": null, "e": 7809, "s": 7248, "text": "This is great! But if we stopped there, we would be stuck in a minimal scope of utilization. Indeed, there you would be limited to using the open3d library to play with the voxel structure, with a limited number of functions, that, depending on your need, will or not fit your application. Therefore, let us dive into the process of creating a 3D mesh from this data structure 😆, that we can export in an open format (.ply or .obj) and load into other pieces of software among which MeshLab, Blender, CloudCompare, MagickaVoxels, Unity, Unreal Engine and more." }, { "code": null, "e": 7943, "s": 7809, "text": "Now that we have the voxel_grid, we will extract the filled voxels for having the possibility to use them as separate entities later." }, { "code": null, "e": 7974, "s": 7943, "text": "voxels=voxel_grid.get_voxels()" }, { "code": null, "e": 8205, "s": 7974, "text": "If we would check what our new voxels variable looks like; we get a list containing open3d.cpu.pybind.geometry.Voxel types that hold the voxel information: Voxel with grid_index: (19, 81, 57), color: (0.330083, 0.277348, 0.22266)." }, { "code": null, "e": 8461, "s": 8205, "text": "Okay, we will translate this into an assembly of 3D cubic meshes (8 vertices and 12 triangles describing the six faces). See the trick that we are trying to achieve 🙃? So first, let us initialize our triangle mesh entity that will hold this cube assembly:" }, { "code": null, "e": 8498, "s": 8461, "text": "vox_mesh=o3d.geometry.TriangleMesh()" }, { "code": null, "e": 8881, "s": 8498, "text": "Now, we will iterate over all voxels with for v in voxels, and for each voxel, we will generate a cube of size one, stored in the variable cube. We then paint it with the voxel color at hand, and we finally position the voxel on the grid using the index provided by the method grid_index. Finally, we add our newly colored and positioned cube to the mesh entity with vox_mesh+=cube." }, { "code": null, "e": 9072, "s": 8881, "text": "for v in voxels: cube=o3d.geometry.TriangleMesh.create_box(width=1, height=1, depth=1) cube.paint_uniform_color(v.color) cube.translate(v.grid_index, relative=False) vox_mesh+=cube" }, { "code": null, "e": 9344, "s": 9072, "text": "🤓 Note: The translation method takes as an argument whether or not the translation should be done relative to the first argument given (the position). In our case, because we set it to False, the first argument v.grid_index acts as the absolute coordinates in our system." }, { "code": null, "e": 9750, "s": 9344, "text": "We now have a 3D mesh object ready for the I/O operation... or almost. Indeed, we are yet in an arbitrary system with arbitrary integer units. To situate ourselves in the initial frame of reference imposed by the input point cloud, we must apply a rigid transformation (translation, rotation, and scale) to get back to the original position. For clarity, I decompose this ambition into three code lines. 🤓" }, { "code": null, "e": 10056, "s": 9750, "text": "First, we relatively translate the 3D mesh (voxel assembly) by half the voxel unit. This is explained by the fact that when we created our initial voxel grid, the reference was the lowest left point of the voxel instead of the barycenter (which is positioned at [0.5,0.5,0.5] relatively in the unit cube)." }, { "code": null, "e": 10105, "s": 10056, "text": "vox_mesh.translate([0.5,0.5,0.5], relative=True)" }, { "code": null, "e": 10339, "s": 10105, "text": "Then, we scale our model by the voxel size, to transform each cube unit into its real size. This makes use of the scale method that takes two arguments. The first is the scaling factor, and the second is the center used when scaling." }, { "code": null, "e": 10375, "s": 10339, "text": "vox_mesh.scale(voxel_size, [0,0,0])" }, { "code": null, "e": 10509, "s": 10375, "text": "Finally, we need to translate our voxel assembly to its true original position by translating using the voxel grid origin relatively." }, { "code": null, "e": 10562, "s": 10509, "text": "vox_mesh.translate(voxel_grid.origin, relative=True)" }, { "code": null, "e": 10877, "s": 10562, "text": "Great, now we have our final cube assembly positioned correctly. An optional command is to merge close vertices. Whenever we generate a cube, we can be in a configuration where one of the corner vertices is overlapping another cube-corner vertice. Thus, it is better to clean that up while preserving the topology." }, { "code": null, "e": 10918, "s": 10877, "text": "vox_mesh.merge_close_vertices(0.0000001)" }, { "code": null, "e": 11092, "s": 10918, "text": "And finally, 🥁 the last element in our pipeline is to simply export our .ply (or .obj depending on the extension you prefer) file to the folder of choice in your OS browser." }, { "code": null, "e": 11160, "s": 11092, "text": "o3d.io.write_triangle_mesh(input_path+”voxel_mesh_h.ply”, vox_mesh)" }, { "code": null, "e": 11402, "s": 11160, "text": "From there, you are free to use the output file in the software of your choosing. If, when importing, you get a rotated file, you can also add the following lines to your python code and change the exported variable to vox_mesh.transform(T):" }, { "code": null, "e": 11549, "s": 11402, "text": "T=np.array([[1, 0, 0, 0],[0, 0, 1, 0],[0, -1, 0, 0],[0, 0, 0, 1]])o3d.io.write_triangle_mesh(input_path+”4_vox_mesh_r.ply”, vox_mesh.transform(T))" }, { "code": null, "e": 11814, "s": 11549, "text": "What this does, is simply creating a transform matrix T, that defines a rotation counterclockwise around the Y-axis, which usually shows inverted Z and Y-axis in some software afterward. This way, if that happens to you, you will have another trick up your sleeve." }, { "code": null, "e": 11896, "s": 11814, "text": "You can access the code directly in your browser with this Google Colab notebook." }, { "code": null, "e": 12235, "s": 11896, "text": "Do you remember that we praised the versatility and simplicity of voxels at the beginning of our article? Well, I wanted to give you a bit of visual context as well. You will see below what can be achieved by playing on their representation. What is interesting with voxels is that you get an ordered structure that you can better handle." }, { "code": null, "e": 12318, "s": 12235, "text": "Of course, this is just a foretaste of what you will be able to do very shortly. 😉" }, { "code": null, "e": 12957, "s": 12318, "text": "You just learned how to import point clouds, turn them into a voxel grid, trick the system into making them 3D meshes, and then export them fully automatedly! Well done! Interestingly, having the ability to use voxels in Python will also permit to grasp better the relationships and topology of any point cloud scene, as shown in [2]. To extend the learning journey outcomes, future articles will deep dive into voxel processing, point cloud file formats, 3D data structures, semantic and instance segmentation [2–4], animation as well as deep learning [1]. We will look into managing big point cloud data as defined in the article below." }, { "code": null, "e": 12980, "s": 12957, "text": "towardsdatascience.com" }, { "code": null, "e": 13188, "s": 12980, "text": "My contributions aim to condense actionable information so you can start from scratch to build 3D automation systems for your projects. You can get started today by taking a formation at the Geodata Academy." }, { "code": null, "e": 13204, "s": 13188, "text": "learngeodata.eu" }, { "code": null, "e": 13430, "s": 13204, "text": "1. Poux, F., & J.-J Ponciano. (2020). Self-Learning Ontology For Instance Segmentation Of 3d Indoor Point Cloud. ISPRS Int. Arch. of Pho. & Rem. XLIII-B2, 309–316; https://doi.org/10.5194/isprs-archives-XLIII-B2–2020–309–2020" }, { "code": null, "e": 13685, "s": 13430, "text": "2. Poux, F., & Billen, R. (2019). Voxel-based 3D point cloud semantic segmentation: unsupervised geometric and relationship featuring vs deep learning methods. ISPRS International Journal of Geo-Information. 8(5), 213; https://doi.org/10.3390/ijgi8050213" }, { "code": null, "e": 13898, "s": 13685, "text": "3. Poux, F., Neuville, R., Nys, G.-A., & Billen, R. (2018). 3D Point Cloud Semantic Modelling: Integrated Framework for Indoor Spaces and Furniture. Remote Sensing, 10(9), 1412. https://doi.org/10.3390/rs10091412" } ]
Why choose between R and Python?. The reticulate package makes it easy to... | by Keith McNulty | Towards Data Science
R and Python have many similarities and many differences. Most of the underlying concepts of data structures are very similar between the two languages, and there are many data science packages that now exist in both languages. But R is set up in a way that I would describe as ‘data first, application second’, whereas Python feels more application development driven from the outset. Javascript programmers, for example, would slot into Python a little quicker than they would slot into R, purely from a syntax and environment management point of view. More and more I have been working in R and Python and I have come across situations where I’d like to use both together. This can happen for numerous reasons, but the most common one is that you are building something in R, and you need functionality that you or someone else has written previously in Python. Sure, you could rewrite it in R, but that’s not very DRY is it? The reticulate package in R allows you to execute Python code inside an R session. It’s been around for a few years actually, and has been improving more and more, so I wanted to type up a brief tutorial on how it works. It you are an R native, getting reticulate up and running requires you to understand a little about how Python works — and how it typically does environment management — and so this tutorial may help you get it set up much quicker than if you tried to work it out yourself. Any programming project operates in an environment, which is where it stores and accesses all the things in needs or creates during its execution. In R, a common global environment is available to all projects, where the R base language and all installed packages are to be accessed. In this sense, all projects in R are usually run through the same common core environment. One way to think about this is to imagine that everyone in your house shares the same charging hub for their iPhones. They have to leave their room to charge the phone, and if they sell it the buyer will need to sort out their own charging arrangement. In Python, however, each project is usually set up to be completely self contained — with its own environment, its own copy of the Python base and independent copies of all the modules it needs to execute. You can think about this as everyone having their own iPhone charger in their room. They don’t have to go outside and plug in somewhere else, and if they sold the phone, it comes complete with its own charger. The Python model is more expensive in terms of installation processes and disk/memory resources, but it allows easier transfer of projects between individuals with minimal configuration, so it’s not hard to see how it has grown more directly out of a software development mindset, which is why I regard Python as more ‘application driven’. I should note here that what I am describing is ‘typical’ for most day to day users of these languages. It is not universal, and it is possible to do both types of project workflows in both languages if you know how to. We have also seen recent moves in the R language to move more towards Python-style environment management models — for example with the renv package. Here’s a little graphic I sketched out to explain in simple terms the difference between how environments usually work in R and Python. Now, if you want Python to talk to R, it still needs to find its environment — you can’t tell it to access R’s global environment. That would be like telling an English-speaker to find directions by asking a Chinese-speaker. So, to get Python working inside your R project, you need two things: A Python environment set up inside your R project, so Python can get its bearingsThe reticulate package to translate the Python code so that it works in R A Python environment set up inside your R project, so Python can get its bearings The reticulate package to translate the Python code so that it works in R From now on I am going to use a simple example. Let’s suppose I have an R project in RStudio which needs to use a function I have written in Python. So here’s a simple function which I will save in a Python script called light_years.py in my R project directory called test_python (yes, RStudio allows you to create Python scripts!). This function takes a distance in either kilometers or miles as an input and calculates how many years it would take to travel that distance at the speed of light — in other words, what is the distance in light years: from scipy.constants import cdef light_years(dist, unit = "km"): c_per_year = c * 60 * 60 * 24 * 365.25 if unit == "km": dist_meters = dist * 1000 elif unit == "mi": dist_meters = dist * 1.60934 * 1000 else: sys.exit("Cannot use that unit!") return dist_meters/c_per_year I am using a very simple function example here to keep this article straightforward, so it’s a little unrealistic, and also a bit silly since I am importing the entire scipy package just to get the value of a constant, but hopefully it will help you get the idea. Now as we discussed above, we need to provide this code with an environment. It needs: A version of Python to work throughAccess to the scipy package so it can get the constant c = speed of light A version of Python to work through Access to the scipy package so it can get the constant c = speed of light It’s not hard to set up a Python environment for your R project. Given how important project environments are in Python, numerous easy to use environment management tools exist. My favourite is Anaconda. There are two versions available. The full version, contains a large universe of all the things an environment may need, including all the most used Python modules. Then there is Miniconda, which is easier on disk space and more appropriate for limited Python users. You can get Miniconda for your operating system here. Make sure you are downloading Conda for the version of Python that you want to work in. Once you’ve installed Conda, if you are in MacOS or Linux, you’ll usually setup your environments using the command line. Just navigate to your R project directory (in my case test_python) in the terminal and use this command: conda create --name test_python Simple as that, you now have a python environment created. I usually name my environments the same as the project folder to avoid future confusion. Now you need to tell Conda to use that environment for this project, so while still in your test_python directory in the command line, use this command: conda activate test_python And now you’ve linked this project to the Python environment, and there is a copy of the Python base in there for your code to run through. Finally, our function needs the scipy package, so we will need to have that inside the environment. This is as simple as typing this inside the activated project folder: conda install scipy Conda will then install scipy and all dependencies it thinks it might need into your active environment and you are ready to go — easy as scipy, so to speak. Now, later you are going to need to tell R where to find Python in this environment, so if you use this command, you can get a list of all environments and the path to where the environments were installed: conda info --envs This tells me, for example, that my environment was installed at /Users/keithmcnulty/opt/miniconda3/envs/test_python. I can always find the Python executables inside the bin subdirectory — so the full path to the Python executable for my project is /Users/keithmcnulty/opt/miniconda3/envs/test_python/bin/python3, since I am using Python 3. This is everything we need to tell R where to find the Python environment. Now, whether you’ve set up your Python environments like I did using Conda, or whether you have used virtualenv, you’ve done the hard bit . The rest is straightforward because reticulate takes care of it. First, you need to tell R where to find the Python executable in the right environment when it loads your project. To do this, start up an empty text file and add the following, replacing my path to whatever path matches your Python executable inside the project environment you created. Sys.setenv(RETICULATE_PYTHON = "/Users/keithmcnulty/opt/miniconda3/envs/test_python/bin/python3") Now save this text file inside your project directory with the name .Renv. This is a hidden file that R will execute whenever you start up your project in RStudio. So now shut down RStudio and restart it with your test_python project open and it will now be pointing to the Python environment. Now if you haven’t already installed the reticulate R package, you should do so at this point. Once installed, you can try a few tests in the terminal to see if everything is as it should be. First you can test if R knows where Python is. reticulate::py_available() should return "TRUE". You can also test if the Python modules you need are installed: reticulate::py_module_available("scipy") should return "TRUE". Assuming all that works, you are ready to bring your function into R. You can source your Python script with a simple: reticulate::source_python("light_years.py") Now you have the light_years() function available as an R function. Let’s see how many years it would take to travel a quadrillion miles at the speed of light: > light_years(1000000000000000, "mi")[1] 170.1074 Nice! Obviously this is a very simple example but it does tell you all you need about how to integrate Python code into your R script. You can now imagine how you can bring in all sorts of functionality or packages that are currently Python-only and get them working in R — very exciting. If you want to see some advanced examples of how to use reticulate to bring Python and R together, check out my recent articles on Five Ways to Work Seamlessly Between R and Python in the Same Project, Generating Parameterized Powerpoint Documents and Running XGBoost in R. Originally I was a Pure Mathematician, then I became a Psychometrician and a Data Scientist. I am passionate about applying the rigor of all those disciplines to complex people questions. I’m also a coding geek and a massive fan of Japanese RPGs. Find me on LinkedIn or on Twitter. Also check out my blog on drkeithmcnulty.com or my soon to be released textbook on People Analytics.
[ { "code": null, "e": 727, "s": 172, "text": "R and Python have many similarities and many differences. Most of the underlying concepts of data structures are very similar between the two languages, and there are many data science packages that now exist in both languages. But R is set up in a way that I would describe as ‘data first, application second’, whereas Python feels more application development driven from the outset. Javascript programmers, for example, would slot into Python a little quicker than they would slot into R, purely from a syntax and environment management point of view." }, { "code": null, "e": 1101, "s": 727, "text": "More and more I have been working in R and Python and I have come across situations where I’d like to use both together. This can happen for numerous reasons, but the most common one is that you are building something in R, and you need functionality that you or someone else has written previously in Python. Sure, you could rewrite it in R, but that’s not very DRY is it?" }, { "code": null, "e": 1596, "s": 1101, "text": "The reticulate package in R allows you to execute Python code inside an R session. It’s been around for a few years actually, and has been improving more and more, so I wanted to type up a brief tutorial on how it works. It you are an R native, getting reticulate up and running requires you to understand a little about how Python works — and how it typically does environment management — and so this tutorial may help you get it set up much quicker than if you tried to work it out yourself." }, { "code": null, "e": 2224, "s": 1596, "text": "Any programming project operates in an environment, which is where it stores and accesses all the things in needs or creates during its execution. In R, a common global environment is available to all projects, where the R base language and all installed packages are to be accessed. In this sense, all projects in R are usually run through the same common core environment. One way to think about this is to imagine that everyone in your house shares the same charging hub for their iPhones. They have to leave their room to charge the phone, and if they sell it the buyer will need to sort out their own charging arrangement." }, { "code": null, "e": 2640, "s": 2224, "text": "In Python, however, each project is usually set up to be completely self contained — with its own environment, its own copy of the Python base and independent copies of all the modules it needs to execute. You can think about this as everyone having their own iPhone charger in their room. They don’t have to go outside and plug in somewhere else, and if they sold the phone, it comes complete with its own charger." }, { "code": null, "e": 3350, "s": 2640, "text": "The Python model is more expensive in terms of installation processes and disk/memory resources, but it allows easier transfer of projects between individuals with minimal configuration, so it’s not hard to see how it has grown more directly out of a software development mindset, which is why I regard Python as more ‘application driven’. I should note here that what I am describing is ‘typical’ for most day to day users of these languages. It is not universal, and it is possible to do both types of project workflows in both languages if you know how to. We have also seen recent moves in the R language to move more towards Python-style environment management models — for example with the renv package." }, { "code": null, "e": 3486, "s": 3350, "text": "Here’s a little graphic I sketched out to explain in simple terms the difference between how environments usually work in R and Python." }, { "code": null, "e": 3711, "s": 3486, "text": "Now, if you want Python to talk to R, it still needs to find its environment — you can’t tell it to access R’s global environment. That would be like telling an English-speaker to find directions by asking a Chinese-speaker." }, { "code": null, "e": 3781, "s": 3711, "text": "So, to get Python working inside your R project, you need two things:" }, { "code": null, "e": 3936, "s": 3781, "text": "A Python environment set up inside your R project, so Python can get its bearingsThe reticulate package to translate the Python code so that it works in R" }, { "code": null, "e": 4018, "s": 3936, "text": "A Python environment set up inside your R project, so Python can get its bearings" }, { "code": null, "e": 4092, "s": 4018, "text": "The reticulate package to translate the Python code so that it works in R" }, { "code": null, "e": 4644, "s": 4092, "text": "From now on I am going to use a simple example. Let’s suppose I have an R project in RStudio which needs to use a function I have written in Python. So here’s a simple function which I will save in a Python script called light_years.py in my R project directory called test_python (yes, RStudio allows you to create Python scripts!). This function takes a distance in either kilometers or miles as an input and calculates how many years it would take to travel that distance at the speed of light — in other words, what is the distance in light years:" }, { "code": null, "e": 5004, "s": 4644, "text": "from scipy.constants import cdef light_years(dist, unit = \"km\"): c_per_year = c * 60 * 60 * 24 * 365.25 if unit == \"km\": dist_meters = dist * 1000 elif unit == \"mi\": dist_meters = dist * 1.60934 * 1000 else: sys.exit(\"Cannot use that unit!\") return dist_meters/c_per_year" }, { "code": null, "e": 5268, "s": 5004, "text": "I am using a very simple function example here to keep this article straightforward, so it’s a little unrealistic, and also a bit silly since I am importing the entire scipy package just to get the value of a constant, but hopefully it will help you get the idea." }, { "code": null, "e": 5355, "s": 5268, "text": "Now as we discussed above, we need to provide this code with an environment. It needs:" }, { "code": null, "e": 5464, "s": 5355, "text": "A version of Python to work throughAccess to the scipy package so it can get the constant c = speed of light" }, { "code": null, "e": 5500, "s": 5464, "text": "A version of Python to work through" }, { "code": null, "e": 5574, "s": 5500, "text": "Access to the scipy package so it can get the constant c = speed of light" }, { "code": null, "e": 5752, "s": 5574, "text": "It’s not hard to set up a Python environment for your R project. Given how important project environments are in Python, numerous easy to use environment management tools exist." }, { "code": null, "e": 6187, "s": 5752, "text": "My favourite is Anaconda. There are two versions available. The full version, contains a large universe of all the things an environment may need, including all the most used Python modules. Then there is Miniconda, which is easier on disk space and more appropriate for limited Python users. You can get Miniconda for your operating system here. Make sure you are downloading Conda for the version of Python that you want to work in." }, { "code": null, "e": 6414, "s": 6187, "text": "Once you’ve installed Conda, if you are in MacOS or Linux, you’ll usually setup your environments using the command line. Just navigate to your R project directory (in my case test_python) in the terminal and use this command:" }, { "code": null, "e": 6446, "s": 6414, "text": "conda create --name test_python" }, { "code": null, "e": 6594, "s": 6446, "text": "Simple as that, you now have a python environment created. I usually name my environments the same as the project folder to avoid future confusion." }, { "code": null, "e": 6747, "s": 6594, "text": "Now you need to tell Conda to use that environment for this project, so while still in your test_python directory in the command line, use this command:" }, { "code": null, "e": 6774, "s": 6747, "text": "conda activate test_python" }, { "code": null, "e": 6914, "s": 6774, "text": "And now you’ve linked this project to the Python environment, and there is a copy of the Python base in there for your code to run through." }, { "code": null, "e": 7084, "s": 6914, "text": "Finally, our function needs the scipy package, so we will need to have that inside the environment. This is as simple as typing this inside the activated project folder:" }, { "code": null, "e": 7104, "s": 7084, "text": "conda install scipy" }, { "code": null, "e": 7262, "s": 7104, "text": "Conda will then install scipy and all dependencies it thinks it might need into your active environment and you are ready to go — easy as scipy, so to speak." }, { "code": null, "e": 7469, "s": 7262, "text": "Now, later you are going to need to tell R where to find Python in this environment, so if you use this command, you can get a list of all environments and the path to where the environments were installed:" }, { "code": null, "e": 7487, "s": 7469, "text": "conda info --envs" }, { "code": null, "e": 7903, "s": 7487, "text": "This tells me, for example, that my environment was installed at /Users/keithmcnulty/opt/miniconda3/envs/test_python. I can always find the Python executables inside the bin subdirectory — so the full path to the Python executable for my project is /Users/keithmcnulty/opt/miniconda3/envs/test_python/bin/python3, since I am using Python 3. This is everything we need to tell R where to find the Python environment." }, { "code": null, "e": 8108, "s": 7903, "text": "Now, whether you’ve set up your Python environments like I did using Conda, or whether you have used virtualenv, you’ve done the hard bit . The rest is straightforward because reticulate takes care of it." }, { "code": null, "e": 8396, "s": 8108, "text": "First, you need to tell R where to find the Python executable in the right environment when it loads your project. To do this, start up an empty text file and add the following, replacing my path to whatever path matches your Python executable inside the project environment you created." }, { "code": null, "e": 8494, "s": 8396, "text": "Sys.setenv(RETICULATE_PYTHON = \"/Users/keithmcnulty/opt/miniconda3/envs/test_python/bin/python3\")" }, { "code": null, "e": 8788, "s": 8494, "text": "Now save this text file inside your project directory with the name .Renv. This is a hidden file that R will execute whenever you start up your project in RStudio. So now shut down RStudio and restart it with your test_python project open and it will now be pointing to the Python environment." }, { "code": null, "e": 8980, "s": 8788, "text": "Now if you haven’t already installed the reticulate R package, you should do so at this point. Once installed, you can try a few tests in the terminal to see if everything is as it should be." }, { "code": null, "e": 9273, "s": 8980, "text": "First you can test if R knows where Python is. reticulate::py_available() should return \"TRUE\". You can also test if the Python modules you need are installed: reticulate::py_module_available(\"scipy\") should return \"TRUE\". Assuming all that works, you are ready to bring your function into R." }, { "code": null, "e": 9322, "s": 9273, "text": "You can source your Python script with a simple:" }, { "code": null, "e": 9366, "s": 9322, "text": "reticulate::source_python(\"light_years.py\")" }, { "code": null, "e": 9526, "s": 9366, "text": "Now you have the light_years() function available as an R function. Let’s see how many years it would take to travel a quadrillion miles at the speed of light:" }, { "code": null, "e": 9576, "s": 9526, "text": "> light_years(1000000000000000, \"mi\")[1] 170.1074" }, { "code": null, "e": 10139, "s": 9576, "text": "Nice! Obviously this is a very simple example but it does tell you all you need about how to integrate Python code into your R script. You can now imagine how you can bring in all sorts of functionality or packages that are currently Python-only and get them working in R — very exciting. If you want to see some advanced examples of how to use reticulate to bring Python and R together, check out my recent articles on Five Ways to Work Seamlessly Between R and Python in the Same Project, Generating Parameterized Powerpoint Documents and Running XGBoost in R." } ]
Write a Golang program to find the sum of digits for a given number
num = 125 => 1 + 2 + 5 = 8 num = 101 => 1 + 0 + 1 = 2 num = 151 => 1 + 5 + 1 = 7 Step 1: Define a function that accepts numbers(num); type is int. Step 2: Start a true loop until num becomes 0 and define res:=0. Step 3: Find modulo and add to res. Step 4: Divide num by 10. Step 5: Return res. Live Demo package main import "fmt" func findDigitSum(num int) int { res := 0 for num>0 { res += num % 10 num /= 10 } return res } func main(){ fmt.Println(findDigitSum(168)) fmt.Println(findDigitSum(576)) fmt.Println(findDigitSum(12345)) } 15 18 15
[ { "code": null, "e": 1089, "s": 1062, "text": "num = 125 => 1 + 2 + 5 = 8" }, { "code": null, "e": 1116, "s": 1089, "text": "num = 101 => 1 + 0 + 1 = 2" }, { "code": null, "e": 1143, "s": 1116, "text": "num = 151 => 1 + 5 + 1 = 7" }, { "code": null, "e": 1209, "s": 1143, "text": "Step 1: Define a function that accepts numbers(num); type is int." }, { "code": null, "e": 1274, "s": 1209, "text": "Step 2: Start a true loop until num becomes 0 and define res:=0." }, { "code": null, "e": 1310, "s": 1274, "text": "Step 3: Find modulo and add to res." }, { "code": null, "e": 1336, "s": 1310, "text": "Step 4: Divide num by 10." }, { "code": null, "e": 1356, "s": 1336, "text": "Step 5: Return res." }, { "code": null, "e": 1366, "s": 1356, "text": "Live Demo" }, { "code": null, "e": 1631, "s": 1366, "text": "package main\nimport \"fmt\"\nfunc findDigitSum(num int) int {\n res := 0\n for num>0 {\n res += num % 10\n num /= 10\n }\n return res\n}\n\nfunc main(){\n fmt.Println(findDigitSum(168))\n fmt.Println(findDigitSum(576))\n fmt.Println(findDigitSum(12345))\n}" }, { "code": null, "e": 1640, "s": 1631, "text": "15\n18\n15" } ]
VB.Net - Button Control
The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event. Let's create a label by dragging a Button control from the Toolbox ad dropping it on the form. The following are some of the commonly used properties of the Button control − AutoSizeMode Gets or sets the mode by which the Button automatically resizes itself. BackColor Gets or sets the background color of the control. BackgroundImage Gets or sets the background image displayed in the control. DialogResult Gets or sets a value that is returned to the parent form when the button is clicked. This is used while creating dialog boxes. ForeColor Gets or sets the foreground color of the control. Image Gets or sets the image that is displayed on a button control. Location Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container. TabIndex Gets or sets the tab order of the control within its container. Text Gets or sets the text associated with this control. The following are some of the commonly used methods of the Button control − GetPreferredSize Retrieves the size of a rectangular area into which a control can be fitted. NotifyDefault Notifies the Button whether it is the default button so that it can adjust its appearance accordingly. Select Activates the control. ToString Returns a String containing the name of the Component, if any. This method should not be overridden. The following are some of the commonly used events of the Button control − Click Occurs when the control is clicked. DoubleClick Occurs when the user double-clicks the Button control. GotFocus Occurs when the control receives focus. TabIndexChanged Occurs when the TabIndex property value changes. TextChanged Occurs when the Text property value changes. Validated Occurs when the control is finished validating. Consult Microsoft documentation for detailed list of properties, methods and events of the Button control. In the following example, we create three buttons. In this example, let us − Set captions for the buttons Set captions for the buttons Set some image for the button Set some image for the button Handle the click events of each buttons Handle the click events of each buttons Take following steps − Drag and drop a Label control on the form. Drag and drop a Label control on the form. Set the Text property to provide the caption "Tutorials Point". Set the Text property to provide the caption "Tutorials Point". Drag and drop three buttons on the form. Drag and drop three buttons on the form. Using the properties window, change the Name properties of the buttons to btnMoto, btnLogo and btnExit respectively. Using the properties window, change the Name properties of the buttons to btnMoto, btnLogo and btnExit respectively. Using the properties window, change the Text properties of the buttons to Show Moto, Show Logo and Exit respectively. Using the properties window, change the Text properties of the buttons to Show Moto, Show Logo and Exit respectively. Drag and Drop another button, using the properties window, set its Image property and name it btnImage. Drag and Drop another button, using the properties window, set its Image property and name it btnImage. At this stage, the form looks like − Click the form and add following code in the code editor − Public Class Form1 Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load ' Set the caption bar text of the form. Me.Text = "tutorialspont.com" btnImage.Visible = False End Sub Private Sub btnMoto_Click(sender As Object, e As EventArgs) Handles btnMoto.Click btnImage.Visible = False Label1.Text = "Simple Easy Learning" End Sub Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click Application.Exit() End Sub Private Sub btnLogo_Click(sender As Object, e As EventArgs) Handles btnLogo.Click Label1.Visible = False btnImage.Visible = True End Sub End Class Clicking the first button, displays − Clicking the second button displays − Clicking the third button, exits the application. 63 Lectures 4 hours Frahaan Hussain 103 Lectures 12 hours Arnold Higuit 60 Lectures 9.5 hours Arnold Higuit 97 Lectures 9 hours Arnold Higuit Print Add Notes Bookmark this page
[ { "code": null, "e": 2448, "s": 2300, "text": "The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event." }, { "code": null, "e": 2543, "s": 2448, "text": "Let's create a label by dragging a Button control from the Toolbox ad dropping it on the form." }, { "code": null, "e": 2622, "s": 2543, "text": "The following are some of the commonly used properties of the Button control −" }, { "code": null, "e": 2635, "s": 2622, "text": "AutoSizeMode" }, { "code": null, "e": 2707, "s": 2635, "text": "Gets or sets the mode by which the Button automatically resizes itself." }, { "code": null, "e": 2717, "s": 2707, "text": "BackColor" }, { "code": null, "e": 2767, "s": 2717, "text": "Gets or sets the background color of the control." }, { "code": null, "e": 2783, "s": 2767, "text": "BackgroundImage" }, { "code": null, "e": 2843, "s": 2783, "text": "Gets or sets the background image displayed in the control." }, { "code": null, "e": 2856, "s": 2843, "text": "DialogResult" }, { "code": null, "e": 2983, "s": 2856, "text": "Gets or sets a value that is returned to the parent form when the button is clicked. This is used while creating dialog boxes." }, { "code": null, "e": 2993, "s": 2983, "text": "ForeColor" }, { "code": null, "e": 3043, "s": 2993, "text": "Gets or sets the foreground color of the control." }, { "code": null, "e": 3049, "s": 3043, "text": "Image" }, { "code": null, "e": 3111, "s": 3049, "text": "Gets or sets the image that is displayed on a button control." }, { "code": null, "e": 3120, "s": 3111, "text": "Location" }, { "code": null, "e": 3241, "s": 3120, "text": "Gets or sets the coordinates of the upper-left corner of the control relative to the upper-left corner of its container." }, { "code": null, "e": 3250, "s": 3241, "text": "TabIndex" }, { "code": null, "e": 3314, "s": 3250, "text": "Gets or sets the tab order of the control within its container." }, { "code": null, "e": 3319, "s": 3314, "text": "Text" }, { "code": null, "e": 3371, "s": 3319, "text": "Gets or sets the text associated with this control." }, { "code": null, "e": 3447, "s": 3371, "text": "The following are some of the commonly used methods of the Button control −" }, { "code": null, "e": 3464, "s": 3447, "text": "GetPreferredSize" }, { "code": null, "e": 3541, "s": 3464, "text": "Retrieves the size of a rectangular area into which a control can be fitted." }, { "code": null, "e": 3555, "s": 3541, "text": "NotifyDefault" }, { "code": null, "e": 3658, "s": 3555, "text": "Notifies the Button whether it is the default button so that it can adjust its appearance accordingly." }, { "code": null, "e": 3665, "s": 3658, "text": "Select" }, { "code": null, "e": 3688, "s": 3665, "text": "Activates the control." }, { "code": null, "e": 3697, "s": 3688, "text": "ToString" }, { "code": null, "e": 3798, "s": 3697, "text": "Returns a String containing the name of the Component, if any. This method should not be overridden." }, { "code": null, "e": 3873, "s": 3798, "text": "The following are some of the commonly used events of the Button control −" }, { "code": null, "e": 3879, "s": 3873, "text": "Click" }, { "code": null, "e": 3915, "s": 3879, "text": "Occurs when the control is clicked." }, { "code": null, "e": 3927, "s": 3915, "text": "DoubleClick" }, { "code": null, "e": 3982, "s": 3927, "text": "Occurs when the user double-clicks the Button control." }, { "code": null, "e": 3991, "s": 3982, "text": "GotFocus" }, { "code": null, "e": 4031, "s": 3991, "text": "Occurs when the control receives focus." }, { "code": null, "e": 4047, "s": 4031, "text": "TabIndexChanged" }, { "code": null, "e": 4097, "s": 4047, "text": "Occurs when the TabIndex property value changes. " }, { "code": null, "e": 4109, "s": 4097, "text": "TextChanged" }, { "code": null, "e": 4154, "s": 4109, "text": "Occurs when the Text property value changes." }, { "code": null, "e": 4164, "s": 4154, "text": "Validated" }, { "code": null, "e": 4212, "s": 4164, "text": "Occurs when the control is finished validating." }, { "code": null, "e": 4319, "s": 4212, "text": "Consult Microsoft documentation for detailed list of properties, methods and events of the Button control." }, { "code": null, "e": 4396, "s": 4319, "text": "In the following example, we create three buttons. In this example, let us −" }, { "code": null, "e": 4425, "s": 4396, "text": "Set captions for the buttons" }, { "code": null, "e": 4454, "s": 4425, "text": "Set captions for the buttons" }, { "code": null, "e": 4484, "s": 4454, "text": "Set some image for the button" }, { "code": null, "e": 4514, "s": 4484, "text": "Set some image for the button" }, { "code": null, "e": 4554, "s": 4514, "text": "Handle the click events of each buttons" }, { "code": null, "e": 4594, "s": 4554, "text": "Handle the click events of each buttons" }, { "code": null, "e": 4617, "s": 4594, "text": "Take following steps −" }, { "code": null, "e": 4660, "s": 4617, "text": "Drag and drop a Label control on the form." }, { "code": null, "e": 4703, "s": 4660, "text": "Drag and drop a Label control on the form." }, { "code": null, "e": 4767, "s": 4703, "text": "Set the Text property to provide the caption \"Tutorials Point\"." }, { "code": null, "e": 4831, "s": 4767, "text": "Set the Text property to provide the caption \"Tutorials Point\"." }, { "code": null, "e": 4872, "s": 4831, "text": "Drag and drop three buttons on the form." }, { "code": null, "e": 4913, "s": 4872, "text": "Drag and drop three buttons on the form." }, { "code": null, "e": 5030, "s": 4913, "text": "Using the properties window, change the Name properties of the buttons to btnMoto, btnLogo and btnExit respectively." }, { "code": null, "e": 5147, "s": 5030, "text": "Using the properties window, change the Name properties of the buttons to btnMoto, btnLogo and btnExit respectively." }, { "code": null, "e": 5265, "s": 5147, "text": "Using the properties window, change the Text properties of the buttons to Show Moto, Show Logo and Exit respectively." }, { "code": null, "e": 5383, "s": 5265, "text": "Using the properties window, change the Text properties of the buttons to Show Moto, Show Logo and Exit respectively." }, { "code": null, "e": 5487, "s": 5383, "text": "Drag and Drop another button, using the properties window, set its Image property and name it btnImage." }, { "code": null, "e": 5591, "s": 5487, "text": "Drag and Drop another button, using the properties window, set its Image property and name it btnImage." }, { "code": null, "e": 5628, "s": 5591, "text": "At this stage, the form looks like −" }, { "code": null, "e": 5687, "s": 5628, "text": "Click the form and add following code in the code editor −" }, { "code": null, "e": 6380, "s": 5687, "text": "Public Class Form1\n Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load\n ' Set the caption bar text of the form. \n Me.Text = \"tutorialspont.com\"\n btnImage.Visible = False\n End Sub\n \n Private Sub btnMoto_Click(sender As Object, e As EventArgs) Handles btnMoto.Click\n btnImage.Visible = False\n Label1.Text = \"Simple Easy Learning\"\n End Sub\n \n Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click\n Application.Exit()\n End Sub\n \n Private Sub btnLogo_Click(sender As Object, e As EventArgs) Handles btnLogo.Click\n Label1.Visible = False\n btnImage.Visible = True\n End Sub\nEnd Class" }, { "code": null, "e": 6418, "s": 6380, "text": "Clicking the first button, displays −" }, { "code": null, "e": 6456, "s": 6418, "text": "Clicking the second button displays −" }, { "code": null, "e": 6506, "s": 6456, "text": "Clicking the third button, exits the application." }, { "code": null, "e": 6539, "s": 6506, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 6556, "s": 6539, "text": " Frahaan Hussain" }, { "code": null, "e": 6591, "s": 6556, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 6606, "s": 6591, "text": " Arnold Higuit" }, { "code": null, "e": 6641, "s": 6606, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6656, "s": 6641, "text": " Arnold Higuit" }, { "code": null, "e": 6689, "s": 6656, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 6704, "s": 6689, "text": " Arnold Higuit" }, { "code": null, "e": 6711, "s": 6704, "text": " Print" }, { "code": null, "e": 6722, "s": 6711, "text": " Add Notes" } ]
Storing Output on a File in Julia
04 May, 2022 Julia provides a vast library to store and save the output in multiple file formats. We can store the output in various forms such as CSV(comma-separated value) or in Excel or just simply a text file. In order to store the data in a text file, we need to use open() function with “w” flag which allows us to write output to a file. The open function takes two parameters first the filename and second the mode you need the file to open. In order to store data in a text file, we need to use the .txt extension after the filename. Also if the file is not present it will create the file for you. The console prints the numbers of characters in the file. Example: Julia # Output in a txt file# opening file with .txt extension and in write mode # let the ans be the output of a questionans = "Hello World" open("geek.txt", "w") do file write(file, ans)end Another method to store data is to use DelimitedFiles.writedlm() function. The function takes two parameters the first is the filename and the second parameter is output. In order to use this function, we need to import DelimitedFiles. Example: Julia # importing the moduleusing DelimitedFiles # The number is the output of random numbersnumbers = rand(5) writedlm("geek.txt", numbers) We can store data on CSV files by importing a library CSV.jl which provides various functions related to storing reading and writing output into a CSV file. It provides more control than other methods. We also need to install the DataFrame package. In order to use this, we need to install the package. To install type the following in Julia console. # importing the Pkg module using Pkg Pkg.add("CSV") # installing the DataFrame Pkg.add("DataFrames") Now to store output we just need to import it. Example: Julia # importing the required moduleusing CSV, DataFrames # a 2d array of random numbersnumbers = rand(5, 5) # using write methodCSV.write("geek.csv", DataFrame(numbers), header = false) Another way to store data is to use DelimitedFiles.writedlm() function. The function takes two parameters the first is the filename and the second parameter is output. In order to use this function, we need to import DelimitedFiles. Here also file extension must be .csv. Example: Julia # importing DelimitedFilesusing DelimitedFiles # Here numbers is a 2d arraynumbers = rand(5, 5) # Since it is a comma separated file we need to,# to separate into a table of row and colwritedlm("geek.csv", numbers, ", ") We can store data on excel file by importing a library XLXS.jl which provides various functions related to storing reading and writing output into an excel file. It provides more control than other methods. To use the package we first need to install the package. To install the package just write the following command in Julia terminal. # importing the Pkg module using Pkg Pkg.add("XLSX") Now to store the data we can use its various methods. We need to use the “w” flag to able to write output the xls file. Example: Julia using XLSX # using "w" to write outputXLSX.openxlsx("geek.xls", mode="w") do f sheet = f[1] # Used for renaming the file for convience XLSX.rename!(sheet, "new_sheet") # This will add output along A column sheet["A1"] = "Welcome" sheet["A2"] = "to" sheet["A3"] = "GeeksForGeeks"end Another way to store data is to use DelimitedFiles.writedlm() function. The function takes two parameters the first is the filename and the second parameter is output. In order to use this function, we need to import DelimitedFiles. Here also file extension must be .xls. Example: Julia # importing DelimitedFilesusing DelimitedFiles # here numbers is an array# of 5*5 random numbersnumbers = rand(5, 5) # writedlm functionwritedlm("geek.xls", numbers) Code_Mech sagartomar9927 Picked Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Exception handling in Julia Get array dimensions and size of a dimension in Julia - size() Method Get number of elements of array in Julia - length() Method Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) NamedTuple in Julia Find maximum element along with its index in Julia - findmax() Method Searching in Array for a given element in Julia Getting the maximum value from a list in Julia - max() Method Broadcasting across arrays in Julia Working with Text Files in Julia
[ { "code": null, "e": 28, "s": 0, "text": "\n04 May, 2022" }, { "code": null, "e": 229, "s": 28, "text": "Julia provides a vast library to store and save the output in multiple file formats. We can store the output in various forms such as CSV(comma-separated value) or in Excel or just simply a text file." }, { "code": null, "e": 466, "s": 229, "text": "In order to store the data in a text file, we need to use open() function with “w” flag which allows us to write output to a file. The open function takes two parameters first the filename and second the mode you need the file to open. " }, { "code": null, "e": 683, "s": 466, "text": "In order to store data in a text file, we need to use the .txt extension after the filename. Also if the file is not present it will create the file for you. The console prints the numbers of characters in the file." }, { "code": null, "e": 692, "s": 683, "text": "Example:" }, { "code": null, "e": 698, "s": 692, "text": "Julia" }, { "code": "# Output in a txt file# opening file with .txt extension and in write mode # let the ans be the output of a questionans = \"Hello World\" open(\"geek.txt\", \"w\") do file write(file, ans)end", "e": 887, "s": 698, "text": null }, { "code": null, "e": 1123, "s": 887, "text": "Another method to store data is to use DelimitedFiles.writedlm() function. The function takes two parameters the first is the filename and the second parameter is output. In order to use this function, we need to import DelimitedFiles." }, { "code": null, "e": 1132, "s": 1123, "text": "Example:" }, { "code": null, "e": 1138, "s": 1132, "text": "Julia" }, { "code": "# importing the moduleusing DelimitedFiles # The number is the output of random numbersnumbers = rand(5) writedlm(\"geek.txt\", numbers)", "e": 1273, "s": 1138, "text": null }, { "code": null, "e": 1527, "s": 1278, "text": "We can store data on CSV files by importing a library CSV.jl which provides various functions related to storing reading and writing output into a CSV file. It provides more control than other methods. We also need to install the DataFrame package." }, { "code": null, "e": 1631, "s": 1529, "text": "In order to use this, we need to install the package. To install type the following in Julia console." }, { "code": null, "e": 1735, "s": 1633, "text": "# importing the Pkg module\nusing Pkg\nPkg.add(\"CSV\")\n\n# installing the DataFrame\nPkg.add(\"DataFrames\")" }, { "code": null, "e": 1785, "s": 1737, "text": " Now to store output we just need to import it." }, { "code": null, "e": 1796, "s": 1787, "text": "Example:" }, { "code": null, "e": 1804, "s": 1798, "text": "Julia" }, { "code": "# importing the required moduleusing CSV, DataFrames # a 2d array of random numbersnumbers = rand(5, 5) # using write methodCSV.write(\"geek.csv\", DataFrame(numbers), header = false) ", "e": 2066, "s": 1804, "text": null }, { "code": null, "e": 2338, "s": 2066, "text": "Another way to store data is to use DelimitedFiles.writedlm() function. The function takes two parameters the first is the filename and the second parameter is output. In order to use this function, we need to import DelimitedFiles. Here also file extension must be .csv." }, { "code": null, "e": 2347, "s": 2338, "text": "Example:" }, { "code": null, "e": 2353, "s": 2347, "text": "Julia" }, { "code": "# importing DelimitedFilesusing DelimitedFiles # Here numbers is a 2d arraynumbers = rand(5, 5) # Since it is a comma separated file we need to,# to separate into a table of row and colwritedlm(\"geek.csv\", numbers, \", \")", "e": 2574, "s": 2353, "text": null }, { "code": null, "e": 2781, "s": 2574, "text": "We can store data on excel file by importing a library XLXS.jl which provides various functions related to storing reading and writing output into an excel file. It provides more control than other methods." }, { "code": null, "e": 2913, "s": 2781, "text": "To use the package we first need to install the package. To install the package just write the following command in Julia terminal." }, { "code": null, "e": 2967, "s": 2913, "text": "# importing the Pkg module\nusing Pkg\n\nPkg.add(\"XLSX\")" }, { "code": null, "e": 3088, "s": 2967, "text": "Now to store the data we can use its various methods. We need to use the “w” flag to able to write output the xls file. " }, { "code": null, "e": 3098, "s": 3088, "text": "Example: " }, { "code": null, "e": 3104, "s": 3098, "text": "Julia" }, { "code": "using XLSX # using \"w\" to write outputXLSX.openxlsx(\"geek.xls\", mode=\"w\") do f sheet = f[1] # Used for renaming the file for convience XLSX.rename!(sheet, \"new_sheet\") # This will add output along A column sheet[\"A1\"] = \"Welcome\" sheet[\"A2\"] = \"to\" sheet[\"A3\"] = \"GeeksForGeeks\"end", "e": 3480, "s": 3104, "text": null }, { "code": null, "e": 3757, "s": 3485, "text": "Another way to store data is to use DelimitedFiles.writedlm() function. The function takes two parameters the first is the filename and the second parameter is output. In order to use this function, we need to import DelimitedFiles. Here also file extension must be .xls." }, { "code": null, "e": 3768, "s": 3759, "text": "Example:" }, { "code": null, "e": 3776, "s": 3770, "text": "Julia" }, { "code": "# importing DelimitedFilesusing DelimitedFiles # here numbers is an array# of 5*5 random numbersnumbers = rand(5, 5) # writedlm functionwritedlm(\"geek.xls\", numbers)", "e": 3942, "s": 3776, "text": null }, { "code": null, "e": 3957, "s": 3947, "text": "Code_Mech" }, { "code": null, "e": 3972, "s": 3957, "text": "sagartomar9927" }, { "code": null, "e": 3979, "s": 3972, "text": "Picked" }, { "code": null, "e": 3985, "s": 3979, "text": "Julia" }, { "code": null, "e": 4083, "s": 3985, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4111, "s": 4083, "text": "Exception handling in Julia" }, { "code": null, "e": 4181, "s": 4111, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 4240, "s": 4181, "text": "Get number of elements of array in Julia - length() Method" }, { "code": null, "e": 4313, "s": 4240, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 4333, "s": 4313, "text": "NamedTuple in Julia" }, { "code": null, "e": 4403, "s": 4333, "text": "Find maximum element along with its index in Julia - findmax() Method" }, { "code": null, "e": 4451, "s": 4403, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 4513, "s": 4451, "text": "Getting the maximum value from a list in Julia - max() Method" }, { "code": null, "e": 4549, "s": 4513, "text": "Broadcasting across arrays in Julia" } ]
How to change the font and size of buttons and frame in tkinter?
Tkinter Button Widgets are a general way to provide Event Handling in a variety of applications. Sometimes, we may need to style the buttons which are defined in an application. In order to add styling in the button widgets, first create an instance of Button widget using a variable. Then, add some property like fontfamily, font-size, padding, etc. into it. The most general way to resize the button is by resizing the text in it. In this example, we have created a button that can be resized by changing the value in the 'font' property. #Import tkinter library from tkinter import * #Create an instance of tkinter frame win= Tk() #Set the Geometry win.geometry("750x250") def click_to_close(): win.destroy() #Create a Button button= Button(win, text= "Click to Close", font= ('Helvetica 20 bold italic'), command=click_to_close) button.pack(pady=20) win.mainloop() Running the given code will generate a button with some text in it which can be resized by changing the value of the font-size.
[ { "code": null, "e": 1620, "s": 1187, "text": "Tkinter Button Widgets are a general way to provide Event Handling in a variety of applications. Sometimes, we may need to style the buttons which are defined in an application. In order to add styling in the button widgets, first create an instance of Button widget using a variable. Then, add some property like fontfamily, font-size, padding, etc. into it. The most general way to resize the button is by resizing the text in it." }, { "code": null, "e": 1728, "s": 1620, "text": "In this example, we have created a button that can be resized by changing the value in the 'font' property." }, { "code": null, "e": 2056, "s": 1728, "text": "#Import tkinter library\nfrom tkinter import *\n#Create an instance of tkinter frame\nwin= Tk()\n#Set the Geometry\nwin.geometry(\"750x250\")\ndef click_to_close():\nwin.destroy()\n#Create a Button\nbutton= Button(win, text= \"Click to Close\", font= ('Helvetica 20\nbold italic'), command=click_to_close)\nbutton.pack(pady=20)\nwin.mainloop()" }, { "code": null, "e": 2184, "s": 2056, "text": "Running the given code will generate a button with some text in it which can be resized by changing the value of the font-size." } ]
GATE | GATE CS 2020 | Question 15
11 Aug, 2021 The preorder traversal of a binary search tree is 15, 10, 12, 11, 20, 18, 16, 19. Which one of the following is the postorder traversal of the tree ?(A) 10, 11, 12, 15, 16, 18, 19, 20(B) 11, 12, 10, 16, 19, 18, 20, 15(C) 20, 19, 18, 16, 15, 12, 11, 10(D) 19, 16, 18, 20, 11, 12, 10, 15Answer: (B)Explanation: Please refer – Find postorder traversal of BST from preorder traversal // C++ program for finding postorder // traversal of BST from preorder traversal #include <bits/stdc++.h> using namespace std; // Function to find postorder traversal from // preorder traversal. void findPostOrderUtil(int pre[], int n, int minval, int maxval, int& preIndex) { // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex] < minval || pre[preIndex] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex]; preIndex++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); cout << val << " "; } // Function to find postorder traversal. void findPostOrder(int pre[], int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. int preIndex = 0; findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex); } // Driver code int main() { int pre[] = { 15, 10, 12, 11, 20, 18, 16, 19 }; int n = sizeof(pre) / sizeof(pre[0]); // Calling function findPostOrder(pre, n); return 0; } Code – https://ide.geeksforgeeks.org/t49kAtJwr7 Option (B) is correct. GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:0037:49 / 1:16:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=fP8QED8d6ws" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Aug, 2021" }, { "code": null, "e": 408, "s": 28, "text": "The preorder traversal of a binary search tree is 15, 10, 12, 11, 20, 18, 16, 19. Which one of the following is the postorder traversal of the tree ?(A) 10, 11, 12, 15, 16, 18, 19, 20(B) 11, 12, 10, 16, 19, 18, 20, 15(C) 20, 19, 18, 16, 15, 12, 11, 10(D) 19, 16, 18, 20, 11, 12, 10, 15Answer: (B)Explanation: Please refer – Find postorder traversal of BST from preorder traversal" }, { "code": "// C++ program for finding postorder // traversal of BST from preorder traversal #include <bits/stdc++.h> using namespace std; // Function to find postorder traversal from // preorder traversal. void findPostOrderUtil(int pre[], int n, int minval, int maxval, int& preIndex) { // If entire preorder array is traversed then // return as no more element is left to be // added to post order array. if (preIndex == n) return; // If array element does not lie in range specified, // then it is not part of current subtree. if (pre[preIndex] < minval || pre[preIndex] > maxval) { return; } // Store current value, to be printed later, after // printing left and right subtrees. Increment // preIndex to find left and right subtrees, // and pass this updated value to recursive calls. int val = pre[preIndex]; preIndex++; // All elements with value between minval and val // lie in left subtree. findPostOrderUtil(pre, n, minval, val, preIndex); // All elements with value between val and maxval // lie in right subtree. findPostOrderUtil(pre, n, val, maxval, preIndex); cout << val << \" \"; } // Function to find postorder traversal. void findPostOrder(int pre[], int n) { // To store index of element to be // traversed next in preorder array. // This is passed by reference to // utility function. int preIndex = 0; findPostOrderUtil(pre, n, INT_MIN, INT_MAX, preIndex); } // Driver code int main() { int pre[] = { 15, 10, 12, 11, 20, 18, 16, 19 }; int n = sizeof(pre) / sizeof(pre[0]); // Calling function findPostOrder(pre, n); return 0; } ", "e": 2137, "s": 408, "text": null }, { "code": null, "e": 2185, "s": 2137, "text": "Code – https://ide.geeksforgeeks.org/t49kAtJwr7" }, { "code": null, "e": 2208, "s": 2185, "text": "Option (B) is correct." }, { "code": null, "e": 3242, "s": 2208, "text": "GATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSE - YouTubeGeeksforGeeks GATE Computer Science17.5K subscribersGATE PYQs 2019 and 2020 | Programming and Data Structures | Shubham Agrawal | GeeksforGeeks GATE CSEWatch 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:0037:49 / 1:16:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=fP8QED8d6ws\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 3247, "s": 3242, "text": "GATE" } ]
What is a Melting Point?
26 Sep, 2021 The matter is characterised by different states. There can be a transition from one state of matter to another. For instance, a solid can be transformed into a liquid and a liquid can be changed into a gas. For example, most of the solid metals, transform into liquid on heating and turn into vapour on further heating. The change in matter state, for instance, from solid to liquid state occurs because of the following two characteristic factors : Temperature – There is a transition from solid to liquid state with the change, that is, an increase in temperature. On raising the temperature, ice changes into water. Also, liquid changes to the vapour state. Ice → Water → Vapour Pressure – Solids are characterised by closely packed particles, with no spaces between them. They don’t allow any compression, and therefore, there is no effect of pressure on solids. On constantly applying the pressure, the solid gets deformed and finally breaks. The process of a solid turning into a liquid state is called melting. It is also known as fusion. The reverse process of a liquid becoming a solid, is in turn called solidification. The temperature at which melting occurs for any pure substance is termed the melting point of that substance. It is considered to be a characteristic of that substance. Energy is required by the system to carry out the melting of a solid to a liquid. It is an endothermic reaction. Every pure substance requires a certain amount of energy which is required to change from a solid to a liquid state. Energy is exclusively required to carry out the transition of the substance, from the solid to the liquid substance. The phase of a substance is changed, and the temperature remains unchanged. Therefore, melting is known to be an isothermal process, since the substance remains at the same unmodified temperature. Melting or fusion is the process by which a solid substance changes into a liquid on heating. On heating a substance, the particles vibrate with greater intensity and move more vigorously. Heat energy is produced. The particles gain sufficient kinetic energy to overcome the strong forces of attraction. They gain energy to break through to form small groups of particles. Solids, therefore, melt to form a liquid state. Melting of a substance occurs at defined ambient pressure conditions. The energy supplied to melt a system is known as enthalpy of fusion or entropy of fusion. However, some of the substances pose an exception to this process, and heat has to be removed from these systems in order to melt them. e.g. Helium. The temperature at which a solid substance melts and transforms into a liquid at atmospheric pressure is termed the melting point of a substance. Different solids display varying melting points. For example, the melting point of wax is 63 °C. The greater the melting point of the substances, the more will be the intraparticle forces of attractions binding the particles. For instance, in the solid form of water, ice melts at a temperature of 0 °C to form liquid water. Therefore, the melting point of ice is 0 °C at atmospheric pressure. At the melting point, the solid and liquid states of matter coexist together. The melting point of a substance is its characteristic property influenced by the applied pressure. The application can be observed during the process of snow skating. The weight of the skater gets concentrated on a thin line, there is considerable pressure applied on the ice slab. This results in the melting of ice beneath the shoe of the skater. This melting ice lubricates the undersides of his skating shoes. This makes it possible to skate on the ice. The heating curve denotes the temperature on the y-axis and the heat that has been supplied on the x-axis respectively. Let us assume a constant rate of heating, owing to which the x-axis can be shown as the amount of time which is shown as the substance is being heated. The curve majorly shows two main points: The portion of the graphs, where the temperature rises as and when heat is supplied to the system, and The portion of the graphs plateaus where the temperature remains at a constant level. Change in phase occurs at this plateaus. Question 1: What causes phase change? Answer: When the temperature or pressure change of a system occurs, the phase changes. Upon increasing the temperature or pressure of the system, the intramolecular forces of attraction increase. Upon decreasing the temperature, the molecules or atoms turn into a rigid structure. Question 2: Does temperature change during the process of heating ice? Answer: As we constantly supply heat energy to transform ice into water, the temperature of the system doesn’t change. The heat energy is absorbed by the ice changing slowing into the liquid state. Both the states of matter coexist together during this process. Question 3: How does melting occur in the case of amorphous solids? Answer: The non-crystalline solids, such as glass or pitch undergo melting by slowly decreasing viscosity with the simultaneous increase in the temperature. However, there is no sharp transformation from solid to liquid state. Question 4: Define heat of fusion. Answer: The amount of energy required by a pure substance to change from the solid to a liquid state is termed as the enthalpy of fusion (or heat of fusion) of the substance. It is denoted by ΔHfus. Question 5: Differentiate between boiling or melting. Answer: Boiling is the process of melting of liquid to gas state whereas melting is the transformation of solid to liquid state. Question 6: How does energy change occur during melting? Answer: Heat must be supplied to the enclosed system in order to simulate the melting of the substance. When energy is supplied the atoms composing the substance break away and are pulled apart farther. Question 7: Which element has the highest melting point? Answer: Tungsten is the element posing the highest melting point, 3,687 K which makes it suitable for making electrical filaments in incandescent lamps. Picked Class 9 School Chemistry School Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2021" }, { "code": null, "e": 348, "s": 28, "text": "The matter is characterised by different states. There can be a transition from one state of matter to another. For instance, a solid can be transformed into a liquid and a liquid can be changed into a gas. For example, most of the solid metals, transform into liquid on heating and turn into vapour on further heating." }, { "code": null, "e": 478, "s": 348, "text": "The change in matter state, for instance, from solid to liquid state occurs because of the following two characteristic factors :" }, { "code": null, "e": 710, "s": 478, "text": "Temperature – There is a transition from solid to liquid state with the change, that is, an increase in temperature. On raising the temperature, ice changes into water. Also, liquid changes to the vapour state. Ice → Water → Vapour" }, { "code": null, "e": 976, "s": 710, "text": "Pressure – Solids are characterised by closely packed particles, with no spaces between them. They don’t allow any compression, and therefore, there is no effect of pressure on solids. On constantly applying the pressure, the solid gets deformed and finally breaks." }, { "code": null, "e": 1159, "s": 976, "text": "The process of a solid turning into a liquid state is called melting. It is also known as fusion. The reverse process of a liquid becoming a solid, is in turn called solidification. " }, { "code": null, "e": 1558, "s": 1159, "text": "The temperature at which melting occurs for any pure substance is termed the melting point of that substance. It is considered to be a characteristic of that substance. Energy is required by the system to carry out the melting of a solid to a liquid. It is an endothermic reaction. Every pure substance requires a certain amount of energy which is required to change from a solid to a liquid state." }, { "code": null, "e": 1873, "s": 1558, "text": "Energy is exclusively required to carry out the transition of the substance, from the solid to the liquid substance. The phase of a substance is changed, and the temperature remains unchanged. Therefore, melting is known to be an isothermal process, since the substance remains at the same unmodified temperature. " }, { "code": null, "e": 2294, "s": 1873, "text": "Melting or fusion is the process by which a solid substance changes into a liquid on heating. On heating a substance, the particles vibrate with greater intensity and move more vigorously. Heat energy is produced. The particles gain sufficient kinetic energy to overcome the strong forces of attraction. They gain energy to break through to form small groups of particles. Solids, therefore, melt to form a liquid state." }, { "code": null, "e": 2603, "s": 2294, "text": "Melting of a substance occurs at defined ambient pressure conditions. The energy supplied to melt a system is known as enthalpy of fusion or entropy of fusion. However, some of the substances pose an exception to this process, and heat has to be removed from these systems in order to melt them. e.g. Helium." }, { "code": null, "e": 2750, "s": 2603, "text": "The temperature at which a solid substance melts and transforms into a liquid at atmospheric pressure is termed the melting point of a substance. " }, { "code": null, "e": 3144, "s": 2750, "text": "Different solids display varying melting points. For example, the melting point of wax is 63 °C. The greater the melting point of the substances, the more will be the intraparticle forces of attractions binding the particles. For instance, in the solid form of water, ice melts at a temperature of 0 °C to form liquid water. Therefore, the melting point of ice is 0 °C at atmospheric pressure." }, { "code": null, "e": 3322, "s": 3144, "text": "At the melting point, the solid and liquid states of matter coexist together. The melting point of a substance is its characteristic property influenced by the applied pressure." }, { "code": null, "e": 3681, "s": 3322, "text": "The application can be observed during the process of snow skating. The weight of the skater gets concentrated on a thin line, there is considerable pressure applied on the ice slab. This results in the melting of ice beneath the shoe of the skater. This melting ice lubricates the undersides of his skating shoes. This makes it possible to skate on the ice." }, { "code": null, "e": 3994, "s": 3681, "text": "The heating curve denotes the temperature on the y-axis and the heat that has been supplied on the x-axis respectively. Let us assume a constant rate of heating, owing to which the x-axis can be shown as the amount of time which is shown as the substance is being heated. The curve majorly shows two main points:" }, { "code": null, "e": 4097, "s": 3994, "text": "The portion of the graphs, where the temperature rises as and when heat is supplied to the system, and" }, { "code": null, "e": 4224, "s": 4097, "text": "The portion of the graphs plateaus where the temperature remains at a constant level. Change in phase occurs at this plateaus." }, { "code": null, "e": 4262, "s": 4224, "text": "Question 1: What causes phase change?" }, { "code": null, "e": 4270, "s": 4262, "text": "Answer:" }, { "code": null, "e": 4543, "s": 4270, "text": "When the temperature or pressure change of a system occurs, the phase changes. Upon increasing the temperature or pressure of the system, the intramolecular forces of attraction increase. Upon decreasing the temperature, the molecules or atoms turn into a rigid structure." }, { "code": null, "e": 4614, "s": 4543, "text": "Question 2: Does temperature change during the process of heating ice?" }, { "code": null, "e": 4622, "s": 4614, "text": "Answer:" }, { "code": null, "e": 4876, "s": 4622, "text": "As we constantly supply heat energy to transform ice into water, the temperature of the system doesn’t change. The heat energy is absorbed by the ice changing slowing into the liquid state. Both the states of matter coexist together during this process." }, { "code": null, "e": 4944, "s": 4876, "text": "Question 3: How does melting occur in the case of amorphous solids?" }, { "code": null, "e": 4952, "s": 4944, "text": "Answer:" }, { "code": null, "e": 5171, "s": 4952, "text": "The non-crystalline solids, such as glass or pitch undergo melting by slowly decreasing viscosity with the simultaneous increase in the temperature. However, there is no sharp transformation from solid to liquid state." }, { "code": null, "e": 5206, "s": 5171, "text": "Question 4: Define heat of fusion." }, { "code": null, "e": 5214, "s": 5206, "text": "Answer:" }, { "code": null, "e": 5405, "s": 5214, "text": "The amount of energy required by a pure substance to change from the solid to a liquid state is termed as the enthalpy of fusion (or heat of fusion) of the substance. It is denoted by ΔHfus." }, { "code": null, "e": 5459, "s": 5405, "text": "Question 5: Differentiate between boiling or melting." }, { "code": null, "e": 5467, "s": 5459, "text": "Answer:" }, { "code": null, "e": 5588, "s": 5467, "text": "Boiling is the process of melting of liquid to gas state whereas melting is the transformation of solid to liquid state." }, { "code": null, "e": 5645, "s": 5588, "text": "Question 6: How does energy change occur during melting?" }, { "code": null, "e": 5653, "s": 5645, "text": "Answer:" }, { "code": null, "e": 5848, "s": 5653, "text": "Heat must be supplied to the enclosed system in order to simulate the melting of the substance. When energy is supplied the atoms composing the substance break away and are pulled apart farther." }, { "code": null, "e": 5905, "s": 5848, "text": "Question 7: Which element has the highest melting point?" }, { "code": null, "e": 5913, "s": 5905, "text": "Answer:" }, { "code": null, "e": 6058, "s": 5913, "text": "Tungsten is the element posing the highest melting point, 3,687 K which makes it suitable for making electrical filaments in incandescent lamps." }, { "code": null, "e": 6065, "s": 6058, "text": "Picked" }, { "code": null, "e": 6073, "s": 6065, "text": "Class 9" }, { "code": null, "e": 6090, "s": 6073, "text": "School Chemistry" }, { "code": null, "e": 6106, "s": 6090, "text": "School Learning" } ]
PostgreSQL – Connecting to the database using Python
30 Aug, 2020 PostgreSQL API for Python allows user to interact with the PostgreSQL database using the psycopg2 module. In this article we will look into the process of connecting to a PostgreSQL database using Python. First we will need to install the psycopg2 module with the below command in the command prompt: pip install psycopg2 For the purpose of example we will be needing a sample database. To create so, follow the below steps: First open a PostgreSQL client tool like pgadmin4 or psql. Second login to the database using your credentials. Finally use the below command to create a database (say, School) CREATE DATABASE school; To connect to the above created database (ie, school), we use the connect () function. The connect() function is used to create a new database session and it returns a new connection class instance. To do so use the below syntax: Syntax: conn = psycopg2.connect("dbname=suppliers user=postgres password=postgres") To make it convenient to use you can use the below method: 1. First create a database.ini file with the credentials as shown below: [postgresql] host=localhost database=school user=postgres password=5555 Now, the following config() function reads the database.ini file and returns connection parameters. The same config() function is added in the config.py file: Python3 #!/usr/bin/pythonfrom configparser import ConfigParser def config(filename='database.ini', section='postgresql'): # create a parser parser = ConfigParser() # read config file parser.read(filename) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db Example: The following connect() function connects to the school database that we created earlier and returns the PostgreSQL database version. Python3 #!/usr/bin/pythonimport psycopg2from config import config def connect(): """ Connect to the PostgreSQL database server """ conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() # execute a statement print('PostgreSQL database version:') cur.execute('SELECT version()') # display the PostgreSQL database server version db_version = cur.fetchone() print(db_version) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.') if __name__ == '__main__': connect() Output: postgreSQL-administration postgreSQL-managing-database PostgreSQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Aug, 2020" }, { "code": null, "e": 233, "s": 28, "text": "PostgreSQL API for Python allows user to interact with the PostgreSQL database using the psycopg2 module. In this article we will look into the process of connecting to a PostgreSQL database using Python." }, { "code": null, "e": 329, "s": 233, "text": "First we will need to install the psycopg2 module with the below command in the command prompt:" }, { "code": null, "e": 351, "s": 329, "text": "pip install psycopg2\n" }, { "code": null, "e": 454, "s": 351, "text": "For the purpose of example we will be needing a sample database. To create so, follow the below steps:" }, { "code": null, "e": 513, "s": 454, "text": "First open a PostgreSQL client tool like pgadmin4 or psql." }, { "code": null, "e": 566, "s": 513, "text": "Second login to the database using your credentials." }, { "code": null, "e": 631, "s": 566, "text": "Finally use the below command to create a database (say, School)" }, { "code": null, "e": 656, "s": 631, "text": "CREATE DATABASE school;\n" }, { "code": null, "e": 855, "s": 656, "text": "To connect to the above created database (ie, school), we use the connect () function. The connect() function is used to create a new database session and it returns a new connection class instance." }, { "code": null, "e": 886, "s": 855, "text": "To do so use the below syntax:" }, { "code": null, "e": 971, "s": 886, "text": "Syntax: conn = psycopg2.connect(\"dbname=suppliers user=postgres password=postgres\")\n" }, { "code": null, "e": 1030, "s": 971, "text": "To make it convenient to use you can use the below method:" }, { "code": null, "e": 1103, "s": 1030, "text": "1. First create a database.ini file with the credentials as shown below:" }, { "code": null, "e": 1176, "s": 1103, "text": "[postgresql]\nhost=localhost\ndatabase=school\nuser=postgres\npassword=5555\n" }, { "code": null, "e": 1335, "s": 1176, "text": "Now, the following config() function reads the database.ini file and returns connection parameters. The same config() function is added in the config.py file:" }, { "code": null, "e": 1343, "s": 1335, "text": "Python3" }, { "code": "#!/usr/bin/pythonfrom configparser import ConfigParser def config(filename='database.ini', section='postgresql'): # create a parser parser = ConfigParser() # read config file parser.read(filename) # get section, default to postgresql db = {} if parser.has_section(section): params = parser.items(section) for param in params: db[param[0]] = param[1] else: raise Exception('Section {0} not found in the {1} file'.format(section, filename)) return db", "e": 1858, "s": 1343, "text": null }, { "code": null, "e": 1867, "s": 1858, "text": "Example:" }, { "code": null, "e": 2002, "s": 1867, "text": "The following connect() function connects to the school database that we created earlier and returns the PostgreSQL database version." }, { "code": null, "e": 2010, "s": 2002, "text": "Python3" }, { "code": "#!/usr/bin/pythonimport psycopg2from config import config def connect(): \"\"\" Connect to the PostgreSQL database server \"\"\" conn = None try: # read connection parameters params = config() # connect to the PostgreSQL server print('Connecting to the PostgreSQL database...') conn = psycopg2.connect(**params) # create a cursor cur = conn.cursor() # execute a statement print('PostgreSQL database version:') cur.execute('SELECT version()') # display the PostgreSQL database server version db_version = cur.fetchone() print(db_version) # close the communication with the PostgreSQL cur.close() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: if conn is not None: conn.close() print('Database connection closed.') if __name__ == '__main__': connect()", "e": 2970, "s": 2010, "text": null }, { "code": null, "e": 2978, "s": 2970, "text": "Output:" }, { "code": null, "e": 3004, "s": 2978, "text": "postgreSQL-administration" }, { "code": null, "e": 3033, "s": 3004, "text": "postgreSQL-managing-database" }, { "code": null, "e": 3044, "s": 3033, "text": "PostgreSQL" }, { "code": null, "e": 3051, "s": 3044, "text": "Python" } ]
Getting union of sets in Julia – union() and union!() Methods
26 Mar, 2020 The union() is an inbuilt function in julia which is used to construct the union of the specified sets. Syntax: union(s, itrs...) Parameters: s: Specified first set. itrs: Specified second set. Returns: It returns the constructed union of the specified sets. Example: # Julia program to illustrate # the use of union() method # Getting the constructed union of the specified sets.println(union([5, 10], [15, 20]))println(union([2, 4], [2, 4, 6]))println(union([1, 3], 5:7))println(union(Set([2, 4, 6]), 1:5)) Output: [5, 10, 15, 20] [2, 4, 6] [1, 3, 5, 6, 7] [4, 2, 6, 1, 3, 5] The union!() is an inbuilt function in julia which is used to construct the union of passed in sets and overwrite s with the result. Syntax:union!(s::Union{AbstractSet, AbstractVector}, itrs...) Parameters: s: Specified set. itrs: Specified iterator. Returns: It returns the constructed union of passed in sets and overwrite s with the result. Example: # Julia program to illustrate # the use of union !() method # Getting constructed union of passed # in sets and overwrite s with the result.s1 = Set([1, 2, 3, 4]);union !(s1, 5:7:9);println(s1) s2 = Set([1, 2, 3, 4]);union !(s2, 1:2:3);println(s2) Output: Set([4, 2, 3, 5, 1]) Set([4, 2, 3, 1]) Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 132, "s": 28, "text": "The union() is an inbuilt function in julia which is used to construct the union of the specified sets." }, { "code": null, "e": 158, "s": 132, "text": "Syntax: union(s, itrs...)" }, { "code": null, "e": 170, "s": 158, "text": "Parameters:" }, { "code": null, "e": 194, "s": 170, "text": "s: Specified first set." }, { "code": null, "e": 222, "s": 194, "text": "itrs: Specified second set." }, { "code": null, "e": 287, "s": 222, "text": "Returns: It returns the constructed union of the specified sets." }, { "code": null, "e": 296, "s": 287, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of union() method # Getting the constructed union of the specified sets.println(union([5, 10], [15, 20]))println(union([2, 4], [2, 4, 6]))println(union([1, 3], 5:7))println(union(Set([2, 4, 6]), 1:5))", "e": 539, "s": 296, "text": null }, { "code": null, "e": 547, "s": 539, "text": "Output:" }, { "code": null, "e": 608, "s": 547, "text": "[5, 10, 15, 20]\n[2, 4, 6]\n[1, 3, 5, 6, 7]\n[4, 2, 6, 1, 3, 5]" }, { "code": null, "e": 741, "s": 608, "text": "The union!() is an inbuilt function in julia which is used to construct the union of passed in sets and overwrite s with the result." }, { "code": null, "e": 803, "s": 741, "text": "Syntax:union!(s::Union{AbstractSet, AbstractVector}, itrs...)" }, { "code": null, "e": 815, "s": 803, "text": "Parameters:" }, { "code": null, "e": 833, "s": 815, "text": "s: Specified set." }, { "code": null, "e": 859, "s": 833, "text": "itrs: Specified iterator." }, { "code": null, "e": 952, "s": 859, "text": "Returns: It returns the constructed union of passed in sets and overwrite s with the result." }, { "code": null, "e": 961, "s": 952, "text": "Example:" }, { "code": "# Julia program to illustrate # the use of union !() method # Getting constructed union of passed # in sets and overwrite s with the result.s1 = Set([1, 2, 3, 4]);union !(s1, 5:7:9);println(s1) s2 = Set([1, 2, 3, 4]);union !(s2, 1:2:3);println(s2)", "e": 1212, "s": 961, "text": null }, { "code": null, "e": 1220, "s": 1212, "text": "Output:" }, { "code": null, "e": 1259, "s": 1220, "text": "Set([4, 2, 3, 5, 1])\nSet([4, 2, 3, 1])" }, { "code": null, "e": 1265, "s": 1259, "text": "Julia" } ]
How to Export Multiple Dataframes to Different Excel Worksheets in R
17 Jun, 2021 In this article, we are going to see how to export multiple dataframe to different Excel Worksheets in R Programming Language. We will be using the xlsx module. The xlsx library provides R functions to read/write/format Excel files and their formats. The xlsx package gives programmatic control of Excel files. The modification of the sheet’s components like the rows, columns, and cells can be carried out as well as the sheet fonts, colors and texts can be formatted. The contents of the file can be read into a data frame and the data frame can also be appended to the sheet. The package can be installed into the working space using the following syntax in R : install.packages ("xlsx") Method 1: Using write.xlsx() The write.xlsx() method in R can be used to write a data frame into an Excel workbook. In case the R object specified as the first argument of the method is not a data frame, it can be converted to one. Syntax: write.xlsx(df, file, sheetName = “Sheet1”, col.names = TRUE, row.names = TRUE, append = FALSE, showNA = TRUE, password = NULL ) Arguments : df – the data.frame to write in the workbook. file – the path to the output file. sheetName – a name assigned to the sheet. col.names – indicator of whether the column names of df should be written on the file. row.names – indicator of whether the row names of df should be written on the file. append – a logical value indicating if df should be appended to an existing file. password – a password string. The following code snippet creates multiple data frames and then adds them to different sheets of the same Excel sheet using the write.xlsx() method, with the specified file path name. In the case, of the second data frame, the append attribute should be equated to a TRUE value, to add the subsequent data frame to the same sheet. R # importing required librarylibrary("xlsx") # creating data framedf1 <- data.frame(col1 = c(1:3), col2 = letters[1:3], col3 = TRUE)print ("Dataframe 1")print (df1) # creating another data framedf2 <- data.frame(c1 = FALSE, c2 = rep(1,5), c3 = seq(0.1,length.out = 5, by = 0.1))print ("Dataframe 2")print (df2) # accessing file pathfile = "/Users/yashchauhan/Desktop/gfg.xlsx" # writing contents to xlsx sheetwrite.xlsx(df1, file = file, sheetName = "sheet1", row.names = FALSE) write.xlsx(df2, file= file, sheetName = "sheet2", append = TRUE, row.names = FALSE) Output: [1] "Dataframe 1" col1 col2 col3 1 1 a TRUE 2 2 b TRUE 3 3 c TRUE [1] "Dataframe 2" c1 c2 c3 1 FALSE 1 0.1 2 FALSE 1 0.2 3 FALSE 1 0.3 4 FALSE 1 0.4 5 FALSE 1 0.5 Method 2: Using createWorkbook() createWorkbook() method in R is used to create an empty workbook object. It returns a java object which contains the reference to an empty object. createWorkbook(type = "xlsx") createSheet() method in R returns the created sheet object. The workbook object can be used to invoke the createSheet() call. createSheet(wb, sheetName) The addDataFrame() method in R can be used to add a data frame to a sheet, allowing for different column styles. This method is better than the previous because it is used to customise rows and columns as well. Syntax: addDataFrame( df , sheetName, col.names = TRUE, row.names = TRUE, startRow = 1, startColumn = 1) Arguments : df – the data.frame to write in the workbook. sheetName – a name assigned to the sheet. col.names – indicator of whether the column names of df should be written on the file. row.names – indicator of whether the row names of df should be written on the file. startRow – starting row indicator. startColumn – starting column indicator. The workbook can then be saved using the saveWorkbook() method, which has the following syntax : saveWorkbook(wb, file, password = NULL) Code: R # importing required librarylibrary("xlsx") # creating data framedf1 <- data.frame(col1 = c(1:3), col2 = letters[1:3], col3 = TRUE)print ("Dataframe 1")print (df1) # creating another data framedf2 <- data.frame(c1 = FALSE, c2 = rep(1,5), c3 = seq(0.1,length.out = 5,by=0.1))print ("Dataframe 2")print (df2) # accessing file pathfile = "/Users/yashchauhan/Desktop/gfg2.xlsx" # creating workbookwb = createWorkbook()sht = createSheet(wb, "Sheet 1") # add data frameaddDataFrame(df1, sheet=sht, startColumn = 1, row.names = FALSE) # create another sheetsht = createSheet(wb, "Sheet 2") # add data frameaddDataFrame(df2, sheet = sht, startColumn = 1, row.names = FALSE) saveWorkbook(wb, file) Output: [1] "Dataframe 1" col1 col2 col3 1 1 a TRUE 2 2 b TRUE 3 3 c TRUE [1] "Dataframe 2" c1 c2 c3 1 FALSE 1 0.1 2 FALSE 1 0.2 3 FALSE 1 0.3 4 FALSE 1 0.4 5 FALSE 1 0.5 Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement Logistic Regression in R Programming Replace Specific Characters in String in R How to import an Excel File into R ? Joining of Dataframes in R Programming
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jun, 2021" }, { "code": null, "e": 155, "s": 28, "text": "In this article, we are going to see how to export multiple dataframe to different Excel Worksheets in R Programming Language." }, { "code": null, "e": 694, "s": 155, "text": "We will be using the xlsx module. The xlsx library provides R functions to read/write/format Excel files and their formats. The xlsx package gives programmatic control of Excel files. The modification of the sheet’s components like the rows, columns, and cells can be carried out as well as the sheet fonts, colors and texts can be formatted. The contents of the file can be read into a data frame and the data frame can also be appended to the sheet. The package can be installed into the working space using the following syntax in R : " }, { "code": null, "e": 720, "s": 694, "text": "install.packages (\"xlsx\")" }, { "code": null, "e": 749, "s": 720, "text": "Method 1: Using write.xlsx()" }, { "code": null, "e": 953, "s": 749, "text": "The write.xlsx() method in R can be used to write a data frame into an Excel workbook. In case the R object specified as the first argument of the method is not a data frame, it can be converted to one. " }, { "code": null, "e": 1089, "s": 953, "text": "Syntax: write.xlsx(df, file, sheetName = “Sheet1”, col.names = TRUE, row.names = TRUE, append = FALSE, showNA = TRUE, password = NULL )" }, { "code": null, "e": 1102, "s": 1089, "text": "Arguments : " }, { "code": null, "e": 1148, "s": 1102, "text": "df – the data.frame to write in the workbook." }, { "code": null, "e": 1184, "s": 1148, "text": "file – the path to the output file." }, { "code": null, "e": 1226, "s": 1184, "text": "sheetName – a name assigned to the sheet." }, { "code": null, "e": 1313, "s": 1226, "text": "col.names – indicator of whether the column names of df should be written on the file." }, { "code": null, "e": 1398, "s": 1313, "text": "row.names – indicator of whether the row names of df should be written on the file." }, { "code": null, "e": 1480, "s": 1398, "text": "append – a logical value indicating if df should be appended to an existing file." }, { "code": null, "e": 1510, "s": 1480, "text": "password – a password string." }, { "code": null, "e": 1844, "s": 1510, "text": "The following code snippet creates multiple data frames and then adds them to different sheets of the same Excel sheet using the write.xlsx() method, with the specified file path name. In the case, of the second data frame, the append attribute should be equated to a TRUE value, to add the subsequent data frame to the same sheet. " }, { "code": null, "e": 1846, "s": 1844, "text": "R" }, { "code": "# importing required librarylibrary(\"xlsx\") # creating data framedf1 <- data.frame(col1 = c(1:3), col2 = letters[1:3], col3 = TRUE)print (\"Dataframe 1\")print (df1) # creating another data framedf2 <- data.frame(c1 = FALSE, c2 = rep(1,5), c3 = seq(0.1,length.out = 5, by = 0.1))print (\"Dataframe 2\")print (df2) # accessing file pathfile = \"/Users/yashchauhan/Desktop/gfg.xlsx\" # writing contents to xlsx sheetwrite.xlsx(df1, file = file, sheetName = \"sheet1\", row.names = FALSE) write.xlsx(df2, file= file, sheetName = \"sheet2\", append = TRUE, row.names = FALSE)", "e": 2527, "s": 1846, "text": null }, { "code": null, "e": 2535, "s": 2527, "text": "Output:" }, { "code": null, "e": 2732, "s": 2535, "text": "[1] \"Dataframe 1\" \ncol1 col2 col3 \n1 1 a TRUE \n2 2 b TRUE \n3 3 c TRUE\n[1] \"Dataframe 2\" \nc1 c2 c3 \n1 FALSE 1 0.1 \n2 FALSE 1 0.2 \n3 FALSE 1 0.3 \n4 FALSE 1 0.4 \n5 FALSE 1 0.5" }, { "code": null, "e": 2765, "s": 2732, "text": "Method 2: Using createWorkbook()" }, { "code": null, "e": 2913, "s": 2765, "text": "createWorkbook() method in R is used to create an empty workbook object. It returns a java object which contains the reference to an empty object. " }, { "code": null, "e": 2943, "s": 2913, "text": "createWorkbook(type = \"xlsx\")" }, { "code": null, "e": 3070, "s": 2943, "text": "createSheet() method in R returns the created sheet object. The workbook object can be used to invoke the createSheet() call. " }, { "code": null, "e": 3097, "s": 3070, "text": "createSheet(wb, sheetName)" }, { "code": null, "e": 3309, "s": 3097, "text": "The addDataFrame() method in R can be used to add a data frame to a sheet, allowing for different column styles. This method is better than the previous because it is used to customise rows and columns as well. " }, { "code": null, "e": 3415, "s": 3309, "text": "Syntax: addDataFrame( df , sheetName, col.names = TRUE, row.names = TRUE, startRow = 1, startColumn = 1) " }, { "code": null, "e": 3428, "s": 3415, "text": "Arguments : " }, { "code": null, "e": 3474, "s": 3428, "text": "df – the data.frame to write in the workbook." }, { "code": null, "e": 3516, "s": 3474, "text": "sheetName – a name assigned to the sheet." }, { "code": null, "e": 3603, "s": 3516, "text": "col.names – indicator of whether the column names of df should be written on the file." }, { "code": null, "e": 3688, "s": 3603, "text": "row.names – indicator of whether the row names of df should be written on the file." }, { "code": null, "e": 3723, "s": 3688, "text": "startRow – starting row indicator." }, { "code": null, "e": 3764, "s": 3723, "text": "startColumn – starting column indicator." }, { "code": null, "e": 3861, "s": 3764, "text": "The workbook can then be saved using the saveWorkbook() method, which has the following syntax :" }, { "code": null, "e": 3901, "s": 3861, "text": "saveWorkbook(wb, file, password = NULL)" }, { "code": null, "e": 3907, "s": 3901, "text": "Code:" }, { "code": null, "e": 3909, "s": 3907, "text": "R" }, { "code": "# importing required librarylibrary(\"xlsx\") # creating data framedf1 <- data.frame(col1 = c(1:3), col2 = letters[1:3], col3 = TRUE)print (\"Dataframe 1\")print (df1) # creating another data framedf2 <- data.frame(c1 = FALSE, c2 = rep(1,5), c3 = seq(0.1,length.out = 5,by=0.1))print (\"Dataframe 2\")print (df2) # accessing file pathfile = \"/Users/yashchauhan/Desktop/gfg2.xlsx\" # creating workbookwb = createWorkbook()sht = createSheet(wb, \"Sheet 1\") # add data frameaddDataFrame(df1, sheet=sht, startColumn = 1, row.names = FALSE) # create another sheetsht = createSheet(wb, \"Sheet 2\") # add data frameaddDataFrame(df2, sheet = sht, startColumn = 1, row.names = FALSE) saveWorkbook(wb, file)", "e": 4698, "s": 3909, "text": null }, { "code": null, "e": 4706, "s": 4698, "text": "Output:" }, { "code": null, "e": 4903, "s": 4706, "text": "[1] \"Dataframe 1\" \ncol1 col2 col3 \n1 1 a TRUE \n2 2 b TRUE \n3 3 c TRUE\n[1] \"Dataframe 2\" \nc1 c2 c3 \n1 FALSE 1 0.1 \n2 FALSE 1 0.2 \n3 FALSE 1 0.3 \n4 FALSE 1 0.4 \n5 FALSE 1 0.5" }, { "code": null, "e": 4910, "s": 4903, "text": "Picked" }, { "code": null, "e": 4918, "s": 4910, "text": "R-Excel" }, { "code": null, "e": 4929, "s": 4918, "text": "R Language" }, { "code": null, "e": 5027, "s": 4929, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5079, "s": 5027, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 5137, "s": 5079, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 5172, "s": 5137, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 5210, "s": 5172, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 5259, "s": 5210, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 5276, "s": 5259, "text": "R - if statement" }, { "code": null, "e": 5313, "s": 5276, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 5356, "s": 5313, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 5393, "s": 5356, "text": "How to import an Excel File into R ?" } ]
Program to print an array in Pendulum Arrangement
08 Jun, 2022 Write a program to input a list of integers in an array and arrange them in a way similar to the to-and-fro movement of a Pendulum. The minimum element out of the list of integers, must come in center position of array. The number in the ascending order next to the minimum, goes to the right, the next higher number goes to the left of minimum number and it continues. As higher numbers are reached, one goes to one side in a to-and-fro manner similar to that of a Pendulum. Examples: Input : 1 3 2 5 4 Output :5 3 1 2 4 Explanation: The minimum element is 1, so it is moved to the middle. The next higher element 2 is moved to the right of the middle element while the next higher element 3 is moved to the left of the middle element and this process is continued. Input : 11 12 31 14 5 Output :31 12 5 11 14 The idea is to sort the array first. Once the array is sorted, use an auxiliary array to store elements one by one. C++ Java Python3 C# PHP Javascript // C++ program for pendulum arrangement of numbers#include <bits/stdc++.h>using namespace std; // Prints pendulum arrangement of arr[]void pendulumArrangement(int arr[], int n){ // sorting the elements sort(arr, arr+n); // Auxiliary array to store output int op[n]; // calculating the middle index int mid = (n-1)/2; // storing the minimum element in the middle // i is index for output array and j is for // input array. int j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid+i] = arr[j++]; op[mid-i] = arr[j++]; } // adjustment for when no. of elements is even if (n%2 == 0) op[mid+i] = arr[j]; // Printing the pendulum arrangement cout << "Pendulum arrangement:" << endl; for (i = 0 ; i < n; i++) cout << op[i] << " "; cout << endl;} // Driver functionint main(){ //input Array int arr[] = {14, 6, 19, 21, 12}; // calculating the length of array A int n = sizeof(arr)/sizeof(arr[0]); // calling pendulum function pendulumArrangement(arr, n); return 0;} // Java program for pendulum arrangement of numbers import java.util.Arrays; class Test{ // Prints pendulum arrangement of arr[] static void pendulumArrangement(int arr[], int n) { // sorting the elements Arrays.sort(arr); // Auxiliary array to store output int op[] = new int[n]; // calculating the middle index int mid = (n-1)/2; // storing the minimum element in the middle // i is index for output array and j is for // input array. int j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid+i] = arr[j++]; op[mid-i] = arr[j++]; } // adjustment for when no. of elements is even if (n%2 == 0) op[mid+i] = arr[j]; // Printing the pendulum arrangement System.out.println("Pendulum arrangement:"); for (i = 0 ; i < n; i++) System.out.print(op[i] + " "); System.out.println(); } // Driver method public static void main(String[] args) { //input Array int arr[] = {14, 6, 19, 21, 12}; // calling pendulum function pendulumArrangement(arr, arr.length); }} # Python 3 program for pendulum# arrangement of numbers # Prints pendulum arrangement of arr[]def pendulumArrangement(arr, n): # sorting the elements arr.sort() # Auxiliary array to store output op = [0] * n # calculating the middle index mid = int((n-1)/2) # storing the minimum # element in the middle # i is index for output # array and j is for # input array. j = 1 i = 1 op[mid] = arr[0] for i in range(1,mid+1): op[mid+i] = arr[j] j+=1 op[mid-i] = arr[j] j+=1 # adjustment for when no. # of elements is even if (int(n%2) == 0): op[mid+i] = arr[j] # Printing the pendulum arrangement print("Pendulum arrangement:") for i in range(0,n): print(op[i],end=" ") # Driver function# input Arrayarr = [14, 6, 19, 21, 12] # calculating the length of array An = len(arr) # calling pendulum functionpendulumArrangement(arr, n) # This code is contributed by# Smitha Dinesh Semwal // C# program for pendulum // arrangement of numbersusing System; class Test { // Prints pendulum arrangement of arr[] static void pendulumArrangement(int []arr, int n) { // sorting the elements Array.Sort(arr); // Auxiliary array to store output int []op = new int[n]; // calculating the middle index int mid = (n - 1) / 2; // storing the minimum element in // the middle i is index for output // array and j is for input array. int j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid + i] = arr[j++]; op[mid - i] = arr[j++]; } // adjustment for when no. // of elements is even if (n % 2 == 0) op[mid + i] = arr[j]; // Printing the pendulum arrangement Console.Write("Pendulum arrangement:"); for (i = 0 ; i < n; i++) Console.Write(op[i] + " "); Console.WriteLine(); } // Driver code public static void Main() { //input Array int []arr = {14, 6, 19, 21, 12}; // calling pendulum function pendulumArrangement(arr, arr.Length); }} // This code is contributed by Nitin Mittal. <?php// PHP program for pendulum // arrangement of numbers // Prints pendulam arrangement of arr[]function pendulumArrangement($arr, $n){ // sorting the elements sort($arr, $n); sort($arr); // Auxiliary array to // store output $op[$n] = NULL; // calculating the // middle index $mid = floor(($n - 1) / 2); // storing the minimum // element in the middle // i is index for output // array and j is for // input array. $j = 1; $i = 1; $op[$mid] = $arr[0]; for ($i = 1; $i <= $mid; $i++) { $op[$mid + $i] = $arr[$j++]; $op[$mid - $i] = $arr[$j++]; } // adjustment for when no. // of elements is even if ($n % 2 == 0) $op[$mid + $i] = $arr[$j]; // Printing the pendulum // arrangement echo "Pendulum arrangement:" ; for ($i = 0 ; $i < $n; $i++) echo $op[$i], " "; echo "\n";} // Driver Code //input Array $arr = array(14, 6, 19, 21, 12); // calculating the length // of array A $n = sizeof($arr); // calling pendulum function pendulumArrangement($arr, $n); // This code is contributed by nitin mittal. ?> <script> // JavaScript program for pendulum // arrangement of numbers // Prints pendulam arrangement of arr[] function pendulumArrangement(arr, n) { // sorting the elements arr.sort(function (a, b) { return a - b; }); // Auxiliary array to store output var op = [...Array(n)]; // calculating the middle index var mid = parseInt((n - 1) / 2); // storing the minimum element in the middle // i is index for output array and j is for // input array. var j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid + i] = arr[j++]; op[mid - i] = arr[j++]; } // adjustment for when no. of elements is even if (n % 2 == 0) op[mid + i] = arr[j]; // Printing the pendulum arrangement document.write("Pendulum arrangement:<br>"); for (i = 0; i < n; i++) document.write(op[i] + " "); document.write("<br>"); } // Driver function //input Array var arr = [14, 6, 19, 21, 12]; // calculating the length of array A var n = arr.length; // calling pendulum function pendulumArrangement(arr, n); </script> Output: Pendulum arrangement: 21 14 6 12 19 Time Complexity: O(n*log(n)) where n is the size of the array.Auxiliary Space: O(n)This article is contributed by Nitin Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. nitin mittal rdtank clintra simmytarika5 pushpeshrajdx01 FactSet Arrays School Programming Sorting FactSet Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Python Dictionary Reverse a string in Java Introduction To PYTHON Interfaces in Java Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Jun, 2022" }, { "code": null, "e": 184, "s": 52, "text": "Write a program to input a list of integers in an array and arrange them in a way similar to the to-and-fro movement of a Pendulum." }, { "code": null, "e": 272, "s": 184, "text": "The minimum element out of the list of integers, must come in center position of array." }, { "code": null, "e": 422, "s": 272, "text": "The number in the ascending order next to the minimum, goes to the right, the next higher number goes to the left of minimum number and it continues." }, { "code": null, "e": 528, "s": 422, "text": "As higher numbers are reached, one goes to one side in a to-and-fro manner similar to that of a Pendulum." }, { "code": null, "e": 540, "s": 528, "text": "Examples: " }, { "code": null, "e": 903, "s": 540, "text": "Input : 1 3 2 5 4\nOutput :5 3 1 2 4\nExplanation: \nThe minimum element is 1, so it is moved to the middle.\nThe next higher element 2 is moved to the right of the \nmiddle element while the next higher element 3 is \nmoved to the left of the middle element and \nthis process is continued.\n\nInput : 11 12 31 14 5\nOutput :31 12 5 11 14" }, { "code": null, "e": 1020, "s": 903, "text": "The idea is to sort the array first. Once the array is sorted, use an auxiliary array to store elements one by one. " }, { "code": null, "e": 1024, "s": 1020, "text": "C++" }, { "code": null, "e": 1029, "s": 1024, "text": "Java" }, { "code": null, "e": 1037, "s": 1029, "text": "Python3" }, { "code": null, "e": 1040, "s": 1037, "text": "C#" }, { "code": null, "e": 1044, "s": 1040, "text": "PHP" }, { "code": null, "e": 1055, "s": 1044, "text": "Javascript" }, { "code": "// C++ program for pendulum arrangement of numbers#include <bits/stdc++.h>using namespace std; // Prints pendulum arrangement of arr[]void pendulumArrangement(int arr[], int n){ // sorting the elements sort(arr, arr+n); // Auxiliary array to store output int op[n]; // calculating the middle index int mid = (n-1)/2; // storing the minimum element in the middle // i is index for output array and j is for // input array. int j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid+i] = arr[j++]; op[mid-i] = arr[j++]; } // adjustment for when no. of elements is even if (n%2 == 0) op[mid+i] = arr[j]; // Printing the pendulum arrangement cout << \"Pendulum arrangement:\" << endl; for (i = 0 ; i < n; i++) cout << op[i] << \" \"; cout << endl;} // Driver functionint main(){ //input Array int arr[] = {14, 6, 19, 21, 12}; // calculating the length of array A int n = sizeof(arr)/sizeof(arr[0]); // calling pendulum function pendulumArrangement(arr, n); return 0;}", "e": 2159, "s": 1055, "text": null }, { "code": "// Java program for pendulum arrangement of numbers import java.util.Arrays; class Test{ // Prints pendulum arrangement of arr[] static void pendulumArrangement(int arr[], int n) { // sorting the elements Arrays.sort(arr); // Auxiliary array to store output int op[] = new int[n]; // calculating the middle index int mid = (n-1)/2; // storing the minimum element in the middle // i is index for output array and j is for // input array. int j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid+i] = arr[j++]; op[mid-i] = arr[j++]; } // adjustment for when no. of elements is even if (n%2 == 0) op[mid+i] = arr[j]; // Printing the pendulum arrangement System.out.println(\"Pendulum arrangement:\"); for (i = 0 ; i < n; i++) System.out.print(op[i] + \" \"); System.out.println(); } // Driver method public static void main(String[] args) { //input Array int arr[] = {14, 6, 19, 21, 12}; // calling pendulum function pendulumArrangement(arr, arr.length); }}", "e": 3428, "s": 2159, "text": null }, { "code": "# Python 3 program for pendulum# arrangement of numbers # Prints pendulum arrangement of arr[]def pendulumArrangement(arr, n): # sorting the elements arr.sort() # Auxiliary array to store output op = [0] * n # calculating the middle index mid = int((n-1)/2) # storing the minimum # element in the middle # i is index for output # array and j is for # input array. j = 1 i = 1 op[mid] = arr[0] for i in range(1,mid+1): op[mid+i] = arr[j] j+=1 op[mid-i] = arr[j] j+=1 # adjustment for when no. # of elements is even if (int(n%2) == 0): op[mid+i] = arr[j] # Printing the pendulum arrangement print(\"Pendulum arrangement:\") for i in range(0,n): print(op[i],end=\" \") # Driver function# input Arrayarr = [14, 6, 19, 21, 12] # calculating the length of array An = len(arr) # calling pendulum functionpendulumArrangement(arr, n) # This code is contributed by# Smitha Dinesh Semwal", "e": 4449, "s": 3428, "text": null }, { "code": "// C# program for pendulum // arrangement of numbersusing System; class Test { // Prints pendulum arrangement of arr[] static void pendulumArrangement(int []arr, int n) { // sorting the elements Array.Sort(arr); // Auxiliary array to store output int []op = new int[n]; // calculating the middle index int mid = (n - 1) / 2; // storing the minimum element in // the middle i is index for output // array and j is for input array. int j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid + i] = arr[j++]; op[mid - i] = arr[j++]; } // adjustment for when no. // of elements is even if (n % 2 == 0) op[mid + i] = arr[j]; // Printing the pendulum arrangement Console.Write(\"Pendulum arrangement:\"); for (i = 0 ; i < n; i++) Console.Write(op[i] + \" \"); Console.WriteLine(); } // Driver code public static void Main() { //input Array int []arr = {14, 6, 19, 21, 12}; // calling pendulum function pendulumArrangement(arr, arr.Length); }} // This code is contributed by Nitin Mittal.", "e": 5809, "s": 4449, "text": null }, { "code": "<?php// PHP program for pendulum // arrangement of numbers // Prints pendulam arrangement of arr[]function pendulumArrangement($arr, $n){ // sorting the elements sort($arr, $n); sort($arr); // Auxiliary array to // store output $op[$n] = NULL; // calculating the // middle index $mid = floor(($n - 1) / 2); // storing the minimum // element in the middle // i is index for output // array and j is for // input array. $j = 1; $i = 1; $op[$mid] = $arr[0]; for ($i = 1; $i <= $mid; $i++) { $op[$mid + $i] = $arr[$j++]; $op[$mid - $i] = $arr[$j++]; } // adjustment for when no. // of elements is even if ($n % 2 == 0) $op[$mid + $i] = $arr[$j]; // Printing the pendulum // arrangement echo \"Pendulum arrangement:\" ; for ($i = 0 ; $i < $n; $i++) echo $op[$i], \" \"; echo \"\\n\";} // Driver Code //input Array $arr = array(14, 6, 19, 21, 12); // calculating the length // of array A $n = sizeof($arr); // calling pendulum function pendulumArrangement($arr, $n); // This code is contributed by nitin mittal. ?>", "e": 6983, "s": 5809, "text": null }, { "code": "<script> // JavaScript program for pendulum // arrangement of numbers // Prints pendulam arrangement of arr[] function pendulumArrangement(arr, n) { // sorting the elements arr.sort(function (a, b) { return a - b; }); // Auxiliary array to store output var op = [...Array(n)]; // calculating the middle index var mid = parseInt((n - 1) / 2); // storing the minimum element in the middle // i is index for output array and j is for // input array. var j = 1, i = 1; op[mid] = arr[0]; for (i = 1; i <= mid; i++) { op[mid + i] = arr[j++]; op[mid - i] = arr[j++]; } // adjustment for when no. of elements is even if (n % 2 == 0) op[mid + i] = arr[j]; // Printing the pendulum arrangement document.write(\"Pendulum arrangement:<br>\"); for (i = 0; i < n; i++) document.write(op[i] + \" \"); document.write(\"<br>\"); } // Driver function //input Array var arr = [14, 6, 19, 21, 12]; // calculating the length of array A var n = arr.length; // calling pendulum function pendulumArrangement(arr, n); </script>", "e": 8285, "s": 6983, "text": null }, { "code": null, "e": 8294, "s": 8285, "text": "Output: " }, { "code": null, "e": 8330, "s": 8294, "text": "Pendulum arrangement:\n21 14 6 12 19" }, { "code": null, "e": 8835, "s": 8330, "text": "Time Complexity: O(n*log(n)) where n is the size of the array.Auxiliary Space: O(n)This article is contributed by Nitin Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8848, "s": 8835, "text": "nitin mittal" }, { "code": null, "e": 8855, "s": 8848, "text": "rdtank" }, { "code": null, "e": 8863, "s": 8855, "text": "clintra" }, { "code": null, "e": 8876, "s": 8863, "text": "simmytarika5" }, { "code": null, "e": 8892, "s": 8876, "text": "pushpeshrajdx01" }, { "code": null, "e": 8900, "s": 8892, "text": "FactSet" }, { "code": null, "e": 8907, "s": 8900, "text": "Arrays" }, { "code": null, "e": 8926, "s": 8907, "text": "School Programming" }, { "code": null, "e": 8934, "s": 8926, "text": "Sorting" }, { "code": null, "e": 8942, "s": 8934, "text": "FactSet" }, { "code": null, "e": 8949, "s": 8942, "text": "Arrays" }, { "code": null, "e": 8957, "s": 8949, "text": "Sorting" }, { "code": null, "e": 9055, "s": 8957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9087, "s": 9055, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9110, "s": 9087, "text": "Introduction to Arrays" }, { "code": null, "e": 9195, "s": 9110, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 9251, "s": 9195, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 9278, "s": 9251, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 9296, "s": 9278, "text": "Python Dictionary" }, { "code": null, "e": 9321, "s": 9296, "text": "Reverse a string in Java" }, { "code": null, "e": 9344, "s": 9321, "text": "Introduction To PYTHON" }, { "code": null, "e": 9363, "s": 9344, "text": "Interfaces in Java" } ]
Operating Systems | Set 16
24 Sep, 2021 Following questions have been asked in GATE CS 2005 exam. 1) Normally user programs are prevented from handling I/O directly by I/O instructions in them. For CPUs having explicit I/O instructions, such I/O protection is ensured by having the I/O instructions privileged. In a CPU with memory mapped I/O, there is no explicit I/O instruction. Which one of the following is true for a CPU with memory mapped I/O? (a) I/O protection is ensured by operating system routine(s) (b) I/O protection is ensured by a hardware trap (c) I/O protection is ensured during system configuration (d) I/O protection is not possible Answer (a) Memory mapped I/O means, accessing I/O via general memory access as opposed to specialized IO instructions. An example, unsigned int volatile const *pMappedAddress const = (unsigned int *)0x100; So, the programmer can directly access any memory location directly. To prevent such an access, the OS (kernel) will divide the address space into kernel space and user space. An user application can easily access user application. To access kernel space, we need system calls (traps). Thanks to Venki for providing the above explanation. 2) What is the swap space in the disk used for? (a) Saving temporary html pages (b) Saving process data (c) Storing the super-block (d) Storing device drivers Answer (b) Swap space is typically used to store process data. See this for more details. 3) Increasing the RAM of a computer typically improves performance because: (a) Virtual memory increases (b) Larger RAMs are faster (c) Fewer page faults occur (d) Fewer segmentation faults occur Answer (c) 4) Suppose n processes, P1, .... Pn share m identical resource units, which can be reserved and released one at a time. The maximum resource requirement of process Pi is Si, where Si > 0. Which one of the following is a sufficient condition for ensuring that deadlock does not occur? Answer (c) In the extreme condition, all processes acquire Si-1 resources and need 1 more resource. So following condition must be true to make sure that deadlock never occurs. < m The above expression can be written as following. < (m + n) 5) Consider the following code fragment: if (fork() == 0) { a = a + 5; printf(“%d,%d\n”, a, &a); } else { a = a –5; printf(“%d, %d\n”, a, &a); } Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (a) u = x + 10 and v = y (b) u = x + 10 and v != y (c) u + 10 = x and v = y (d) u + 10 = x and v != y Answer (c) fork() returns 0 in child process and process ID of child process in parent process. In Child (x), a = a + 5 In Parent (u), a = a – 5; Therefore x = u + 10. The physical addresses of ‘a’ in parent and child must be different. But our program accesses virtual addresses (assuming we are running on an OS that uses virtual memory). The child process gets an exact copy of parent process and virtual address of ‘a’ doesn’t change in child process. Therefore, we get same addresses in both parent and child. See this run for example. Thanks to Smart Pointer for providing the above explanation. Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. surinderdawra388 GATE-CS-2005 GATE CS MCQ Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Sep, 2021" }, { "code": null, "e": 111, "s": 52, "text": "Following questions have been asked in GATE CS 2005 exam. " }, { "code": null, "e": 668, "s": 111, "text": "1) Normally user programs are prevented from handling I/O directly by I/O instructions in them. For CPUs having explicit I/O instructions, such I/O protection is ensured by having the I/O instructions privileged. In a CPU with memory mapped I/O, there is no explicit I/O instruction. Which one of the following is true for a CPU with memory mapped I/O? (a) I/O protection is ensured by operating system routine(s) (b) I/O protection is ensured by a hardware trap (c) I/O protection is ensured during system configuration (d) I/O protection is not possible " }, { "code": null, "e": 801, "s": 668, "text": "Answer (a) Memory mapped I/O means, accessing I/O via general memory access as opposed to specialized IO instructions. An example, " }, { "code": null, "e": 878, "s": 801, "text": " unsigned int volatile const *pMappedAddress const = (unsigned int *)0x100;" }, { "code": null, "e": 1218, "s": 878, "text": "So, the programmer can directly access any memory location directly. To prevent such an access, the OS (kernel) will divide the address space into kernel space and user space. An user application can easily access user application. To access kernel space, we need system calls (traps). Thanks to Venki for providing the above explanation. " }, { "code": null, "e": 1378, "s": 1218, "text": "2) What is the swap space in the disk used for? (a) Saving temporary html pages (b) Saving process data (c) Storing the super-block (d) Storing device drivers " }, { "code": null, "e": 1469, "s": 1378, "text": "Answer (b) Swap space is typically used to store process data. See this for more details. " }, { "code": null, "e": 1666, "s": 1469, "text": "3) Increasing the RAM of a computer typically improves performance because: (a) Virtual memory increases (b) Larger RAMs are faster (c) Fewer page faults occur (d) Fewer segmentation faults occur " }, { "code": null, "e": 1678, "s": 1666, "text": "Answer (c) " }, { "code": null, "e": 1964, "s": 1678, "text": "4) Suppose n processes, P1, .... Pn share m identical resource units, which can be reserved and released one at a time. The maximum resource requirement of process Pi is Si, where Si > 0. Which one of the following is a sufficient condition for ensuring that deadlock does not occur? " }, { "code": null, "e": 2143, "s": 1964, "text": "Answer (c) In the extreme condition, all processes acquire Si-1 resources and need 1 more resource. So following condition must be true to make sure that deadlock never occurs. " }, { "code": null, "e": 2148, "s": 2143, "text": "< m " }, { "code": null, "e": 2200, "s": 2148, "text": "The above expression can be written as following. " }, { "code": null, "e": 2211, "s": 2200, "text": "< (m + n) " }, { "code": null, "e": 2254, "s": 2211, "text": "5) Consider the following code fragment: " }, { "code": null, "e": 2365, "s": 2254, "text": " if (fork() == 0)\n { a = a + 5; printf(“%d,%d\\n”, a, &a); }\n else { a = a –5; printf(“%d, %d\\n”, a, &a); } " }, { "code": null, "e": 2611, "s": 2365, "text": "Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE? (a) u = x + 10 and v = y (b) u = x + 10 and v != y (c) u + 10 = x and v = y (d) u + 10 = x and v != y " }, { "code": null, "e": 3214, "s": 2611, "text": "Answer (c) fork() returns 0 in child process and process ID of child process in parent process. In Child (x), a = a + 5 In Parent (u), a = a – 5; Therefore x = u + 10. The physical addresses of ‘a’ in parent and child must be different. But our program accesses virtual addresses (assuming we are running on an OS that uses virtual memory). The child process gets an exact copy of parent process and virtual address of ‘a’ doesn’t change in child process. Therefore, we get same addresses in both parent and child. See this run for example. Thanks to Smart Pointer for providing the above explanation. " }, { "code": null, "e": 3329, "s": 3214, "text": "Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc. " }, { "code": null, "e": 3479, "s": 3329, "text": "Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. " }, { "code": null, "e": 3496, "s": 3479, "text": "surinderdawra388" }, { "code": null, "e": 3509, "s": 3496, "text": "GATE-CS-2005" }, { "code": null, "e": 3517, "s": 3509, "text": "GATE CS" }, { "code": null, "e": 3521, "s": 3517, "text": "MCQ" }, { "code": null, "e": 3539, "s": 3521, "text": "Operating Systems" }, { "code": null, "e": 3557, "s": 3539, "text": "Operating Systems" } ]
Python | Binary list to integer
21 Feb, 2019 The problem being discussed in this article is quite common that every programmer would have come across it. Conversion of binary number list to its integer value can be done using shorthands and knowledge of them can prove to be quite useful. Let’s discuss certain ways in which this can be done. Method #1 : Using join() + list comprehensionThe combination of these two function can help to achieve this particular task. In this method, the entire list is first converted to string and then type conversion into int and then binary number is obtained. # Python3 code to demonstrate # converting binary list to integer # using join() + list comprehension # initializing list test_list = [1, 0, 0, 1, 1, 0] # printing original listprint ("The original list is : " + str(test_list)) # using join() + list comprehension# converting binary list to integer res = int("".join(str(x) for x in test_list), 2) # printing result print ("The converted integer value is : " + str(res)) Output : The original list is : [1, 0, 0, 1, 1, 0] The converted integer value is : 38 Method #2 : Using bit shift + | operatorThis particular task can be performed by shifting the bits and taking the | with each of the bits being processed. This is yet another elegant way in which this can be performed. # Python3 code to demonstrate # converting binary list to integer # using bit shift + | operator # initializing list test_list = [1, 0, 0, 1, 1, 0] # printing original listprint ("The original list is : " + str(test_list)) # using bit shift + | operator# converting binary list to integer res = 0for ele in test_list: res = (res << 1) | ele # printing result print ("The converted integer value is : " + str(res)) Output : The original list is : [1, 0, 0, 1, 1, 0] The converted integer value is : 38 Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2019" }, { "code": null, "e": 326, "s": 28, "text": "The problem being discussed in this article is quite common that every programmer would have come across it. Conversion of binary number list to its integer value can be done using shorthands and knowledge of them can prove to be quite useful. Let’s discuss certain ways in which this can be done." }, { "code": null, "e": 582, "s": 326, "text": "Method #1 : Using join() + list comprehensionThe combination of these two function can help to achieve this particular task. In this method, the entire list is first converted to string and then type conversion into int and then binary number is obtained." }, { "code": "# Python3 code to demonstrate # converting binary list to integer # using join() + list comprehension # initializing list test_list = [1, 0, 0, 1, 1, 0] # printing original listprint (\"The original list is : \" + str(test_list)) # using join() + list comprehension# converting binary list to integer res = int(\"\".join(str(x) for x in test_list), 2) # printing result print (\"The converted integer value is : \" + str(res))", "e": 1008, "s": 582, "text": null }, { "code": null, "e": 1017, "s": 1008, "text": "Output :" }, { "code": null, "e": 1096, "s": 1017, "text": "The original list is : [1, 0, 0, 1, 1, 0]\nThe converted integer value is : 38\n" }, { "code": null, "e": 1317, "s": 1098, "text": "Method #2 : Using bit shift + | operatorThis particular task can be performed by shifting the bits and taking the | with each of the bits being processed. This is yet another elegant way in which this can be performed." }, { "code": "# Python3 code to demonstrate # converting binary list to integer # using bit shift + | operator # initializing list test_list = [1, 0, 0, 1, 1, 0] # printing original listprint (\"The original list is : \" + str(test_list)) # using bit shift + | operator# converting binary list to integer res = 0for ele in test_list: res = (res << 1) | ele # printing result print (\"The converted integer value is : \" + str(res))", "e": 1739, "s": 1317, "text": null }, { "code": null, "e": 1748, "s": 1739, "text": "Output :" }, { "code": null, "e": 1827, "s": 1748, "text": "The original list is : [1, 0, 0, 1, 1, 0]\nThe converted integer value is : 38\n" }, { "code": null, "e": 1848, "s": 1827, "text": "Python list-programs" }, { "code": null, "e": 1860, "s": 1848, "text": "python-list" }, { "code": null, "e": 1867, "s": 1860, "text": "Python" }, { "code": null, "e": 1883, "s": 1867, "text": "Python Programs" }, { "code": null, "e": 1895, "s": 1883, "text": "python-list" }, { "code": null, "e": 1993, "s": 1895, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2011, "s": 1993, "text": "Python Dictionary" }, { "code": null, "e": 2053, "s": 2011, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2075, "s": 2053, "text": "Enumerate() in Python" }, { "code": null, "e": 2110, "s": 2075, "text": "Read a file line by line in Python" }, { "code": null, "e": 2136, "s": 2110, "text": "Python String | replace()" }, { "code": null, "e": 2179, "s": 2136, "text": "Python program to convert a list to string" }, { "code": null, "e": 2201, "s": 2179, "text": "Defaultdict in Python" }, { "code": null, "e": 2240, "s": 2201, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2278, "s": 2240, "text": "Python | Convert a list to dictionary" } ]
Julia Fractal set in C/C++ Using Graphics
02 Jan, 2020 The Julia set is associated with those points z = x + iy on the complex plane for which the series zn+1 = zn2 + c does not tend to infinity. c is a complex constant, one gets a different Julia set for each c. The initial value z0 for the series is each point in the image plane. The well known Mandelbrot set forms a kind of index into the Julia set. A Julia set is either connected or disconnected, values of c chosen from within the Mandelbrot set are connected while those from the outside of the Mandelbrot set are disconnected. The disconnected sets are often called “dust”, they consist of individual points no matter what resolution they are viewed at. #include <complex.h>#include <stdio.h>#include <tgmath.h>#include <winbgim.h> #define Y 1079#define X 1919 // To recursively find the end value// of the passed point till the pixel// goes out of the bounded region// or the maximum depth is reached.int julia_point(float x, float y, int r, int depth, int max, double _Complex c, double _Complex z){ if (cabs(z) > r) { putpixel(x, y, COLOR(255 - 255 * ((max - depth) * (max - depth)) % (max * max), 0, 0)); depth = 0; } if (sqrt(pow((x - X / 2), 2) + pow((y - Y / 2), 2)) > Y / 2) { putpixel(x, y, 0); } if (depth < max / 4) { return 0; } julia_point(x, y, r, depth - 1, max, c, cpow(z, 2) + c);} // To select the points in a Julia set.void juliaset(int depth, double _Complex c, int r, int detail){ for (float x = X / 2 - Y / 2; x < X / 2 + Y / 2; x += detail) { for (float y = 0; y < Y; y += detail) { julia_point(x, y, r, depth, depth, c, (2 * r * (x - X / 2) / Y) + (2 * r * (y - Y / 2) / Y) * _Complex_I); } }} // Driver codeint main(){ initwindow(X, Y); int depth = 100, r = 2, detail = 1; // Initial value for Julia // set taken by my personal preference. double _Complex c = 0.282 - 0.58 * _Complex_I; while (1) { cleardevice(); // To formulate the display text // for the 'c' coordinate // into string format. char str1[100], str2[100], strtemp[100]; if (floor(creal(c)) == -1) { strcpy(str1, "-0."); } if (floor(creal(c)) == -0) { strcpy(str1, "0."); } if (floor(cimag(c)) == -1) { strcpy(str2, "-0."); } if (floor(cimag(c)) == -0) { strcpy(str2, "0."); } itoa(sqrt(pow(creal(c), 2)) * 1000, strtemp, 10); strcat(str1, strtemp); strcat(str1, ", "); itoa(sqrt(pow(cimag(c), 2)) * 1000, strtemp, 10); strcat(str2, strtemp); strcat(str1, str2); outtextxy(X * 0.8, Y * 0.8, str1); // To call the julia-set for the selected value of 'c'. juliaset(depth, c, r, detail); outtextxy(X / 3, Y * 0.9, "Press '1' to Exit, Space to" " select a point or any " "other key to continue"); char key = getch(); if (key == '\n') { break; } // To select the value of 'c' // using the position of the mouse and then // normalizing it between a value of -1-1i and 1+1i. while (key == ' ') { c = 2 * (double)(mousex() - X / 2) / X + 2 * (mousey() - Y / 2) * _Complex_I / Y; if (floor(creal(c)) == -1) { strcpy(str1, "-0."); } if (floor(creal(c)) == -0) { strcpy(str1, "0."); } if (floor(cimag(c)) == -1) { strcpy(str2, "-0."); } if (floor(cimag(c)) == -0) { strcpy(str2, "0."); } itoa(sqrt(pow(creal(c), 2)) * 1000, strtemp, 10); strcat(str1, strtemp); strcat(str1, ", "); itoa(sqrt(pow(cimag(c), 2)) * 1000, strtemp, 10); strcat(str2, strtemp); strcat(str1, str2); outtextxy(X * 0.8, Y * 0.8, str1); if (kbhit()) { key = getch(); } } } closegraph(); return 0;} C Programs C++ Programs Geometric Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jan, 2020" }, { "code": null, "e": 333, "s": 54, "text": "The Julia set is associated with those points z = x + iy on the complex plane for which the series zn+1 = zn2 + c does not tend to infinity. c is a complex constant, one gets a different Julia set for each c. The initial value z0 for the series is each point in the image plane." }, { "code": null, "e": 714, "s": 333, "text": "The well known Mandelbrot set forms a kind of index into the Julia set. A Julia set is either connected or disconnected, values of c chosen from within the Mandelbrot set are connected while those from the outside of the Mandelbrot set are disconnected. The disconnected sets are often called “dust”, they consist of individual points no matter what resolution they are viewed at." }, { "code": "#include <complex.h>#include <stdio.h>#include <tgmath.h>#include <winbgim.h> #define Y 1079#define X 1919 // To recursively find the end value// of the passed point till the pixel// goes out of the bounded region// or the maximum depth is reached.int julia_point(float x, float y, int r, int depth, int max, double _Complex c, double _Complex z){ if (cabs(z) > r) { putpixel(x, y, COLOR(255 - 255 * ((max - depth) * (max - depth)) % (max * max), 0, 0)); depth = 0; } if (sqrt(pow((x - X / 2), 2) + pow((y - Y / 2), 2)) > Y / 2) { putpixel(x, y, 0); } if (depth < max / 4) { return 0; } julia_point(x, y, r, depth - 1, max, c, cpow(z, 2) + c);} // To select the points in a Julia set.void juliaset(int depth, double _Complex c, int r, int detail){ for (float x = X / 2 - Y / 2; x < X / 2 + Y / 2; x += detail) { for (float y = 0; y < Y; y += detail) { julia_point(x, y, r, depth, depth, c, (2 * r * (x - X / 2) / Y) + (2 * r * (y - Y / 2) / Y) * _Complex_I); } }} // Driver codeint main(){ initwindow(X, Y); int depth = 100, r = 2, detail = 1; // Initial value for Julia // set taken by my personal preference. double _Complex c = 0.282 - 0.58 * _Complex_I; while (1) { cleardevice(); // To formulate the display text // for the 'c' coordinate // into string format. char str1[100], str2[100], strtemp[100]; if (floor(creal(c)) == -1) { strcpy(str1, \"-0.\"); } if (floor(creal(c)) == -0) { strcpy(str1, \"0.\"); } if (floor(cimag(c)) == -1) { strcpy(str2, \"-0.\"); } if (floor(cimag(c)) == -0) { strcpy(str2, \"0.\"); } itoa(sqrt(pow(creal(c), 2)) * 1000, strtemp, 10); strcat(str1, strtemp); strcat(str1, \", \"); itoa(sqrt(pow(cimag(c), 2)) * 1000, strtemp, 10); strcat(str2, strtemp); strcat(str1, str2); outtextxy(X * 0.8, Y * 0.8, str1); // To call the julia-set for the selected value of 'c'. juliaset(depth, c, r, detail); outtextxy(X / 3, Y * 0.9, \"Press '1' to Exit, Space to\" \" select a point or any \" \"other key to continue\"); char key = getch(); if (key == '\\n') { break; } // To select the value of 'c' // using the position of the mouse and then // normalizing it between a value of -1-1i and 1+1i. while (key == ' ') { c = 2 * (double)(mousex() - X / 2) / X + 2 * (mousey() - Y / 2) * _Complex_I / Y; if (floor(creal(c)) == -1) { strcpy(str1, \"-0.\"); } if (floor(creal(c)) == -0) { strcpy(str1, \"0.\"); } if (floor(cimag(c)) == -1) { strcpy(str2, \"-0.\"); } if (floor(cimag(c)) == -0) { strcpy(str2, \"0.\"); } itoa(sqrt(pow(creal(c), 2)) * 1000, strtemp, 10); strcat(str1, strtemp); strcat(str1, \", \"); itoa(sqrt(pow(cimag(c), 2)) * 1000, strtemp, 10); strcat(str2, strtemp); strcat(str1, str2); outtextxy(X * 0.8, Y * 0.8, str1); if (kbhit()) { key = getch(); } } } closegraph(); return 0;}", "e": 4466, "s": 714, "text": null }, { "code": null, "e": 4477, "s": 4466, "text": "C Programs" }, { "code": null, "e": 4490, "s": 4477, "text": "C++ Programs" }, { "code": null, "e": 4500, "s": 4490, "text": "Geometric" }, { "code": null, "e": 4510, "s": 4500, "text": "Geometric" } ]
Recursive Program to print multiplication table of a number - GeeksforGeeks
05 Apr, 2021 Given a number N, the task is to print its multiplication table using recursion. Examples Input: N = 5 Output: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50Input: N = 8 Output: 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80 Recursive approach to print multiplication table of a number Approach: Get the number for which multiplication table is to print.Recursively iterate from value 1 to 10: Base case: If the value called recursively is greater than 10, exit from the function. Get the number for which multiplication table is to print. Recursively iterate from value 1 to 10: Base case: If the value called recursively is greater than 10, exit from the function. Base case: If the value called recursively is greater than 10, exit from the function. if(i > N) return ; Recursive call: If the base case is not met, then print its multiplication table for that value and then call the function for next iteration. print("N*i = ", N*i) recursive_function(N, i+1); Return statement: At each recursive call(except the base case), return the recursive function for next iteration. return recursive_function(N, i+1); Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to print table// of a number using recursion#include <iostream>using namespace std; // Function that print the// table of a given number// using recursionvoid mul_table(int N, int i){ // Base Case if (i > 10) return; // Print the table for // current iteration cout << N << " * " << i << " = " << N * i << endl; // Recursive call to next // iteration return mul_table(N, i + 1);} // Driver Codeint main(){ // Input number whose table // is to print int N = 8; // Function call to print // the table mul_table(N, 1); return 0;} // Java program to print table// of a number using recursionclass GFG { // Function that print the // table of a given number // using recursion static void mul_table(int N, int i) { // Base Case if (i > 10) return ; // Print the table for // current iteration System.out.println(N + " * " + i + " = " + N * i); // Recursive call to next // iteration mul_table(N, i + 1); } // Driver Code public static void main (String[] args) { // Input number whose table // is to print int N = 8; // Function call to print // the table mul_table(N, 1); }} // This code is contributed by AnkitRai01 # Python3 program to print table# of a number using recursion # Function that print the# table of a given number# using recursiondef mul_table(N, i): # Base Case if (i > 10): return # Print the table for # current iteration print(N,"*",i,"=",N * i) # Recursive call to next # iteration return mul_table(N, i + 1) # Driver Code # Input number whose table# is to printN = 8 # Function call to print# the tablemul_table(N, 1) # This is contributed by shubhamsingh10 // C# program to print table// of a number using recursionusing System; class GFG{ // Function that print the // table of a given number // using recursion static void mul_table(int N, int i) { // Base Case if (i > 10) return ; // Print the table for // current iteration Console.WriteLine(N + " * " + i + " = " + N * i); // Recursive call to next // iteration mul_table(N, i + 1); } // Driver Code public static void Main() { // Input number whose table // is to print int N = 8; // Function call to print // the table mul_table(N, 1); }} // This code is contributed by AnkitRai01 <script> // Javascript program to print table// of a number using recursion // Function that print the// table of a given number// using recursionfunction mul_table(N, i){ // Base Case if (i > 10) return; // Print the table for // current iteration document.write(N + " * " + i + " = " + N * i + "<br>"); // Recursive call to next // iteration return mul_table(N, i + 1);} // Driver Code // Input number whose table// is to printvar N = 8; // Function call to print// the tablemul_table(N, 1); </script> 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80 Time Complexity: O(1) SHUBHAMSINGH10 ankthon Code_Mech rrrtnx Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Print all possible combinations of r elements in a given array of size n
[ { "code": null, "e": 27151, "s": 27123, "text": "\n05 Apr, 2021" }, { "code": null, "e": 27243, "s": 27151, "text": "Given a number N, the task is to print its multiplication table using recursion. Examples " }, { "code": null, "e": 27506, "s": 27243, "text": "Input: N = 5 Output: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50Input: N = 8 Output: 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 8 * 10 = 80 " }, { "code": null, "e": 27571, "s": 27510, "text": "Recursive approach to print multiplication table of a number" }, { "code": null, "e": 27583, "s": 27571, "text": "Approach: " }, { "code": null, "e": 27770, "s": 27583, "text": "Get the number for which multiplication table is to print.Recursively iterate from value 1 to 10: Base case: If the value called recursively is greater than 10, exit from the function. " }, { "code": null, "e": 27829, "s": 27770, "text": "Get the number for which multiplication table is to print." }, { "code": null, "e": 27958, "s": 27829, "text": "Recursively iterate from value 1 to 10: Base case: If the value called recursively is greater than 10, exit from the function. " }, { "code": null, "e": 28047, "s": 27958, "text": "Base case: If the value called recursively is greater than 10, exit from the function. " }, { "code": null, "e": 28069, "s": 28047, "text": "if(i > N) \n return ;" }, { "code": null, "e": 28216, "s": 28071, "text": "Recursive call: If the base case is not met, then print its multiplication table for that value and then call the function for next iteration. " }, { "code": null, "e": 28265, "s": 28216, "text": "print(\"N*i = \", N*i)\nrecursive_function(N, i+1);" }, { "code": null, "e": 28383, "s": 28267, "text": "Return statement: At each recursive call(except the base case), return the recursive function for next iteration. " }, { "code": null, "e": 28418, "s": 28383, "text": "return recursive_function(N, i+1);" }, { "code": null, "e": 28472, "s": 28420, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 28476, "s": 28472, "text": "C++" }, { "code": null, "e": 28481, "s": 28476, "text": "Java" }, { "code": null, "e": 28489, "s": 28481, "text": "Python3" }, { "code": null, "e": 28492, "s": 28489, "text": "C#" }, { "code": null, "e": 28503, "s": 28492, "text": "Javascript" }, { "code": "// C++ program to print table// of a number using recursion#include <iostream>using namespace std; // Function that print the// table of a given number// using recursionvoid mul_table(int N, int i){ // Base Case if (i > 10) return; // Print the table for // current iteration cout << N << \" * \" << i << \" = \" << N * i << endl; // Recursive call to next // iteration return mul_table(N, i + 1);} // Driver Codeint main(){ // Input number whose table // is to print int N = 8; // Function call to print // the table mul_table(N, 1); return 0;}", "e": 29116, "s": 28503, "text": null }, { "code": "// Java program to print table// of a number using recursionclass GFG { // Function that print the // table of a given number // using recursion static void mul_table(int N, int i) { // Base Case if (i > 10) return ; // Print the table for // current iteration System.out.println(N + \" * \" + i + \" = \" + N * i); // Recursive call to next // iteration mul_table(N, i + 1); } // Driver Code public static void main (String[] args) { // Input number whose table // is to print int N = 8; // Function call to print // the table mul_table(N, 1); }} // This code is contributed by AnkitRai01", "e": 29877, "s": 29116, "text": null }, { "code": "# Python3 program to print table# of a number using recursion # Function that print the# table of a given number# using recursiondef mul_table(N, i): # Base Case if (i > 10): return # Print the table for # current iteration print(N,\"*\",i,\"=\",N * i) # Recursive call to next # iteration return mul_table(N, i + 1) # Driver Code # Input number whose table# is to printN = 8 # Function call to print# the tablemul_table(N, 1) # This is contributed by shubhamsingh10", "e": 30386, "s": 29877, "text": null }, { "code": "// C# program to print table// of a number using recursionusing System; class GFG{ // Function that print the // table of a given number // using recursion static void mul_table(int N, int i) { // Base Case if (i > 10) return ; // Print the table for // current iteration Console.WriteLine(N + \" * \" + i + \" = \" + N * i); // Recursive call to next // iteration mul_table(N, i + 1); } // Driver Code public static void Main() { // Input number whose table // is to print int N = 8; // Function call to print // the table mul_table(N, 1); }} // This code is contributed by AnkitRai01", "e": 31143, "s": 30386, "text": null }, { "code": "<script> // Javascript program to print table// of a number using recursion // Function that print the// table of a given number// using recursionfunction mul_table(N, i){ // Base Case if (i > 10) return; // Print the table for // current iteration document.write(N + \" * \" + i + \" = \" + N * i + \"<br>\"); // Recursive call to next // iteration return mul_table(N, i + 1);} // Driver Code // Input number whose table// is to printvar N = 8; // Function call to print// the tablemul_table(N, 1); </script>", "e": 31696, "s": 31143, "text": null }, { "code": null, "e": 31806, "s": 31696, "text": "8 * 1 = 8\n8 * 2 = 16\n8 * 3 = 24\n8 * 4 = 32\n8 * 5 = 40\n8 * 6 = 48\n8 * 7 = 56\n8 * 8 = 64\n8 * 9 = 72\n8 * 10 = 80" }, { "code": null, "e": 31831, "s": 31808, "text": "Time Complexity: O(1) " }, { "code": null, "e": 31846, "s": 31831, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 31854, "s": 31846, "text": "ankthon" }, { "code": null, "e": 31864, "s": 31854, "text": "Code_Mech" }, { "code": null, "e": 31871, "s": 31864, "text": "rrrtnx" }, { "code": null, "e": 31884, "s": 31871, "text": "Mathematical" }, { "code": null, "e": 31894, "s": 31884, "text": "Recursion" }, { "code": null, "e": 31907, "s": 31894, "text": "Mathematical" }, { "code": null, "e": 31917, "s": 31907, "text": "Recursion" }, { "code": null, "e": 32015, "s": 31917, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32039, "s": 32015, "text": "Merge two sorted arrays" }, { "code": null, "e": 32082, "s": 32039, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 32096, "s": 32082, "text": "Prime Numbers" }, { "code": null, "e": 32138, "s": 32096, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 32211, "s": 32138, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 32296, "s": 32211, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 32306, "s": 32296, "text": "Recursion" }, { "code": null, "e": 32333, "s": 32306, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 32361, "s": 32333, "text": "Backtracking | Introduction" } ]
React-Bootstrap OverlayTrigger Component - GeeksforGeeks
04 May, 2021 React-Bootstrap is a front-end framework that was designed keeping react in mind. OverlayTrigger Component helps with common use-cases into our Overlay components. It positions itself with the help of ref and style prop for our overlay component. We can use the following approach in ReactJS to use the react-bootstrap OverlayTrigger Component. OverlayTrigger Props: children: It is used to indicate the children’s attribute for an overlay. defaultShow: It is used to indicate the initial visible state of an overlay. delay: It is used to indicate delay time for an overlay to show and hide once it is triggered. flip: It is used to indicate the initial flip state of an overlay. onHide: It is used to indicate the on hiding property of an overlay. onToggle: It is a callback function that is triggered when the user changes the visibility of tooltip. overlay: It is text to or an element overlay that is next to the target. placement: It is used to set the positioned direction of the overlay. popperConfig: It is a config object of Popper.js which is passed to the underlying instance of popper. show: It indicates the visibility of the overlay. target: It is the target attribute used when a target needs to be set for an overlay. trigger: It is used to specify which actions trigger action or overlay visibility. Overlay Props: children: It is used to indicate the children’s attribute for an overlay. container: It is basically a component instance or a function that returns either or a DOM node. onEnter: It is a callback function that is triggered before overlay transitions in. onEntered: It is a callback function that is triggered after overlay finishes transitioning in. onEntering: It is a callback function that is triggered as overlay begins to transition in. onExit: It is a callback function that is triggered right before overlay transitions out. onExited: It is a callback function that is triggered after overlay finishes transitioning out. onExiting: It is a callback function that is triggered as overlay begins to transition out. onHide: It is used to indicate the on hiding property of an overlay. placement: It is used to set the positioned direction of the overlay. popperConfig: It is a config object of Popper.js which is passed to the underlying instance of popper. rootClose: It is used to specify whether to call the onHide function when the user clicks outside the overlay. rootCloseEvent: It is used to close the component when an event is fired outside it. show: It indicates the visibility of the overlay. target: It is the target attribute used when a target needs to be set for an overlay. transition: It is used for the animation of the entering and exiting of the Overlay. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap npm install bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install react-bootstrap npm install bootstrap 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 React from 'react';import 'bootstrap/dist/css/bootstrap.css';import OverlayTrigger from 'react-bootstrap/OverlayTrigger';import Popover from 'react-bootstrap/Popover'import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap OverlayTrigger Component</h4> <OverlayTrigger placement="bottom" trigger="click" overlay={( <Popover> <Popover.Title as="h3"> Hello User </Popover.Title> </Popover> )}> <Button variant="primary"> OverlayTrigger Button </Button> </OverlayTrigger> </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://react-bootstrap.github.io/components/overlays/#overlay-trigger-props React-Bootstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook Axios in React: A Guide for Beginners How to set background images in ReactJS ? How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26181, "s": 26153, "text": "\n04 May, 2021" }, { "code": null, "e": 26526, "s": 26181, "text": "React-Bootstrap is a front-end framework that was designed keeping react in mind. OverlayTrigger Component helps with common use-cases into our Overlay components. It positions itself with the help of ref and style prop for our overlay component. We can use the following approach in ReactJS to use the react-bootstrap OverlayTrigger Component." }, { "code": null, "e": 26548, "s": 26526, "text": "OverlayTrigger Props:" }, { "code": null, "e": 26622, "s": 26548, "text": "children: It is used to indicate the children’s attribute for an overlay." }, { "code": null, "e": 26699, "s": 26622, "text": "defaultShow: It is used to indicate the initial visible state of an overlay." }, { "code": null, "e": 26794, "s": 26699, "text": "delay: It is used to indicate delay time for an overlay to show and hide once it is triggered." }, { "code": null, "e": 26861, "s": 26794, "text": "flip: It is used to indicate the initial flip state of an overlay." }, { "code": null, "e": 26930, "s": 26861, "text": "onHide: It is used to indicate the on hiding property of an overlay." }, { "code": null, "e": 27033, "s": 26930, "text": "onToggle: It is a callback function that is triggered when the user changes the visibility of tooltip." }, { "code": null, "e": 27106, "s": 27033, "text": "overlay: It is text to or an element overlay that is next to the target." }, { "code": null, "e": 27176, "s": 27106, "text": "placement: It is used to set the positioned direction of the overlay." }, { "code": null, "e": 27279, "s": 27176, "text": "popperConfig: It is a config object of Popper.js which is passed to the underlying instance of popper." }, { "code": null, "e": 27329, "s": 27279, "text": "show: It indicates the visibility of the overlay." }, { "code": null, "e": 27415, "s": 27329, "text": "target: It is the target attribute used when a target needs to be set for an overlay." }, { "code": null, "e": 27498, "s": 27415, "text": "trigger: It is used to specify which actions trigger action or overlay visibility." }, { "code": null, "e": 27513, "s": 27498, "text": "Overlay Props:" }, { "code": null, "e": 27587, "s": 27513, "text": "children: It is used to indicate the children’s attribute for an overlay." }, { "code": null, "e": 27684, "s": 27587, "text": "container: It is basically a component instance or a function that returns either or a DOM node." }, { "code": null, "e": 27768, "s": 27684, "text": "onEnter: It is a callback function that is triggered before overlay transitions in." }, { "code": null, "e": 27864, "s": 27768, "text": "onEntered: It is a callback function that is triggered after overlay finishes transitioning in." }, { "code": null, "e": 27956, "s": 27864, "text": "onEntering: It is a callback function that is triggered as overlay begins to transition in." }, { "code": null, "e": 28046, "s": 27956, "text": "onExit: It is a callback function that is triggered right before overlay transitions out." }, { "code": null, "e": 28142, "s": 28046, "text": "onExited: It is a callback function that is triggered after overlay finishes transitioning out." }, { "code": null, "e": 28234, "s": 28142, "text": "onExiting: It is a callback function that is triggered as overlay begins to transition out." }, { "code": null, "e": 28303, "s": 28234, "text": "onHide: It is used to indicate the on hiding property of an overlay." }, { "code": null, "e": 28373, "s": 28303, "text": "placement: It is used to set the positioned direction of the overlay." }, { "code": null, "e": 28476, "s": 28373, "text": "popperConfig: It is a config object of Popper.js which is passed to the underlying instance of popper." }, { "code": null, "e": 28587, "s": 28476, "text": "rootClose: It is used to specify whether to call the onHide function when the user clicks outside the overlay." }, { "code": null, "e": 28672, "s": 28587, "text": "rootCloseEvent: It is used to close the component when an event is fired outside it." }, { "code": null, "e": 28722, "s": 28672, "text": "show: It indicates the visibility of the overlay." }, { "code": null, "e": 28808, "s": 28722, "text": "target: It is the target attribute used when a target needs to be set for an overlay." }, { "code": null, "e": 28893, "s": 28808, "text": "transition: It is used for the animation of the entering and exiting of the Overlay." }, { "code": null, "e": 28943, "s": 28893, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 29038, "s": 28943, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 29102, "s": 29038, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 29134, "s": 29102, "text": "npx create-react-app foldername" }, { "code": null, "e": 29247, "s": 29134, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 29347, "s": 29247, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 29361, "s": 29347, "text": "cd foldername" }, { "code": null, "e": 29516, "s": 29361, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 29621, "s": 29516, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 29672, "s": 29621, "text": "npm install react-bootstrap \nnpm install bootstrap" }, { "code": null, "e": 29724, "s": 29672, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 29742, "s": 29724, "text": "Project Structure" }, { "code": null, "e": 29872, "s": 29742, "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": 29879, "s": 29872, "text": "App.js" }, { "code": "import React from 'react';import 'bootstrap/dist/css/bootstrap.css';import OverlayTrigger from 'react-bootstrap/OverlayTrigger';import Popover from 'react-bootstrap/Popover'import Button from 'react-bootstrap/Button'; export default function App() { return ( <div style={{ display: 'block', width: 700, padding: 30 }}> <h4>React-Bootstrap OverlayTrigger Component</h4> <OverlayTrigger placement=\"bottom\" trigger=\"click\" overlay={( <Popover> <Popover.Title as=\"h3\"> Hello User </Popover.Title> </Popover> )}> <Button variant=\"primary\"> OverlayTrigger Button </Button> </OverlayTrigger> </div> );}", "e": 30605, "s": 29879, "text": null }, { "code": null, "e": 30718, "s": 30605, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 30728, "s": 30718, "text": "npm start" }, { "code": null, "e": 30827, "s": 30728, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 30915, "s": 30827, "text": "Reference: https://react-bootstrap.github.io/components/overlays/#overlay-trigger-props" }, { "code": null, "e": 30931, "s": 30915, "text": "React-Bootstrap" }, { "code": null, "e": 30939, "s": 30931, "text": "ReactJS" }, { "code": null, "e": 30956, "s": 30939, "text": "Web Technologies" }, { "code": null, "e": 31054, "s": 30956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31081, "s": 31054, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 31119, "s": 31081, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 31161, "s": 31119, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 31196, "s": 31161, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 31254, "s": 31196, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 31294, "s": 31254, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31327, "s": 31294, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31372, "s": 31327, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31422, "s": 31372, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Convert Decimal to String in Python - GeeksforGeeks
28 Jul, 2020 Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting decimal to string. str() method can be used to convert decimal to string in Python. Syntax: str(object, encoding=’utf-8?, errors=’strict’) Parameters: object: The object whose string representation is to be returned. encoding: Encoding of the given object. errors: Response when decoding fails. Example 1: Python3 from decimal import Decimal dec = Decimal(10)print(dec, type(dec)) # Converting to stringdec = str(dec)print(dec, type(dec)) Output: 10 <class 'decimal.Decimal'> 10 <class 'str'> Example 2: Python3 from decimal import Decimal dec = Decimal("0.01")print(dec, type(dec)) # Converting decimal to strings = str(dec)print(s, type(dec)) Output: 0.01 <class 'decimal.Decimal'> 0.01 <class 'decimal.Decimal'> python-basics python-string Python 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Defaultdict in Python Python OOPs Concepts Python | os.path.join() method Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24317, "s": 24289, "text": "\n28 Jul, 2020" }, { "code": null, "e": 24491, "s": 24317, "text": "Python defines type conversion functions to directly convert one data type to another. This article is aimed at providing the information about converting decimal to string." }, { "code": null, "e": 24556, "s": 24491, "text": "str() method can be used to convert decimal to string in Python." }, { "code": null, "e": 24611, "s": 24556, "text": "Syntax: str(object, encoding=’utf-8?, errors=’strict’)" }, { "code": null, "e": 24623, "s": 24611, "text": "Parameters:" }, { "code": null, "e": 24689, "s": 24623, "text": "object: The object whose string representation is to be returned." }, { "code": null, "e": 24729, "s": 24689, "text": "encoding: Encoding of the given object." }, { "code": null, "e": 24767, "s": 24729, "text": "errors: Response when decoding fails." }, { "code": null, "e": 24778, "s": 24767, "text": "Example 1:" }, { "code": null, "e": 24786, "s": 24778, "text": "Python3" }, { "code": "from decimal import Decimal dec = Decimal(10)print(dec, type(dec)) # Converting to stringdec = str(dec)print(dec, type(dec))", "e": 24913, "s": 24786, "text": null }, { "code": null, "e": 24921, "s": 24913, "text": "Output:" }, { "code": null, "e": 24967, "s": 24921, "text": "10 <class 'decimal.Decimal'>\n10 <class 'str'>" }, { "code": null, "e": 24978, "s": 24967, "text": "Example 2:" }, { "code": null, "e": 24986, "s": 24978, "text": "Python3" }, { "code": "from decimal import Decimal dec = Decimal(\"0.01\")print(dec, type(dec)) # Converting decimal to strings = str(dec)print(s, type(dec))", "e": 25123, "s": 24986, "text": null }, { "code": null, "e": 25131, "s": 25123, "text": "Output:" }, { "code": null, "e": 25193, "s": 25131, "text": "0.01 <class 'decimal.Decimal'>\n0.01 <class 'decimal.Decimal'>" }, { "code": null, "e": 25207, "s": 25193, "text": "python-basics" }, { "code": null, "e": 25221, "s": 25207, "text": "python-string" }, { "code": null, "e": 25228, "s": 25221, "text": "Python" }, { "code": null, "e": 25326, "s": 25228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25335, "s": 25326, "text": "Comments" }, { "code": null, "e": 25348, "s": 25335, "text": "Old Comments" }, { "code": null, "e": 25380, "s": 25348, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25435, "s": 25380, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 25491, "s": 25435, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25533, "s": 25491, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25575, "s": 25533, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25614, "s": 25575, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25636, "s": 25614, "text": "Defaultdict in Python" }, { "code": null, "e": 25657, "s": 25636, "text": "Python OOPs Concepts" }, { "code": null, "e": 25688, "s": 25657, "text": "Python | os.path.join() method" } ]