title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
anacron command in linux with examples - GeeksforGeeks
12 Oct, 2021 anacron command is used to execute commands periodically with a frequency specified in days. Its main advantage over cron is that it can be used on a machine which is not running continuously. In cron if a machine is not running on time of a scheduled job then it will skip it, but anacron is a bit different as it first checks for timestamp of the job then decides whether to run it or not and if its timestamp is >=n(n is defined number of days) then runs it after a specified time delay. It mainly constitutes of two important Files: /etc/anacrontab : It contains specifications of job.See line SHELL=/bin/sh. It uses sh not bash you cannot run bash scripts.Table at the last represents different scheduling. The first column is the number of days(n) i.e. period and second is a time delay in minutes./var/spool/anacron : This directory is used by Anacron for storing timestamp files. It represents timestamp for different catetgory of jobs i.e. daily, weekly, monthly, etc. /etc/anacrontab : It contains specifications of job.See line SHELL=/bin/sh. It uses sh not bash you cannot run bash scripts.Table at the last represents different scheduling. The first column is the number of days(n) i.e. period and second is a time delay in minutes. See line SHELL=/bin/sh. It uses sh not bash you cannot run bash scripts. Table at the last represents different scheduling. The first column is the number of days(n) i.e. period and second is a time delay in minutes. /var/spool/anacron : This directory is used by Anacron for storing timestamp files. It represents timestamp for different catetgory of jobs i.e. daily, weekly, monthly, etc. Syntax: anacron [-s] [-f] [-n] [-d] [-q] [-t anacrontab] [-S spooldir] [job] anacron [-S spooldir] -u [-t anacrontab] [job] ... anacron [-V|-h] anacron -T [-t anacrontab] Options: f : Used to force execution of the jobs, ignoring the timestamps. u : Only update the timestamps of the jobs, to the current date, but don’t run anything. s : Serialize execution of jobs. Anacron will not start a new job before the previous one finished. n : Run jobs now.Ignore any delay. d : Don’t fork to the background. In this mode, Anacron will output informational messages to standard error, as well as to syslog. The output of jobs is mailed as usual. q : Suppress messages to standard error. Only applicable with -d. V (Use specified anacrontab) : Print version information and exit. h (Use specified anacrontab) : Print short usage message, and exit. Note: You can add any script to etc/cron.daily or etc/cron.weekly or cron.monthly directory.but remember script should be sh not bash. Don’t forget to give executable permissions to your files sudo chmod +x filename. Scripts in directories automatically get executed depending upon which directory they are in. Examples: Changing the timestamp of jobs. Observe the change in timestamp values. Performing force execution. Notice the time delay. Serialized Execution. Print version information. Print sort Usage message. Note: Here we have used -d option with all commands to display on the screen what is actually happening. anikakapoor linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments tar command in Linux with examples UDP Server-Client implementation in C Conditional Statements | Shell Script echo command in Linux with Examples Cat command in Linux with examples Mutex lock for Linux Thread Synchronization touch command in Linux with Examples Tail command in Linux with examples tee command in Linux with examples Compiling with g++
[ { "code": null, "e": 23956, "s": 23928, "text": "\n12 Oct, 2021" }, { "code": null, "e": 24447, "s": 23956, "text": "anacron command is used to execute commands periodically with a frequency specified in days. Its main advantage over cron is that it can be used on a machine which is not running continuously. In cron if a machine is not running on time of a scheduled job then it will skip it, but anacron is a bit different as it first checks for timestamp of the job then decides whether to run it or not and if its timestamp is >=n(n is defined number of days) then runs it after a specified time delay." }, { "code": null, "e": 24493, "s": 24447, "text": "It mainly constitutes of two important Files:" }, { "code": null, "e": 24934, "s": 24493, "text": "/etc/anacrontab : It contains specifications of job.See line SHELL=/bin/sh. It uses sh not bash you cannot run bash scripts.Table at the last represents different scheduling. The first column is the number of days(n) i.e. period and second is a time delay in minutes./var/spool/anacron : This directory is used by Anacron for storing timestamp files. It represents timestamp for different catetgory of jobs i.e. daily, weekly, monthly, etc." }, { "code": null, "e": 25202, "s": 24934, "text": "/etc/anacrontab : It contains specifications of job.See line SHELL=/bin/sh. It uses sh not bash you cannot run bash scripts.Table at the last represents different scheduling. The first column is the number of days(n) i.e. period and second is a time delay in minutes." }, { "code": null, "e": 25275, "s": 25202, "text": "See line SHELL=/bin/sh. It uses sh not bash you cannot run bash scripts." }, { "code": null, "e": 25419, "s": 25275, "text": "Table at the last represents different scheduling. The first column is the number of days(n) i.e. period and second is a time delay in minutes." }, { "code": null, "e": 25593, "s": 25419, "text": "/var/spool/anacron : This directory is used by Anacron for storing timestamp files. It represents timestamp for different catetgory of jobs i.e. daily, weekly, monthly, etc." }, { "code": null, "e": 25601, "s": 25593, "text": "Syntax:" }, { "code": null, "e": 25769, "s": 25601, "text": "anacron [-s] [-f] [-n] [-d] [-q] [-t anacrontab] [-S spooldir] [job]\nanacron [-S spooldir] -u [-t anacrontab] [job] ...\n anacron [-V|-h]\n anacron -T [-t anacrontab]\n" }, { "code": null, "e": 25778, "s": 25769, "text": "Options:" }, { "code": null, "e": 25844, "s": 25778, "text": "f : Used to force execution of the jobs, ignoring the timestamps." }, { "code": null, "e": 25933, "s": 25844, "text": "u : Only update the timestamps of the jobs, to the current date, but don’t run anything." }, { "code": null, "e": 26033, "s": 25933, "text": "s : Serialize execution of jobs. Anacron will not start a new job before the previous one finished." }, { "code": null, "e": 26068, "s": 26033, "text": "n : Run jobs now.Ignore any delay." }, { "code": null, "e": 26239, "s": 26068, "text": "d : Don’t fork to the background. In this mode, Anacron will output informational messages to standard error, as well as to syslog. The output of jobs is mailed as usual." }, { "code": null, "e": 26305, "s": 26239, "text": "q : Suppress messages to standard error. Only applicable with -d." }, { "code": null, "e": 26372, "s": 26305, "text": "V (Use specified anacrontab) : Print version information and exit." }, { "code": null, "e": 26440, "s": 26372, "text": "h (Use specified anacrontab) : Print short usage message, and exit." }, { "code": null, "e": 26446, "s": 26440, "text": "Note:" }, { "code": null, "e": 26575, "s": 26446, "text": "You can add any script to etc/cron.daily or etc/cron.weekly or cron.monthly directory.but remember script should be sh not bash." }, { "code": null, "e": 26657, "s": 26575, "text": "Don’t forget to give executable permissions to your files sudo chmod +x filename." }, { "code": null, "e": 26751, "s": 26657, "text": "Scripts in directories automatically get executed depending upon which directory they are in." }, { "code": null, "e": 26761, "s": 26751, "text": "Examples:" }, { "code": null, "e": 26833, "s": 26761, "text": "Changing the timestamp of jobs. Observe the change in timestamp values." }, { "code": null, "e": 26884, "s": 26833, "text": "Performing force execution. Notice the time delay." }, { "code": null, "e": 26906, "s": 26884, "text": "Serialized Execution." }, { "code": null, "e": 26933, "s": 26906, "text": "Print version information." }, { "code": null, "e": 26959, "s": 26933, "text": "Print sort Usage message." }, { "code": null, "e": 27064, "s": 26959, "text": "Note: Here we have used -d option with all commands to display on the screen what is actually happening." }, { "code": null, "e": 27076, "s": 27064, "text": "anikakapoor" }, { "code": null, "e": 27090, "s": 27076, "text": "linux-command" }, { "code": null, "e": 27097, "s": 27090, "text": "Picked" }, { "code": null, "e": 27108, "s": 27097, "text": "Linux-Unix" }, { "code": null, "e": 27206, "s": 27108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27215, "s": 27206, "text": "Comments" }, { "code": null, "e": 27228, "s": 27215, "text": "Old Comments" }, { "code": null, "e": 27263, "s": 27228, "text": "tar command in Linux with examples" }, { "code": null, "e": 27301, "s": 27263, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27339, "s": 27301, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27375, "s": 27339, "text": "echo command in Linux with Examples" }, { "code": null, "e": 27410, "s": 27375, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27454, "s": 27410, "text": "Mutex lock for Linux Thread Synchronization" }, { "code": null, "e": 27491, "s": 27454, "text": "touch command in Linux with Examples" }, { "code": null, "e": 27527, "s": 27491, "text": "Tail command in Linux with examples" }, { "code": null, "e": 27562, "s": 27527, "text": "tee command in Linux with examples" } ]
How will you show memory representation of C variables? - GeeksforGeeks
18 Feb, 2022 Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer. Program: c #include <stdio.h>typedef unsigned char *byte_pointer; /*show bytes takes byte pointer as an argument and prints memory contents from byte_pointer to byte_pointer + len */void show_bytes(byte_pointer start, int len){ int i; for (i = 0; i < len; i++) printf(" %.2x", start[i]); printf("\n");} void show_int(int x){ show_bytes((byte_pointer) &x, sizeof(int));} void show_float(float x){ show_bytes((byte_pointer) &x, sizeof(float));} void show_pointer(void *x){ show_bytes((byte_pointer) &x, sizeof(void *));} /* Driver program to test above functions */int main(){ int i = 1; float f = 1.0; int *p = &i; show_float(f); show_int(i); show_pointer(p); show_int(i); getchar(); return 0;} simmytarika5 c-puzzle C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Structures in C TCP Server-Client implementation in C Data Types in C Multithreading in C Pointer to an Array | Array Pointer Memory Layout of C Programs Power Function in C/C++ Taking String input with space in C (4 Different Methods) Exception Handling in C++ INT_MAX and INT_MIN in C/C++ and Applications
[ { "code": null, "e": 24500, "s": 24472, "text": "\n18 Feb, 2022" }, { "code": null, "e": 24766, "s": 24500, "text": "Write a C program to show memory representation of C variables like int, float, pointer, etc. Algorithm: Get the address and size of the variable. Typecast the address to char pointer. Now loop for size of the variable and print the value at the typecasted pointer." }, { "code": null, "e": 24776, "s": 24766, "text": "Program: " }, { "code": null, "e": 24778, "s": 24776, "text": "c" }, { "code": "#include <stdio.h>typedef unsigned char *byte_pointer; /*show bytes takes byte pointer as an argument and prints memory contents from byte_pointer to byte_pointer + len */void show_bytes(byte_pointer start, int len){ int i; for (i = 0; i < len; i++) printf(\" %.2x\", start[i]); printf(\"\\n\");} void show_int(int x){ show_bytes((byte_pointer) &x, sizeof(int));} void show_float(float x){ show_bytes((byte_pointer) &x, sizeof(float));} void show_pointer(void *x){ show_bytes((byte_pointer) &x, sizeof(void *));} /* Driver program to test above functions */int main(){ int i = 1; float f = 1.0; int *p = &i; show_float(f); show_int(i); show_pointer(p); show_int(i); getchar(); return 0;}", "e": 25524, "s": 24778, "text": null }, { "code": null, "e": 25537, "s": 25524, "text": "simmytarika5" }, { "code": null, "e": 25546, "s": 25537, "text": "c-puzzle" }, { "code": null, "e": 25557, "s": 25546, "text": "C Language" }, { "code": null, "e": 25655, "s": 25557, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25671, "s": 25655, "text": "Structures in C" }, { "code": null, "e": 25709, "s": 25671, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 25725, "s": 25709, "text": "Data Types in C" }, { "code": null, "e": 25745, "s": 25725, "text": "Multithreading in C" }, { "code": null, "e": 25781, "s": 25745, "text": "Pointer to an Array | Array Pointer" }, { "code": null, "e": 25809, "s": 25781, "text": "Memory Layout of C Programs" }, { "code": null, "e": 25833, "s": 25809, "text": "Power Function in C/C++" }, { "code": null, "e": 25891, "s": 25833, "text": "Taking String input with space in C (4 Different Methods)" }, { "code": null, "e": 25917, "s": 25891, "text": "Exception Handling in C++" } ]
A Practical Summary of Pandas in 30 Python Snippets | by Lucas Soares | Towards Data Science
Pandas is one of the most important Python libraries for Data Science and Machine Learning. I used it practically every day but I always feel like I am missing out on useful functionalities, so I decided to write a compressed summary to help guide my progress with my pandas' skills. In this article, I will share a practical summary of the main functionalities of the pandas library in 30 Python snippets. The functionalities we will cover here are: Working with dataframes Reading and writing tabular data Filtering rows in dataframes Selecting specific rows and columns Creating plots Creating new columns from existing columns Calculating summary statistics Sorting values from a table Combining data from multiple tables Handling Time Series Data Manipulating Textual Data Let’s get started! Let’s start with creating a basic dataframe from a dictionary: import pandas as pddata = {"Country": ["Portugal", "USA", "France"], "Population": [10.31*10**6, 329.5*10**6, 67.39*10**6] }df = pd.DataFrame(data)df When you use a Python dictionary to create a pandas dataframe, the keys from that dictionary will be the column headers of the dataframe and the corresponding values will be the columns. You can store multiple data types in the same dataframe. To select a column from a pandas dataframe we do: df["Country"]# Output0 Portugal1 USA2 FranceName: Country, dtype: object Using brackets “[]”, which will return a Series object. As stated in the documentation: A pandas Series has no column labels, as it is just a single column of a DataFrame. A Series does have row labels. We can also check the data type for each column according to pandas interpretation: df.dtypesCountry objectPopulation float64dtype: object In this case, the data types are floats (float64) and strings (object) Pandas provides the read_csv()function to read data stored as a csv file into a pandas DataFrame. Pandas supports many different file formats or data sources out of the box (csv, excel, sql, json, parquet). df = pd.read_csv("Advertising.csv")df If you want to see a controlled subset of the data you can do: df.head(8) Here we are showing only the first 8 rows of the dataframe. If we want to visualize the last 8 rows of the dataframe we can do: df.tail(8) We can also read excel files easily with pandas: df = pd.read_excel("Advertising.xlsx")df You can get a technical summary from a dataframe: df.info()# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 200 entries, 0 to 199Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 TV 200 non-null float64 1 radio 200 non-null float64 2 newspaper 200 non-null float64 3 sales 200 non-null float64dtypes: float64(4)memory usage: 6.4 KB This will output technical information about the dataframe like the number of entries, the data types, the number of columns, the number of null-values, etc. Let’s say I am interested in TV ratings bigger than 100.0, how could I filter my dataframe to get that specific subset? df[df["TV"]>100] We can also do conditional expressions to help our filtering. For example, say we have the titanic dataset (same used in Pandas documentation): df = pd.read_csv("titanic.csv")df And we wanted the info from people under 35 years that survived - we would then use: survived_under_35 = df[(df["Survived"]==1) & (df["Age"]<35)]survived_under_35 Here we use a conditional expression inside parenthesis combined with the and operator here as & to combine the two filtering statements. If we want to work only with the values from a specific column that are not null, we can use the conditional function notna() that returns True for each row the values are not a Null value. df[df["Age"].notna()] For more on conditional expressions and filtering, see this section of the pandas documentation. Say I wanted the names of the passengers older than 40 years old. Since I want a subset of both rows and columns, using just selection brackets [] is not going to be sufficient anymore, so I use the loc/iloc operators: df.loc[df["Age"]>40, "Name"]6 McCarthy, Mr. Timothy J11 Bonnell, Miss. Elizabeth15 Hewlett, Mrs. (Mary D Kingcome) 33 Wheadon, Mr. Edward H35 Holverson, Mr. Alexander Oskar ... 862 Swift, Mrs. Frederick Joel (Margaret Welles Ba...865 Bystrom, Mrs. (Karolina)871 Beckwith, Mrs. Richard Leonard (Sallie Monypeny)873 Vander Cruyssen, Mr. Victor879 Potter, Mrs. Thomas Jr (Lily Alexenia Wilson)Name: Name, Length: 150, dtype: object As said in the documentation: When using loc/iloc, the part before the comma is the rows you want, and the part after the comma is the columns you want to select. When using the column names, row labels, or a condition expression, use the loc operator in front of the selection brackets []. For both the part before and after the comma, you can use a single label, a list of labels, a slice of labels, a conditional expression, or a colon. If you use a colon that means you want to select all rows or columns. When your selection is based on the position on the table, use iloc. For example, say you wanted the rows from 23 to 42 and the columns 1 to 3: df.iloc[22:42, 0:3] When selecting specific rows and/or columns with loc|iloc, new values can be assigned to the selected data. For example, to assign the name anonymous to the first 3 elements of the third column. For more on selection see here. df = pd.read_csv("Advertising.csv") If you want to quickly visualize the data you can simply call the .plot() method: df.plot(); Here pandas creates a one-line plot for each column with numeric data. If you want to get specific, you can select the desired column, for example, say you wanted to plot only the sales: df["sales"].plot(); If you wanted to assess the effect of TV/radio/newspaper ratings on sales, you could plot them against each other one by one: df.plot.scatter(x="TV", y="sales", alpha=0.6); df.plot.scatter(x="radio", y="sales", alpha=0.6); df.plot.scatter(x="newspaper", y="sales", alpha=0.6); There are many plotting options in pandas, and we can check them using the built-in dir() function from Python: for method_name in dir(df.plot): if not method_name.startswith("_"): print(method_name)areabarbarhboxdensityhexbinhistkdelinepiescatter For more plotting with pandas, check this section of the pandas documentation. Creating a new column in pandas is simple. Just use brackets [] with the new column name at the left side assignment and the data for that column on the right side assigment: df["Date"] = pd.date_range("1965-01-01", periods=len(df))df Note: here I also used another cool pandas method called date_range which generates a list of date values from a starting point with a given periodicity indicated by the period parameter. But, what if we want to create a new column from an existing column? For example, say we had the air quality dataset used by the pandas documentation: df = pd.read_csv("air_quality_no2.csv")df Say you want to check the ratio of the values in Antwerp versus London and save that result as a new column: df["ratio_antwerp_london"] = (df["station_antwerp"] / df["station_london"])df If you wanted to apply a more complex function to a column and have the result saved as a new column of the dataframe, you could use the .apply() method. For example, let's apply a conditional to the NO2 values from the London station, where, if they are larger than a threshold, the output will be “High” and otherwise “Low”:: def highLow(temp): if temp > 24.77: return "High" else: return "Low"df["station_london_high_low"] = df["station_london"].apply(highLow)df To rename data columns use pandas .rename(): data = {"Name": ["John", "Mary", "Paul"], "Age": [20,25,30], "Occupation": ["Software Engineer", "Artist", "Product Manager"] }df = pd.DataFrame(data)df_renamed = df.rename(columns={"Name":"First Name", "Occupation": "Job"})df_renamed Notice that I don’t have to rename all of the columns, the Age column remained the same. Calculating statistics in pandas is straight forward: df = pd.read_csv("titanic.csv")print(df["Age"].mean())print(df["Age"].max())print(df["Age"].min())print(df["Age"].median())29.6991176470588280.00.4228.0df.describe() You can also calculate specific combinations of aggregating statistics for given columns: df.agg( { "Age": ["min", "max", "mean"], "Parch": ["min", "max", "mean"] }) The .describe() method comes in handy to speed things up: df.describe() It provides a quick overview of the numerical data in the table. You can also count the number of values/records by category with just one line of code: df["Pclass"].value_counts()3 4911 2162 184Name: Pclass, dtype: int64 You can see more details in this section. Say you had a dataset of names and ages: data = { "Name": ["Lucas", "Beatriz", "Clara", "Sara"], "Age": [30, 26, 20, 22] }df = pd.DataFrame(data)df and you wanted to sort them by age: df.sort_values(by="Age") You can also do it in descending order: df.sort_values(by="Age", ascending=False) df1 = pd.DataFrame( { "Name": ["Lucas", "Beatriz", "Clara", "Sara"], "Age": [30, 26, 20, 22] })df2 = pd.DataFrame( { "Name": ["John", "Mary"], "Age": [45, 38] })df_names_ages = pd.concat([df1, df2], axis=0)df_names_ages One can also merge two dataframes using a shared column. df1 = pd.DataFrame( { "Name": ["Lucas", "Beatriz", "Clara", "Sara"], "Age": [30, 26, 20, 22], "City": ["Lisbon", "Barcelona", "London", "Paris"], })df2 = pd.DataFrame( { "City": ["Lisbon", "Barcelona", "London", "Paris"], "Occupation": ["Machine Learning Enginner", "Scientist", "Writer","Teacher"] })df_merged = pd.merge(df1,df2,how="left", on="City")df_merged You can learn more about concatenating and merging in pandas in this section. import pandas as pdimport matplotlib.pyplot as plt Say we have a dataset like this: df = pd.read_csv("typingPerformance.csv")df This is actually a dataset I created to track my touch typing performance to showing how fast I am typing on my keyboard. One issue here is that the data type for the “date” column is a string. I would like it to be a datetime object so I could perform standard operations for dates on it. Pandas offers a simple way to convert columns to datetime objects: df["date"] = pd.to_datetime(df["date"])df Now, we can check the data type to make sure it is datetime: df.dtypesdate datetime64[ns]wpm objectaccuracy float64dtype: object Perfect! Now we can answer questions with simple expressions. For example, when did I start tracking my typing performance? df["date"].min()Timestamp('2021-01-14 00:00:00') When did I last practice? df["date"].max()Timestamp('2021-10-01 00:00:00') For how long have I been tracking? df["date"].max() - df['date'].min()Timedelta('260 days 00:00:00') I can now create a new column specifying something about the date like what month was it when that data point was created: df["month"] = df["date"].dt.monthdf Now, I can plot for instance the average wpm (words per minute) performance at each month: df_monthly_performance = df.groupby("month")["wpm"].mean()df_monthly_performance.plot()plt.ylabel("wpm"); There is a ton of date-related functionalities in pandas and I recommend checking out this section of the documentation to learn more about it! data = {"Full Name": ["Mark Harrison Junior", "Mary Elisabeth"], "Age": [40, 50]}df = pd.DataFrame(data)df we can use the .str() method to work with string columns. For example, we can make all the strings in a given column lower case: df["Full Name"].str.lower()0 mark harrison junior1 mary elisabethName: Full Name, dtype: object Or create another column based on text manipulation of a given column: df["Last Name"] = df["Full Name"].str.split(" ").str.get(-1)df We can check if string columns contain a certain string: df["Full Name"].str.contains("Junior")0 True1 FalseName: Full Name, dtype: bool You can learn more about text manipulation in this section. Pandas is one of the most ubiquitous Python libraries for Data Scientists and Machine Learning engineers. It has amazing functionalities that if learned properly can be of major help when working with data and speed up your workflow. Put in the time to learn pandas the right way, read the documentation, practice the individual functionalities that tend to reoccur in every project, and I guarantee the results will speak for themselves. If you want to learn more about pandas, check out these two courses from Udemy: The Ultimate Pandas Bootcamp Data Analysis with Pandas (These are affiliate links, if you use them I get a small commission, cheers! :)) If you liked this post, follow me on Medium, subscribe to my newsletter, or join Medium (if you haven’t already :)). Connect with me on Twitter, LinkedIn, and Instagram! Thanks and see you next time! :) pandas documentation pandas user guide
[ { "code": null, "e": 455, "s": 171, "text": "Pandas is one of the most important Python libraries for Data Science and Machine Learning. I used it practically every day but I always feel like I am missing out on useful functionalities, so I decided to write a compressed summary to help guide my progress with my pandas' skills." }, { "code": null, "e": 578, "s": 455, "text": "In this article, I will share a practical summary of the main functionalities of the pandas library in 30 Python snippets." }, { "code": null, "e": 622, "s": 578, "text": "The functionalities we will cover here are:" }, { "code": null, "e": 646, "s": 622, "text": "Working with dataframes" }, { "code": null, "e": 679, "s": 646, "text": "Reading and writing tabular data" }, { "code": null, "e": 708, "s": 679, "text": "Filtering rows in dataframes" }, { "code": null, "e": 744, "s": 708, "text": "Selecting specific rows and columns" }, { "code": null, "e": 759, "s": 744, "text": "Creating plots" }, { "code": null, "e": 802, "s": 759, "text": "Creating new columns from existing columns" }, { "code": null, "e": 833, "s": 802, "text": "Calculating summary statistics" }, { "code": null, "e": 861, "s": 833, "text": "Sorting values from a table" }, { "code": null, "e": 897, "s": 861, "text": "Combining data from multiple tables" }, { "code": null, "e": 923, "s": 897, "text": "Handling Time Series Data" }, { "code": null, "e": 949, "s": 923, "text": "Manipulating Textual Data" }, { "code": null, "e": 968, "s": 949, "text": "Let’s get started!" }, { "code": null, "e": 1031, "s": 968, "text": "Let’s start with creating a basic dataframe from a dictionary:" }, { "code": null, "e": 1207, "s": 1031, "text": "import pandas as pddata = {\"Country\": [\"Portugal\", \"USA\", \"France\"], \"Population\": [10.31*10**6, 329.5*10**6, 67.39*10**6] }df = pd.DataFrame(data)df" }, { "code": null, "e": 1451, "s": 1207, "text": "When you use a Python dictionary to create a pandas dataframe, the keys from that dictionary will be the column headers of the dataframe and the corresponding values will be the columns. You can store multiple data types in the same dataframe." }, { "code": null, "e": 1501, "s": 1451, "text": "To select a column from a pandas dataframe we do:" }, { "code": null, "e": 1590, "s": 1501, "text": "df[\"Country\"]# Output0 Portugal1 USA2 FranceName: Country, dtype: object" }, { "code": null, "e": 1646, "s": 1590, "text": "Using brackets “[]”, which will return a Series object." }, { "code": null, "e": 1678, "s": 1646, "text": "As stated in the documentation:" }, { "code": null, "e": 1793, "s": 1678, "text": "A pandas Series has no column labels, as it is just a single column of a DataFrame. A Series does have row labels." }, { "code": null, "e": 1877, "s": 1793, "text": "We can also check the data type for each column according to pandas interpretation:" }, { "code": null, "e": 1942, "s": 1877, "text": "df.dtypesCountry objectPopulation float64dtype: object" }, { "code": null, "e": 2013, "s": 1942, "text": "In this case, the data types are floats (float64) and strings (object)" }, { "code": null, "e": 2220, "s": 2013, "text": "Pandas provides the read_csv()function to read data stored as a csv file into a pandas DataFrame. Pandas supports many different file formats or data sources out of the box (csv, excel, sql, json, parquet)." }, { "code": null, "e": 2258, "s": 2220, "text": "df = pd.read_csv(\"Advertising.csv\")df" }, { "code": null, "e": 2321, "s": 2258, "text": "If you want to see a controlled subset of the data you can do:" }, { "code": null, "e": 2332, "s": 2321, "text": "df.head(8)" }, { "code": null, "e": 2392, "s": 2332, "text": "Here we are showing only the first 8 rows of the dataframe." }, { "code": null, "e": 2460, "s": 2392, "text": "If we want to visualize the last 8 rows of the dataframe we can do:" }, { "code": null, "e": 2471, "s": 2460, "text": "df.tail(8)" }, { "code": null, "e": 2520, "s": 2471, "text": "We can also read excel files easily with pandas:" }, { "code": null, "e": 2561, "s": 2520, "text": "df = pd.read_excel(\"Advertising.xlsx\")df" }, { "code": null, "e": 2611, "s": 2561, "text": "You can get a technical summary from a dataframe:" }, { "code": null, "e": 3002, "s": 2611, "text": "df.info()# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 200 entries, 0 to 199Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 TV 200 non-null float64 1 radio 200 non-null float64 2 newspaper 200 non-null float64 3 sales 200 non-null float64dtypes: float64(4)memory usage: 6.4 KB" }, { "code": null, "e": 3160, "s": 3002, "text": "This will output technical information about the dataframe like the number of entries, the data types, the number of columns, the number of null-values, etc." }, { "code": null, "e": 3280, "s": 3160, "text": "Let’s say I am interested in TV ratings bigger than 100.0, how could I filter my dataframe to get that specific subset?" }, { "code": null, "e": 3297, "s": 3280, "text": "df[df[\"TV\"]>100]" }, { "code": null, "e": 3441, "s": 3297, "text": "We can also do conditional expressions to help our filtering. For example, say we have the titanic dataset (same used in Pandas documentation):" }, { "code": null, "e": 3475, "s": 3441, "text": "df = pd.read_csv(\"titanic.csv\")df" }, { "code": null, "e": 3560, "s": 3475, "text": "And we wanted the info from people under 35 years that survived - we would then use:" }, { "code": null, "e": 3638, "s": 3560, "text": "survived_under_35 = df[(df[\"Survived\"]==1) & (df[\"Age\"]<35)]survived_under_35" }, { "code": null, "e": 3776, "s": 3638, "text": "Here we use a conditional expression inside parenthesis combined with the and operator here as & to combine the two filtering statements." }, { "code": null, "e": 3966, "s": 3776, "text": "If we want to work only with the values from a specific column that are not null, we can use the conditional function notna() that returns True for each row the values are not a Null value." }, { "code": null, "e": 3988, "s": 3966, "text": "df[df[\"Age\"].notna()]" }, { "code": null, "e": 4085, "s": 3988, "text": "For more on conditional expressions and filtering, see this section of the pandas documentation." }, { "code": null, "e": 4304, "s": 4085, "text": "Say I wanted the names of the passengers older than 40 years old. Since I want a subset of both rows and columns, using just selection brackets [] is not going to be sufficient anymore, so I use the loc/iloc operators:" }, { "code": null, "e": 4987, "s": 4304, "text": "df.loc[df[\"Age\"]>40, \"Name\"]6 McCarthy, Mr. Timothy J11 Bonnell, Miss. Elizabeth15 Hewlett, Mrs. (Mary D Kingcome) 33 Wheadon, Mr. Edward H35 Holverson, Mr. Alexander Oskar ... 862 Swift, Mrs. Frederick Joel (Margaret Welles Ba...865 Bystrom, Mrs. (Karolina)871 Beckwith, Mrs. Richard Leonard (Sallie Monypeny)873 Vander Cruyssen, Mr. Victor879 Potter, Mrs. Thomas Jr (Lily Alexenia Wilson)Name: Name, Length: 150, dtype: object" }, { "code": null, "e": 5017, "s": 4987, "text": "As said in the documentation:" }, { "code": null, "e": 5150, "s": 5017, "text": "When using loc/iloc, the part before the comma is the rows you want, and the part after the comma is the columns you want to select." }, { "code": null, "e": 5278, "s": 5150, "text": "When using the column names, row labels, or a condition expression, use the loc operator in front of the selection brackets []." }, { "code": null, "e": 5497, "s": 5278, "text": "For both the part before and after the comma, you can use a single label, a list of labels, a slice of labels, a conditional expression, or a colon. If you use a colon that means you want to select all rows or columns." }, { "code": null, "e": 5641, "s": 5497, "text": "When your selection is based on the position on the table, use iloc. For example, say you wanted the rows from 23 to 42 and the columns 1 to 3:" }, { "code": null, "e": 5661, "s": 5641, "text": "df.iloc[22:42, 0:3]" }, { "code": null, "e": 5888, "s": 5661, "text": "When selecting specific rows and/or columns with loc|iloc, new values can be assigned to the selected data. For example, to assign the name anonymous to the first 3 elements of the third column. For more on selection see here." }, { "code": null, "e": 5924, "s": 5888, "text": "df = pd.read_csv(\"Advertising.csv\")" }, { "code": null, "e": 6006, "s": 5924, "text": "If you want to quickly visualize the data you can simply call the .plot() method:" }, { "code": null, "e": 6017, "s": 6006, "text": "df.plot();" }, { "code": null, "e": 6204, "s": 6017, "text": "Here pandas creates a one-line plot for each column with numeric data. If you want to get specific, you can select the desired column, for example, say you wanted to plot only the sales:" }, { "code": null, "e": 6224, "s": 6204, "text": "df[\"sales\"].plot();" }, { "code": null, "e": 6350, "s": 6224, "text": "If you wanted to assess the effect of TV/radio/newspaper ratings on sales, you could plot them against each other one by one:" }, { "code": null, "e": 6397, "s": 6350, "text": "df.plot.scatter(x=\"TV\", y=\"sales\", alpha=0.6);" }, { "code": null, "e": 6447, "s": 6397, "text": "df.plot.scatter(x=\"radio\", y=\"sales\", alpha=0.6);" }, { "code": null, "e": 6501, "s": 6447, "text": "df.plot.scatter(x=\"newspaper\", y=\"sales\", alpha=0.6);" }, { "code": null, "e": 6613, "s": 6501, "text": "There are many plotting options in pandas, and we can check them using the built-in dir() function from Python:" }, { "code": null, "e": 6759, "s": 6613, "text": "for method_name in dir(df.plot): if not method_name.startswith(\"_\"): print(method_name)areabarbarhboxdensityhexbinhistkdelinepiescatter" }, { "code": null, "e": 6838, "s": 6759, "text": "For more plotting with pandas, check this section of the pandas documentation." }, { "code": null, "e": 7013, "s": 6838, "text": "Creating a new column in pandas is simple. Just use brackets [] with the new column name at the left side assignment and the data for that column on the right side assigment:" }, { "code": null, "e": 7073, "s": 7013, "text": "df[\"Date\"] = pd.date_range(\"1965-01-01\", periods=len(df))df" }, { "code": null, "e": 7261, "s": 7073, "text": "Note: here I also used another cool pandas method called date_range which generates a list of date values from a starting point with a given periodicity indicated by the period parameter." }, { "code": null, "e": 7412, "s": 7261, "text": "But, what if we want to create a new column from an existing column? For example, say we had the air quality dataset used by the pandas documentation:" }, { "code": null, "e": 7454, "s": 7412, "text": "df = pd.read_csv(\"air_quality_no2.csv\")df" }, { "code": null, "e": 7563, "s": 7454, "text": "Say you want to check the ratio of the values in Antwerp versus London and save that result as a new column:" }, { "code": null, "e": 7641, "s": 7563, "text": "df[\"ratio_antwerp_london\"] = (df[\"station_antwerp\"] / df[\"station_london\"])df" }, { "code": null, "e": 7795, "s": 7641, "text": "If you wanted to apply a more complex function to a column and have the result saved as a new column of the dataframe, you could use the .apply() method." }, { "code": null, "e": 7969, "s": 7795, "text": "For example, let's apply a conditional to the NO2 values from the London station, where, if they are larger than a threshold, the output will be “High” and otherwise “Low”::" }, { "code": null, "e": 8127, "s": 7969, "text": "def highLow(temp): if temp > 24.77: return \"High\" else: return \"Low\"df[\"station_london_high_low\"] = df[\"station_london\"].apply(highLow)df" }, { "code": null, "e": 8172, "s": 8127, "text": "To rename data columns use pandas .rename():" }, { "code": null, "e": 8482, "s": 8172, "text": "data = {\"Name\": [\"John\", \"Mary\", \"Paul\"], \"Age\": [20,25,30], \"Occupation\": [\"Software Engineer\", \"Artist\", \"Product Manager\"] }df = pd.DataFrame(data)df_renamed = df.rename(columns={\"Name\":\"First Name\", \"Occupation\": \"Job\"})df_renamed" }, { "code": null, "e": 8571, "s": 8482, "text": "Notice that I don’t have to rename all of the columns, the Age column remained the same." }, { "code": null, "e": 8625, "s": 8571, "text": "Calculating statistics in pandas is straight forward:" }, { "code": null, "e": 8791, "s": 8625, "text": "df = pd.read_csv(\"titanic.csv\")print(df[\"Age\"].mean())print(df[\"Age\"].max())print(df[\"Age\"].min())print(df[\"Age\"].median())29.6991176470588280.00.4228.0df.describe()" }, { "code": null, "e": 8881, "s": 8791, "text": "You can also calculate specific combinations of aggregating statistics for given columns:" }, { "code": null, "e": 8977, "s": 8881, "text": "df.agg( { \"Age\": [\"min\", \"max\", \"mean\"], \"Parch\": [\"min\", \"max\", \"mean\"] })" }, { "code": null, "e": 9035, "s": 8977, "text": "The .describe() method comes in handy to speed things up:" }, { "code": null, "e": 9049, "s": 9035, "text": "df.describe()" }, { "code": null, "e": 9202, "s": 9049, "text": "It provides a quick overview of the numerical data in the table. You can also count the number of values/records by category with just one line of code:" }, { "code": null, "e": 9280, "s": 9202, "text": "df[\"Pclass\"].value_counts()3 4911 2162 184Name: Pclass, dtype: int64" }, { "code": null, "e": 9322, "s": 9280, "text": "You can see more details in this section." }, { "code": null, "e": 9363, "s": 9322, "text": "Say you had a dataset of names and ages:" }, { "code": null, "e": 9514, "s": 9363, "text": "data = { \"Name\": [\"Lucas\", \"Beatriz\", \"Clara\", \"Sara\"], \"Age\": [30, 26, 20, 22] }df = pd.DataFrame(data)df" }, { "code": null, "e": 9550, "s": 9514, "text": "and you wanted to sort them by age:" }, { "code": null, "e": 9575, "s": 9550, "text": "df.sort_values(by=\"Age\")" }, { "code": null, "e": 9615, "s": 9575, "text": "You can also do it in descending order:" }, { "code": null, "e": 9657, "s": 9615, "text": "df.sort_values(by=\"Age\", ascending=False)" }, { "code": null, "e": 9922, "s": 9657, "text": "df1 = pd.DataFrame( { \"Name\": [\"Lucas\", \"Beatriz\", \"Clara\", \"Sara\"], \"Age\": [30, 26, 20, 22] })df2 = pd.DataFrame( { \"Name\": [\"John\", \"Mary\"], \"Age\": [45, 38] })df_names_ages = pd.concat([df1, df2], axis=0)df_names_ages" }, { "code": null, "e": 9979, "s": 9922, "text": "One can also merge two dataframes using a shared column." }, { "code": null, "e": 10393, "s": 9979, "text": "df1 = pd.DataFrame( { \"Name\": [\"Lucas\", \"Beatriz\", \"Clara\", \"Sara\"], \"Age\": [30, 26, 20, 22], \"City\": [\"Lisbon\", \"Barcelona\", \"London\", \"Paris\"], })df2 = pd.DataFrame( { \"City\": [\"Lisbon\", \"Barcelona\", \"London\", \"Paris\"], \"Occupation\": [\"Machine Learning Enginner\", \"Scientist\", \"Writer\",\"Teacher\"] })df_merged = pd.merge(df1,df2,how=\"left\", on=\"City\")df_merged" }, { "code": null, "e": 10471, "s": 10393, "text": "You can learn more about concatenating and merging in pandas in this section." }, { "code": null, "e": 10522, "s": 10471, "text": "import pandas as pdimport matplotlib.pyplot as plt" }, { "code": null, "e": 10555, "s": 10522, "text": "Say we have a dataset like this:" }, { "code": null, "e": 10599, "s": 10555, "text": "df = pd.read_csv(\"typingPerformance.csv\")df" }, { "code": null, "e": 10721, "s": 10599, "text": "This is actually a dataset I created to track my touch typing performance to showing how fast I am typing on my keyboard." }, { "code": null, "e": 10956, "s": 10721, "text": "One issue here is that the data type for the “date” column is a string. I would like it to be a datetime object so I could perform standard operations for dates on it. Pandas offers a simple way to convert columns to datetime objects:" }, { "code": null, "e": 10998, "s": 10956, "text": "df[\"date\"] = pd.to_datetime(df[\"date\"])df" }, { "code": null, "e": 11059, "s": 10998, "text": "Now, we can check the data type to make sure it is datetime:" }, { "code": null, "e": 11160, "s": 11059, "text": "df.dtypesdate datetime64[ns]wpm objectaccuracy float64dtype: object" }, { "code": null, "e": 11284, "s": 11160, "text": "Perfect! Now we can answer questions with simple expressions. For example, when did I start tracking my typing performance?" }, { "code": null, "e": 11333, "s": 11284, "text": "df[\"date\"].min()Timestamp('2021-01-14 00:00:00')" }, { "code": null, "e": 11359, "s": 11333, "text": "When did I last practice?" }, { "code": null, "e": 11408, "s": 11359, "text": "df[\"date\"].max()Timestamp('2021-10-01 00:00:00')" }, { "code": null, "e": 11443, "s": 11408, "text": "For how long have I been tracking?" }, { "code": null, "e": 11509, "s": 11443, "text": "df[\"date\"].max() - df['date'].min()Timedelta('260 days 00:00:00')" }, { "code": null, "e": 11632, "s": 11509, "text": "I can now create a new column specifying something about the date like what month was it when that data point was created:" }, { "code": null, "e": 11668, "s": 11632, "text": "df[\"month\"] = df[\"date\"].dt.monthdf" }, { "code": null, "e": 11759, "s": 11668, "text": "Now, I can plot for instance the average wpm (words per minute) performance at each month:" }, { "code": null, "e": 11865, "s": 11759, "text": "df_monthly_performance = df.groupby(\"month\")[\"wpm\"].mean()df_monthly_performance.plot()plt.ylabel(\"wpm\");" }, { "code": null, "e": 12009, "s": 11865, "text": "There is a ton of date-related functionalities in pandas and I recommend checking out this section of the documentation to learn more about it!" }, { "code": null, "e": 12128, "s": 12009, "text": "data = {\"Full Name\": [\"Mark Harrison Junior\", \"Mary Elisabeth\"], \"Age\": [40, 50]}df = pd.DataFrame(data)df" }, { "code": null, "e": 12257, "s": 12128, "text": "we can use the .str() method to work with string columns. For example, we can make all the strings in a given column lower case:" }, { "code": null, "e": 12365, "s": 12257, "text": "df[\"Full Name\"].str.lower()0 mark harrison junior1 mary elisabethName: Full Name, dtype: object" }, { "code": null, "e": 12436, "s": 12365, "text": "Or create another column based on text manipulation of a given column:" }, { "code": null, "e": 12499, "s": 12436, "text": "df[\"Last Name\"] = df[\"Full Name\"].str.split(\" \").str.get(-1)df" }, { "code": null, "e": 12556, "s": 12499, "text": "We can check if string columns contain a certain string:" }, { "code": null, "e": 12643, "s": 12556, "text": "df[\"Full Name\"].str.contains(\"Junior\")0 True1 FalseName: Full Name, dtype: bool" }, { "code": null, "e": 12703, "s": 12643, "text": "You can learn more about text manipulation in this section." }, { "code": null, "e": 12937, "s": 12703, "text": "Pandas is one of the most ubiquitous Python libraries for Data Scientists and Machine Learning engineers. It has amazing functionalities that if learned properly can be of major help when working with data and speed up your workflow." }, { "code": null, "e": 13142, "s": 12937, "text": "Put in the time to learn pandas the right way, read the documentation, practice the individual functionalities that tend to reoccur in every project, and I guarantee the results will speak for themselves." }, { "code": null, "e": 13222, "s": 13142, "text": "If you want to learn more about pandas, check out these two courses from Udemy:" }, { "code": null, "e": 13251, "s": 13222, "text": "The Ultimate Pandas Bootcamp" }, { "code": null, "e": 13277, "s": 13251, "text": "Data Analysis with Pandas" }, { "code": null, "e": 13359, "s": 13277, "text": "(These are affiliate links, if you use them I get a small commission, cheers! :))" }, { "code": null, "e": 13562, "s": 13359, "text": "If you liked this post, follow me on Medium, subscribe to my newsletter, or join Medium (if you haven’t already :)). Connect with me on Twitter, LinkedIn, and Instagram! Thanks and see you next time! :)" }, { "code": null, "e": 13583, "s": 13562, "text": "pandas documentation" } ]
C / C++ Program for Dijkstra's shortest path algorithm | Greedy Algo-7 - GeeksforGeeks
08 Jul, 2021 Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph.Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has a minimum distance from the source.Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm 1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. 2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. 3) While sptSet doesn’t include all vertices ....a) Pick a vertex u which is not there in sptSet and has minimum distance value. ....b) Include u to sptSet. ....c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. C++ // A C++ program for Dijkstra's single source shortest path algorithm.// The program is for adjacency matrix representation of the graph #include <limits.h>#include <stdio.h> // Number of vertices in the graph#define V 9 // A utility function to find the vertex with minimum distance value, from// the set of vertices not yet included in shortest path treeint minDistance(int dist[], bool sptSet[]){ // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index;} // A utility function to print the constructed distance arrayint printSolution(int dist[], int n){ printf("Vertex Distance from Source\n"); for (int i = 0; i < V; i++) printf("%d \t\t %d\n", i, dist[i]);} // Function that implements Dijkstra's single source shortest path algorithm// for a graph represented using adjacency matrix representationvoid dijkstra(int graph[V][V], int src){ int dist[V]; // The output array. dist[i] will hold the shortest // distance from src to i bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest // path tree or shortest distance from src to i is finalized // Initialize all distances as INFINITE and stpSet[] as false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of vertices not // yet processed. u is always equal to src in the first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, there is an edge from // u to v, and total weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist, V);} // driver program to test above functionint main(){ /* Let us create the example graph discussed above */ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; dijkstra(graph, 0); return 0;} Vertex Distance from Source 0 0 1 4 2 12 3 19 4 21 5 11 6 9 7 8 8 14 Please refer complete article on Dijkstra’s shortest path algorithm | Greedy Algo-7 for more details! adityakayal Dijkstra C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Header files in C/C++ and its uses How to return multiple values from a function in C or C++? How to Append a Character to a String in C Program to print ASCII Value of a character Producer Consumer Problem in C C program to sort an array in ascending order Program to find Prime Numbers Between given Interval time() function in C C Program to Swap two Numbers
[ { "code": null, "e": 25344, "s": 25316, "text": "\n08 Jul, 2021" }, { "code": null, "e": 26936, "s": 25344, "text": "Given a graph and a source vertex in the graph, find shortest paths from source to all vertices in the given graph.Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain two sets, one set contains vertices included in shortest path tree, other set includes vertices not yet included in shortest path tree. At every step of the algorithm, we find a vertex which is in the other set (set of not yet included) and has a minimum distance from the source.Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm 1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. 2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. 3) While sptSet doesn’t include all vertices ....a) Pick a vertex u which is not there in sptSet and has minimum distance value. ....b) Include u to sptSet. ....c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v. " }, { "code": null, "e": 26940, "s": 26936, "text": "C++" }, { "code": "// A C++ program for Dijkstra's single source shortest path algorithm.// The program is for adjacency matrix representation of the graph #include <limits.h>#include <stdio.h> // Number of vertices in the graph#define V 9 // A utility function to find the vertex with minimum distance value, from// the set of vertices not yet included in shortest path treeint minDistance(int dist[], bool sptSet[]){ // Initialize min value int min = INT_MAX, min_index; for (int v = 0; v < V; v++) if (sptSet[v] == false && dist[v] <= min) min = dist[v], min_index = v; return min_index;} // A utility function to print the constructed distance arrayint printSolution(int dist[], int n){ printf(\"Vertex Distance from Source\\n\"); for (int i = 0; i < V; i++) printf(\"%d \\t\\t %d\\n\", i, dist[i]);} // Function that implements Dijkstra's single source shortest path algorithm// for a graph represented using adjacency matrix representationvoid dijkstra(int graph[V][V], int src){ int dist[V]; // The output array. dist[i] will hold the shortest // distance from src to i bool sptSet[V]; // sptSet[i] will be true if vertex i is included in shortest // path tree or shortest distance from src to i is finalized // Initialize all distances as INFINITE and stpSet[] as false for (int i = 0; i < V; i++) dist[i] = INT_MAX, sptSet[i] = false; // Distance of source vertex from itself is always 0 dist[src] = 0; // Find shortest path for all vertices for (int count = 0; count < V - 1; count++) { // Pick the minimum distance vertex from the set of vertices not // yet processed. u is always equal to src in the first iteration. int u = minDistance(dist, sptSet); // Mark the picked vertex as processed sptSet[u] = true; // Update dist value of the adjacent vertices of the picked vertex. for (int v = 0; v < V; v++) // Update dist[v] only if is not in sptSet, there is an edge from // u to v, and total weight of path from src to v through u is // smaller than current value of dist[v] if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + graph[u][v] < dist[v]) dist[v] = dist[u] + graph[u][v]; } // print the constructed distance array printSolution(dist, V);} // driver program to test above functionint main(){ /* Let us create the example graph discussed above */ int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; dijkstra(graph, 0); return 0;}", "e": 29956, "s": 26940, "text": null }, { "code": null, "e": 30109, "s": 29956, "text": "Vertex Distance from Source\n0 0\n1 4\n2 12\n3 19\n4 21\n5 11\n6 9\n7 8\n8 14\n" }, { "code": null, "e": 30212, "s": 30109, "text": "Please refer complete article on Dijkstra’s shortest path algorithm | Greedy Algo-7 for more details! " }, { "code": null, "e": 30224, "s": 30212, "text": "adityakayal" }, { "code": null, "e": 30233, "s": 30224, "text": "Dijkstra" }, { "code": null, "e": 30244, "s": 30233, "text": "C Programs" }, { "code": null, "e": 30342, "s": 30244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30383, "s": 30342, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30418, "s": 30383, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30477, "s": 30418, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 30520, "s": 30477, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 30564, "s": 30520, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30595, "s": 30564, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 30641, "s": 30595, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 30694, "s": 30641, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 30715, "s": 30694, "text": "time() function in C" } ]
C++ Program for ShellSort - GeeksforGeeks
09 May, 2019 In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted. // C++ implementation of Shell Sort#include <iostream> /* function to sort arr using shellSort */void shellSort(int arr[], int n){ // Start with a big gap, then reduce the gap for (int gap = n / 2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements arr[0..gap-1] are already in gapped order // keep adding one more element until the entire array is // gap sorted for (int i = gap; i < n; i += 1) { // add arr[i] to the elements that have been gap sorted // save arr[i] in temp and make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until the correct // location for arr[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original arr[i]) in its correct location arr[j] = temp; } }} void printArray(int arr[], int n){ for (int i = 0; i < n; i++) std::cout << arr[i] << " "; std::cout << "\n";} int main(){ int arr[] = { 12, 34, 54, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); std::cout << "Array before sorting: \n"; printArray(arr, n); shellSort(arr, n); std::cout << "Array after sorting: \n"; printArray(arr, n);} Array before sorting: 12 34 54 2 3 Array after sorting: 2 3 12 34 54 Please refer complete article on ShellSort for more details! ted1 C++ Programs Sorting Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class cout in C++ Pi(π) in C++ with Examples Const keyword in C++
[ { "code": null, "e": 24215, "s": 24187, "text": "\n09 May, 2019" }, { "code": null, "e": 24413, "s": 24215, "text": "In shellSort, we make the array h-sorted for a large value of h. We keep reducing the value of h until it becomes 1. An array is said to be h-sorted if all sublists of every h’th element is sorted." }, { "code": "// C++ implementation of Shell Sort#include <iostream> /* function to sort arr using shellSort */void shellSort(int arr[], int n){ // Start with a big gap, then reduce the gap for (int gap = n / 2; gap > 0; gap /= 2) { // Do a gapped insertion sort for this gap size. // The first gap elements arr[0..gap-1] are already in gapped order // keep adding one more element until the entire array is // gap sorted for (int i = gap; i < n; i += 1) { // add arr[i] to the elements that have been gap sorted // save arr[i] in temp and make a hole at position i int temp = arr[i]; // shift earlier gap-sorted elements up until the correct // location for arr[i] is found int j; for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) arr[j] = arr[j - gap]; // put temp (the original arr[i]) in its correct location arr[j] = temp; } }} void printArray(int arr[], int n){ for (int i = 0; i < n; i++) std::cout << arr[i] << \" \"; std::cout << \"\\n\";} int main(){ int arr[] = { 12, 34, 54, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); std::cout << \"Array before sorting: \\n\"; printArray(arr, n); shellSort(arr, n); std::cout << \"Array after sorting: \\n\"; printArray(arr, n);}", "e": 25785, "s": 24413, "text": null }, { "code": null, "e": 25858, "s": 25785, "text": "Array before sorting: \n12 34 54 2 3 \nArray after sorting: \n2 3 12 34 54\n" }, { "code": null, "e": 25919, "s": 25858, "text": "Please refer complete article on ShellSort for more details!" }, { "code": null, "e": 25924, "s": 25919, "text": "ted1" }, { "code": null, "e": 25937, "s": 25924, "text": "C++ Programs" }, { "code": null, "e": 25945, "s": 25937, "text": "Sorting" }, { "code": null, "e": 25953, "s": 25945, "text": "Sorting" }, { "code": null, "e": 26051, "s": 25953, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26060, "s": 26051, "text": "Comments" }, { "code": null, "e": 26073, "s": 26060, "text": "Old Comments" }, { "code": null, "e": 26114, "s": 26073, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 26173, "s": 26114, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 26185, "s": 26173, "text": "cout in C++" }, { "code": null, "e": 26212, "s": 26185, "text": "Pi(π) in C++ with Examples" } ]
SciPy - Stats
All of the statistics functions are located in the sub-package scipy.stats and a fairly complete listing of these functions can be obtained using info(stats) function. A list of random variables available can also be obtained from the docstring for the stats sub-package. This module contains a large number of probability distributions as well as a growing library of statistical functions. Each univariate distribution has its own subclass as described in the following table − rv_continuous A generic continuous random variable class meant for subclassing rv_discrete A generic discrete random variable class meant for subclassing rv_histogram Generates a distribution given by a histogram A probability distribution in which the random variable X can take any value is continuous random variable. The location (loc) keyword specifies the mean. The scale (scale) keyword specifies the standard deviation. As an instance of the rv_continuous class, norm object inherits from it a collection of generic methods and completes them with details specific for this particular distribution. To compute the CDF at a number of points, we can pass a list or a NumPy array. Let us consider the following example. from scipy.stats import norm import numpy as np print norm.cdf(np.array([1,-1., 0, 1, 3, 4, -2, 6])) The above program will generate the following output. array([ 0.84134475, 0.15865525, 0.5 , 0.84134475, 0.9986501 , 0.99996833, 0.02275013, 1. ]) To find the median of a distribution, we can use the Percent Point Function (PPF), which is the inverse of the CDF. Let us understand by using the following example. from scipy.stats import norm print norm.ppf(0.5) The above program will generate the following output. 0.0 To generate a sequence of random variates, we should use the size keyword argument, which is shown in the following example. from scipy.stats import norm print norm.rvs(size = 5) The above program will generate the following output. array([ 0.20929928, -1.91049255, 0.41264672, -0.7135557 , -0.03833048]) The above output is not reproducible. To generate the same random numbers, use the seed function. A uniform distribution can be generated using the uniform function. Let us consider the following example. from scipy.stats import uniform print uniform.cdf([0, 1, 2, 3, 4, 5], loc = 1, scale = 4) The above program will generate the following output. array([ 0. , 0. , 0.25, 0.5 , 0.75, 1. ]) Let us generate a random sample and compare the observed frequencies with the probabilities. As an instance of the rv_discrete class, the binom object inherits from it a collection of generic methods and completes them with details specific for this particular distribution. Let us consider the following example. from scipy.stats import uniform print uniform.cdf([0, 1, 2, 3, 4, 5], loc = 1, scale = 4) The above program will generate the following output. array([ 0. , 0. , 0.25, 0.5 , 0.75, 1. ]) The basic stats such as Min, Max, Mean and Variance takes the NumPy array as input and returns the respective results. A few basic statistical functions available in the scipy.stats package are described in the following table. describe() Computes several descriptive statistics of the passed array gmean() Computes geometric mean along the specified axis hmean() Calculates the harmonic mean along the specified axis kurtosis() Computes the kurtosis mode() Returns the modal value skew() Tests the skewness of the data f_oneway() Performs a 1-way ANOVA iqr() Computes the interquartile range of the data along the specified axis zscore() Calculates the z score of each value in the sample, relative to the sample mean and standard deviation sem() Calculates the standard error of the mean (or standard error of measurement) of the values in the input array Several of these functions have a similar version in the scipy.stats.mstats, which work for masked arrays. Let us understand this with the example given below. from scipy import stats import numpy as np x = np.array([1,2,3,4,5,6,7,8,9]) print x.max(),x.min(),x.mean(),x.var() The above program will generate the following output. (9, 1, 5.0, 6.666666666666667) Let us understand how T-test is useful in SciPy. Calculates the T-test for the mean of ONE group of scores. This is a two-sided test for the null hypothesis that the expected value (mean) of a sample of independent observations ‘a’ is equal to the given population mean, popmean. Let us consider the following example. from scipy import stats rvs = stats.norm.rvs(loc = 5, scale = 10, size = (50,2)) print stats.ttest_1samp(rvs,5.0) The above program will generate the following output. Ttest_1sampResult(statistic = array([-1.40184894, 2.70158009]), pvalue = array([ 0.16726344, 0.00945234])) In the following examples, there are two samples, which can come either from the same or from different distribution, and we want to test whether these samples have the same statistical properties. ttest_ind − Calculates the T-test for the means of two independent samples of scores. This is a two-sided test for the null hypothesis that two independent samples have identical average (expected) values. This test assumes that the populations have identical variances by default. We can use this test, if we observe two independent samples from the same or different population. Let us consider the following example. from scipy import stats rvs1 = stats.norm.rvs(loc = 5,scale = 10,size = 500) rvs2 = stats.norm.rvs(loc = 5,scale = 10,size = 500) print stats.ttest_ind(rvs1,rvs2) The above program will generate the following output. Ttest_indResult(statistic = -0.67406312233650278, pvalue = 0.50042727502272966) You can test the same with a new array of the same length, but with a varied mean. Use a different value in loc and test the same. Print Add Notes Bookmark this page
[ { "code": null, "e": 2279, "s": 1887, "text": "All of the statistics functions are located in the sub-package scipy.stats and a fairly complete listing of these functions can be obtained using info(stats) function. A list of random variables available can also be obtained from the docstring for the stats sub-package. This module contains a large number of probability distributions as well as a growing library of statistical functions." }, { "code": null, "e": 2367, "s": 2279, "text": "Each univariate distribution has its own subclass as described in the following table −" }, { "code": null, "e": 2381, "s": 2367, "text": "rv_continuous" }, { "code": null, "e": 2446, "s": 2381, "text": "A generic continuous random variable class meant for subclassing" }, { "code": null, "e": 2458, "s": 2446, "text": "rv_discrete" }, { "code": null, "e": 2521, "s": 2458, "text": "A generic discrete random variable class meant for subclassing" }, { "code": null, "e": 2534, "s": 2521, "text": "rv_histogram" }, { "code": null, "e": 2580, "s": 2534, "text": "Generates a distribution given by a histogram" }, { "code": null, "e": 2795, "s": 2580, "text": "A probability distribution in which the random variable X can take any value is continuous random variable. The location (loc) keyword specifies the mean. The scale (scale) keyword specifies the standard deviation." }, { "code": null, "e": 2974, "s": 2795, "text": "As an instance of the rv_continuous class, norm object inherits from it a collection of generic methods and completes them with details specific for this particular distribution." }, { "code": null, "e": 3092, "s": 2974, "text": "To compute the CDF at a number of points, we can pass a list or a NumPy array. Let us consider the following example." }, { "code": null, "e": 3194, "s": 3092, "text": "from scipy.stats import norm\nimport numpy as np\nprint norm.cdf(np.array([1,-1., 0, 1, 3, 4, -2, 6]))\n" }, { "code": null, "e": 3248, "s": 3194, "text": "The above program will generate the following output." }, { "code": null, "e": 3341, "s": 3248, "text": "array([ 0.84134475, 0.15865525, 0.5 , 0.84134475, 0.9986501 ,\n0.99996833, 0.02275013, 1. ])\n" }, { "code": null, "e": 3507, "s": 3341, "text": "To find the median of a distribution, we can use the Percent Point Function (PPF), which is the inverse of the CDF. Let us understand by using the following example." }, { "code": null, "e": 3557, "s": 3507, "text": "from scipy.stats import norm\nprint norm.ppf(0.5)\n" }, { "code": null, "e": 3611, "s": 3557, "text": "The above program will generate the following output." }, { "code": null, "e": 3616, "s": 3611, "text": "0.0\n" }, { "code": null, "e": 3741, "s": 3616, "text": "To generate a sequence of random variates, we should use the size keyword argument, which is shown in the following example." }, { "code": null, "e": 3796, "s": 3741, "text": "from scipy.stats import norm\nprint norm.rvs(size = 5)\n" }, { "code": null, "e": 3850, "s": 3796, "text": "The above program will generate the following output." }, { "code": null, "e": 3923, "s": 3850, "text": "array([ 0.20929928, -1.91049255, 0.41264672, -0.7135557 , -0.03833048])\n" }, { "code": null, "e": 4021, "s": 3923, "text": "The above output is not reproducible. To generate the same random numbers, use the seed function." }, { "code": null, "e": 4128, "s": 4021, "text": "A uniform distribution can be generated using the uniform function. Let us consider the following example." }, { "code": null, "e": 4219, "s": 4128, "text": "from scipy.stats import uniform\nprint uniform.cdf([0, 1, 2, 3, 4, 5], loc = 1, scale = 4)\n" }, { "code": null, "e": 4273, "s": 4219, "text": "The above program will generate the following output." }, { "code": null, "e": 4316, "s": 4273, "text": "array([ 0. , 0. , 0.25, 0.5 , 0.75, 1. ])\n" }, { "code": null, "e": 4409, "s": 4316, "text": "Let us generate a random sample and compare the observed frequencies with the probabilities." }, { "code": null, "e": 4630, "s": 4409, "text": "As an instance of the rv_discrete class, the binom object inherits from it a collection of generic methods and completes them with details specific for this particular distribution. Let us consider the following example." }, { "code": null, "e": 4721, "s": 4630, "text": "from scipy.stats import uniform\nprint uniform.cdf([0, 1, 2, 3, 4, 5], loc = 1, scale = 4)\n" }, { "code": null, "e": 4775, "s": 4721, "text": "The above program will generate the following output." }, { "code": null, "e": 4818, "s": 4775, "text": "array([ 0. , 0. , 0.25, 0.5 , 0.75, 1. ])\n" }, { "code": null, "e": 5046, "s": 4818, "text": "The basic stats such as Min, Max, Mean and Variance takes the NumPy array as input and returns the respective results. A few basic statistical functions available in the scipy.stats package are described in the following table." }, { "code": null, "e": 5057, "s": 5046, "text": "describe()" }, { "code": null, "e": 5117, "s": 5057, "text": "Computes several descriptive statistics of the passed array" }, { "code": null, "e": 5125, "s": 5117, "text": "gmean()" }, { "code": null, "e": 5174, "s": 5125, "text": "Computes geometric mean along the specified axis" }, { "code": null, "e": 5182, "s": 5174, "text": "hmean()" }, { "code": null, "e": 5236, "s": 5182, "text": "Calculates the harmonic mean along the specified axis" }, { "code": null, "e": 5247, "s": 5236, "text": "kurtosis()" }, { "code": null, "e": 5269, "s": 5247, "text": "Computes the kurtosis" }, { "code": null, "e": 5276, "s": 5269, "text": "mode()" }, { "code": null, "e": 5300, "s": 5276, "text": "Returns the modal value" }, { "code": null, "e": 5307, "s": 5300, "text": "skew()" }, { "code": null, "e": 5338, "s": 5307, "text": "Tests the skewness of the data" }, { "code": null, "e": 5349, "s": 5338, "text": "f_oneway()" }, { "code": null, "e": 5372, "s": 5349, "text": "Performs a 1-way ANOVA" }, { "code": null, "e": 5378, "s": 5372, "text": "iqr()" }, { "code": null, "e": 5448, "s": 5378, "text": "Computes the interquartile range of the data along the specified axis" }, { "code": null, "e": 5457, "s": 5448, "text": "zscore()" }, { "code": null, "e": 5560, "s": 5457, "text": "Calculates the z score of each value in the sample, relative to the sample mean and standard deviation" }, { "code": null, "e": 5566, "s": 5560, "text": "sem()" }, { "code": null, "e": 5676, "s": 5566, "text": "Calculates the standard error of the mean (or standard error of measurement) of the values in the input array" }, { "code": null, "e": 5836, "s": 5676, "text": "Several of these functions have a similar version in the scipy.stats.mstats, which work for masked arrays. Let us understand this with the example given below." }, { "code": null, "e": 5952, "s": 5836, "text": "from scipy import stats\nimport numpy as np\nx = np.array([1,2,3,4,5,6,7,8,9])\nprint x.max(),x.min(),x.mean(),x.var()" }, { "code": null, "e": 6006, "s": 5952, "text": "The above program will generate the following output." }, { "code": null, "e": 6038, "s": 6006, "text": "(9, 1, 5.0, 6.666666666666667)\n" }, { "code": null, "e": 6087, "s": 6038, "text": "Let us understand how T-test is useful in SciPy." }, { "code": null, "e": 6357, "s": 6087, "text": "Calculates the T-test for the mean of ONE group of scores. This is a two-sided test for the null hypothesis that the expected value (mean) of a sample of independent observations ‘a’ is equal to the given population mean, popmean. Let us consider the following example." }, { "code": null, "e": 6471, "s": 6357, "text": "from scipy import stats\nrvs = stats.norm.rvs(loc = 5, scale = 10, size = (50,2))\nprint stats.ttest_1samp(rvs,5.0)" }, { "code": null, "e": 6525, "s": 6471, "text": "The above program will generate the following output." }, { "code": null, "e": 6633, "s": 6525, "text": "Ttest_1sampResult(statistic = array([-1.40184894, 2.70158009]),\npvalue = array([ 0.16726344, 0.00945234]))\n" }, { "code": null, "e": 6831, "s": 6633, "text": "In the following examples, there are two samples, which can come either from the same or from different distribution, and we want to test whether these samples have the same statistical properties." }, { "code": null, "e": 7113, "s": 6831, "text": "ttest_ind − Calculates the T-test for the means of two independent samples of scores. This is a two-sided test for the null hypothesis that two independent samples have identical average (expected) values. This test assumes that the populations have identical variances by default." }, { "code": null, "e": 7251, "s": 7113, "text": "We can use this test, if we observe two independent samples from the same or different population. Let us consider the following example." }, { "code": null, "e": 7414, "s": 7251, "text": "from scipy import stats\nrvs1 = stats.norm.rvs(loc = 5,scale = 10,size = 500)\nrvs2 = stats.norm.rvs(loc = 5,scale = 10,size = 500)\nprint stats.ttest_ind(rvs1,rvs2)" }, { "code": null, "e": 7468, "s": 7414, "text": "The above program will generate the following output." }, { "code": null, "e": 7549, "s": 7468, "text": "Ttest_indResult(statistic = -0.67406312233650278, pvalue = 0.50042727502272966)\n" }, { "code": null, "e": 7680, "s": 7549, "text": "You can test the same with a new array of the same length, but with a varied mean. Use a different value in loc and test the same." }, { "code": null, "e": 7687, "s": 7680, "text": " Print" }, { "code": null, "e": 7698, "s": 7687, "text": " Add Notes" } ]
How to merge two strings alternatively in JavaScript
We are required to write a JavaScript function that takes in two. Our function should then return a new array that contains characters alternatively from both the strings. For example: If the two strings are − const str1 = 'abc'; const str2 = 'def'; Then the output should be − const output = 'adbecf'; The code for this will be − const str1 = 'abc'; const str2 = 'def'; const mergeAlternatively = (str1, str2) => { const a = str1.split("").filter(el => !!el); const b = str2.split(""); let mergedString = ''; for(var i = 0; i < a.length || i < b.length; i++){ if(i < a.length){ mergedString += a[i]; }; if(i < b.length){ mergedString += b[i]; }; }; return mergedString; }; console.log(mergeAlternatively(str1, str2)); The output in the console − adbecf
[ { "code": null, "e": 1234, "s": 1062, "text": "We are required to write a JavaScript function that takes in two. Our function should then return a new array that contains characters alternatively from both the strings." }, { "code": null, "e": 1272, "s": 1234, "text": "For example: If the two strings are −" }, { "code": null, "e": 1312, "s": 1272, "text": "const str1 = 'abc';\nconst str2 = 'def';" }, { "code": null, "e": 1340, "s": 1312, "text": "Then the output should be −" }, { "code": null, "e": 1365, "s": 1340, "text": "const output = 'adbecf';" }, { "code": null, "e": 1393, "s": 1365, "text": "The code for this will be −" }, { "code": null, "e": 1841, "s": 1393, "text": "const str1 = 'abc';\nconst str2 = 'def';\nconst mergeAlternatively = (str1, str2) => {\n const a = str1.split(\"\").filter(el => !!el);\n const b = str2.split(\"\");\n let mergedString = '';\n for(var i = 0; i < a.length || i < b.length; i++){\n if(i < a.length){\n mergedString += a[i];\n };\n if(i < b.length){\n mergedString += b[i];\n };\n };\n return mergedString;\n};\nconsole.log(mergeAlternatively(str1, str2));" }, { "code": null, "e": 1869, "s": 1841, "text": "The output in the console −" }, { "code": null, "e": 1876, "s": 1869, "text": "adbecf" } ]
Converting a Picture into an Excel File | by Sutan Ashari Mufti | Towards Data Science
A question popped up in my head. Images are basically raster files. As a raster file, naturally, an image consists of rows and columns filled by colour values. You can see this by opening a picture in Photoshop and zoom in. Or just open the picture and zoom in, you’ll see it’ll get pixelated. So technically, an image can be converted into an excel file that also consists of rows and columns. How to convert an image into an excel file Diving into computer vision (CV) science, there is a way by utilising Python and VBA for Excel. In CV, commonly, images are treated as an array. Usually, the colours are expressed in RGB values that range between 0–255, but it can also be in another model such as the HSV value scale. These colour models need 3 channels, one for each element. but for excel, we need a colour expression that only needs 1 channel. Well, not really, but it’s easier this way. And that’s where the hex colour model comes in. We can visit the science behind the hex colour model, but it’s just too long for this essay. My concern for this essay is that one colour must be represented in one channel. So, this essay's objective is to describe how to convert an image into an excel file with coloured cells corresponding to the input image. Let’s get into it! there are many tools to do this, but I think the principles remain the same. convert the image into an array object (for this case, a NumPy array)(optional, but recommended) resize the image so that it won’t be too heavy in excel. My preference is to scale the width to 100 px. This means that the result excel file will contain 100 columns.this array, naturally, is a 3-dimensional array (height, width, RGB value); the RGB values must be converted into Hexadecimal form. (well this is also optional, but it’s easier in excel to convert hex form into colour for the cell)export the array into an excel file (the shape will be (height, width, hex value)colour each cell based on its hexadecimal colour value. Use VBA! VBA is used because this work is mathematical and scalable. don’t waste your time by colouring it one by one.... convert the image into an array object (for this case, a NumPy array) (optional, but recommended) resize the image so that it won’t be too heavy in excel. My preference is to scale the width to 100 px. This means that the result excel file will contain 100 columns. this array, naturally, is a 3-dimensional array (height, width, RGB value); the RGB values must be converted into Hexadecimal form. (well this is also optional, but it’s easier in excel to convert hex form into colour for the cell) export the array into an excel file (the shape will be (height, width, hex value) colour each cell based on its hexadecimal colour value. Use VBA! VBA is used because this work is mathematical and scalable. don’t waste your time by colouring it one by one.... All right, let’s get started... let’s just go to the python script! the philosophy behind the script: I want to run the script, type my image file name, type my excel file name, and that’s it (for now). # input the image name via command linename = input("what is your filename?: ")# check if the image name is valid or not. if valid, continue to the next step!# use PIL for image manipulationreadmode=Truefrom PIL import Imagewhile readmode: try: img = Image.open(name) readmode = Falseexcept: print("can not read", name) print("please input your file name again: ") name = input("what is your filename?:")# resize the imagebasewidth = 100wpercent = (basewidth/float(img.size[0]))hsize = int((float(img.size[1])*float(wpercent)))img = img.resize((basewidth,hsize), Image.ANTIALIAS)# convert the image into an array object# I also convert the image into a pandas DataFrame because I'm going to convert it into an excel fileimport numpy as nparr = np.array(img)arr_container = np.empty((arr.shape[0], arr.shape[1]), dtype=np.str)import pandas as pddf = pd.DataFrame(arr_container)# convert the R,G,B into hexadecimal# populate the DataFrame with the hexadecimal valuefor l,x in enumerate(arr): for m,y in enumerate(x): r,g,b = arr[l][m] hexval = '%02x%02x%02x' % (r, g, b) df[m][l] = hexval# save it! yeay!save_file_name = input("your excel file name, without '.xlsx' please: ")df.to_excel(str(save_file_name) + ".xlsx")print("success!! now colour the file") The source code for the VBA can be found here. basically, the code colours the cell every time the cell is typed a hexadecimal colour value. open the excel file resultadd the VBA code into the sheet (copy the code from below)copy all cell, and paste into the same location (the cell will be coloured automatically) (ctrl + a, ctrl + c, ctrl + v)delete all cell values (ctrl + a, delete)adjust the column sizevoila open the excel file result add the VBA code into the sheet (copy the code from below) copy all cell, and paste into the same location (the cell will be coloured automatically) (ctrl + a, ctrl + c, ctrl + v) delete all cell values (ctrl + a, delete) adjust the column size voila Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo bm_Safe_Exit Application.EnableEvents = False Dim rng As Range, clr As String For Each rng In Target If Len(rng.Value2) = 6 Then clr = rng.Value2 rng.Interior.Color = _ RGB(Application.Hex2Dec(Left(clr, 2)), _ Application.Hex2Dec(Mid(clr, 3, 2)), _ Application.Hex2Dec(Right(clr, 2))) End If Next rngbm_Safe_Exit: Application.EnableEvents = TrueEnd Sub and yeah, that’s it. you can see in the gif below that the cells are coloured, and we still can change the cell color. good luck!
[ { "code": null, "e": 567, "s": 172, "text": "A question popped up in my head. Images are basically raster files. As a raster file, naturally, an image consists of rows and columns filled by colour values. You can see this by opening a picture in Photoshop and zoom in. Or just open the picture and zoom in, you’ll see it’ll get pixelated. So technically, an image can be converted into an excel file that also consists of rows and columns." }, { "code": null, "e": 610, "s": 567, "text": "How to convert an image into an excel file" }, { "code": null, "e": 1068, "s": 610, "text": "Diving into computer vision (CV) science, there is a way by utilising Python and VBA for Excel. In CV, commonly, images are treated as an array. Usually, the colours are expressed in RGB values that range between 0–255, but it can also be in another model such as the HSV value scale. These colour models need 3 channels, one for each element. but for excel, we need a colour expression that only needs 1 channel. Well, not really, but it’s easier this way." }, { "code": null, "e": 1290, "s": 1068, "text": "And that’s where the hex colour model comes in. We can visit the science behind the hex colour model, but it’s just too long for this essay. My concern for this essay is that one colour must be represented in one channel." }, { "code": null, "e": 1448, "s": 1290, "text": "So, this essay's objective is to describe how to convert an image into an excel file with coloured cells corresponding to the input image. Let’s get into it!" }, { "code": null, "e": 1525, "s": 1448, "text": "there are many tools to do this, but I think the principles remain the same." }, { "code": null, "e": 2279, "s": 1525, "text": "convert the image into an array object (for this case, a NumPy array)(optional, but recommended) resize the image so that it won’t be too heavy in excel. My preference is to scale the width to 100 px. This means that the result excel file will contain 100 columns.this array, naturally, is a 3-dimensional array (height, width, RGB value); the RGB values must be converted into Hexadecimal form. (well this is also optional, but it’s easier in excel to convert hex form into colour for the cell)export the array into an excel file (the shape will be (height, width, hex value)colour each cell based on its hexadecimal colour value. Use VBA! VBA is used because this work is mathematical and scalable. don’t waste your time by colouring it one by one...." }, { "code": null, "e": 2349, "s": 2279, "text": "convert the image into an array object (for this case, a NumPy array)" }, { "code": null, "e": 2545, "s": 2349, "text": "(optional, but recommended) resize the image so that it won’t be too heavy in excel. My preference is to scale the width to 100 px. This means that the result excel file will contain 100 columns." }, { "code": null, "e": 2777, "s": 2545, "text": "this array, naturally, is a 3-dimensional array (height, width, RGB value); the RGB values must be converted into Hexadecimal form. (well this is also optional, but it’s easier in excel to convert hex form into colour for the cell)" }, { "code": null, "e": 2859, "s": 2777, "text": "export the array into an excel file (the shape will be (height, width, hex value)" }, { "code": null, "e": 3037, "s": 2859, "text": "colour each cell based on its hexadecimal colour value. Use VBA! VBA is used because this work is mathematical and scalable. don’t waste your time by colouring it one by one...." }, { "code": null, "e": 3069, "s": 3037, "text": "All right, let’s get started..." }, { "code": null, "e": 3105, "s": 3069, "text": "let’s just go to the python script!" }, { "code": null, "e": 3240, "s": 3105, "text": "the philosophy behind the script: I want to run the script, type my image file name, type my excel file name, and that’s it (for now)." }, { "code": null, "e": 4557, "s": 3240, "text": "# input the image name via command linename = input(\"what is your filename?: \")# check if the image name is valid or not. if valid, continue to the next step!# use PIL for image manipulationreadmode=Truefrom PIL import Imagewhile readmode: try: img = Image.open(name) readmode = Falseexcept: print(\"can not read\", name) print(\"please input your file name again: \") name = input(\"what is your filename?:\")# resize the imagebasewidth = 100wpercent = (basewidth/float(img.size[0]))hsize = int((float(img.size[1])*float(wpercent)))img = img.resize((basewidth,hsize), Image.ANTIALIAS)# convert the image into an array object# I also convert the image into a pandas DataFrame because I'm going to convert it into an excel fileimport numpy as nparr = np.array(img)arr_container = np.empty((arr.shape[0], arr.shape[1]), dtype=np.str)import pandas as pddf = pd.DataFrame(arr_container)# convert the R,G,B into hexadecimal# populate the DataFrame with the hexadecimal valuefor l,x in enumerate(arr): for m,y in enumerate(x): r,g,b = arr[l][m] hexval = '%02x%02x%02x' % (r, g, b) df[m][l] = hexval# save it! yeay!save_file_name = input(\"your excel file name, without '.xlsx' please: \")df.to_excel(str(save_file_name) + \".xlsx\")print(\"success!! now colour the file\")" }, { "code": null, "e": 4698, "s": 4557, "text": "The source code for the VBA can be found here. basically, the code colours the cell every time the cell is typed a hexadecimal colour value." }, { "code": null, "e": 4971, "s": 4698, "text": "open the excel file resultadd the VBA code into the sheet (copy the code from below)copy all cell, and paste into the same location (the cell will be coloured automatically) (ctrl + a, ctrl + c, ctrl + v)delete all cell values (ctrl + a, delete)adjust the column sizevoila" }, { "code": null, "e": 4998, "s": 4971, "text": "open the excel file result" }, { "code": null, "e": 5057, "s": 4998, "text": "add the VBA code into the sheet (copy the code from below)" }, { "code": null, "e": 5178, "s": 5057, "text": "copy all cell, and paste into the same location (the cell will be coloured automatically) (ctrl + a, ctrl + c, ctrl + v)" }, { "code": null, "e": 5220, "s": 5178, "text": "delete all cell values (ctrl + a, delete)" }, { "code": null, "e": 5243, "s": 5220, "text": "adjust the column size" }, { "code": null, "e": 5249, "s": 5243, "text": "voila" }, { "code": null, "e": 5769, "s": 5249, "text": "Private Sub Worksheet_Change(ByVal Target As Range) On Error GoTo bm_Safe_Exit Application.EnableEvents = False Dim rng As Range, clr As String For Each rng In Target If Len(rng.Value2) = 6 Then clr = rng.Value2 rng.Interior.Color = _ RGB(Application.Hex2Dec(Left(clr, 2)), _ Application.Hex2Dec(Mid(clr, 3, 2)), _ Application.Hex2Dec(Right(clr, 2))) End If Next rngbm_Safe_Exit: Application.EnableEvents = TrueEnd Sub" } ]
WPF - Debugging
It is a systematic mechanism of identifying and fixing the bugs or defects in a piece of code which are not behaving the same as you are expecting. Debugging a complex application where the subsystems are tightly coupled are not that easy, because fixing bugs in one subsystem can create bugs in another subsystem. In WPF applications, programmers deal with two languages such as C# and XAML. If you are familiar with debugging in any procedural language such as C# or C/C++ and you also know the usage of break points, then you can debug the C# part of your application easily. Let’s take a simple example to demonstrate how to debug a C# code. Create a new WPF project with the name WPFDebuggingDemo. Drag four labels, three textboxes, and one button from the toolbox. Take a look at the following XAML code. <Window x:Class = "WPFDebuggingDemo.Window1" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "Window1" Height = "400" Width = "604"> <Grid> <TextBox Height = "23" Margin = "0,44,169,0" Name = "textBox1" VerticalAlignment = "Top" HorizontalAlignment = "Right" Width = "120" /> <TextBox Height = "23" Margin = "0,99,169,0" Name = "textBox2" VerticalAlignment = "Top" HorizontalAlignment = "Right" Width = "120" /> <TextBox HorizontalAlignment = "Right" Margin = "0,153,169,0" Name = "textBox3" Width = "120" Height = "23" VerticalAlignment = "Top" /> <Label Height = "28" Margin = "117,42,0,0" Name = "label1" VerticalAlignment = "Top" HorizontalAlignment = "Left" Width = "120"> Item 1</Label> <Label Height = "28" HorizontalAlignment = "Left" Margin = "117,99,0,0" Name = "label2" VerticalAlignment = "Top" Width = "120"> Item 2</Label> <Label HorizontalAlignment = "Left" Margin = "117,153,0,181" Name = "label3" Width = "120">Item 3</Label> <Button Height = "23" HorizontalAlignment = "Right" Margin = "0,0,214,127" Name = "button1" VerticalAlignment = "Bottom" Width = "75" Click = "button1_Click">Total</Button> <Label Height = "28" HorizontalAlignment = "Right" Margin = "0,0,169,66" Name = "label4" VerticalAlignment = "Bottom" Width = "120"/> </Grid> </Window> Given below is the C# code in which a button click event is implemented. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPFDebuggingDemo { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void button1_Click(object sender, RoutedEventArgs e) { if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0 && textBox2.Text.Length > 0) { double total = Convert.ToDouble(textBox1.Text) + Convert.ToDouble(textBox2.Text) + Convert.ToDouble(textBox3.Text); label4.Content = total.ToString(); } else { MessageBox.Show("Enter the value in all field."); } } } } When you compile and execute the above code, it will produce the following window. Now enter values in the textboxes and press the Total button. You will get the total value after summation of all the values entered in the textboxes. If you try to enter values other than real values, then the above application will crash. To find and resolve the issue (why it is crashing), you can insert break points in the button click event. Let’s write "abc" in item 1 as shown below. Upon clicking the Total button, you will see that the program stops at the break point. Now move the cursor towards the textbox1.Text and you will see that the program is trying to add abc value with the other values which is why the program is crashing. If you are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug the XAML code like debugging any other procedural language code. When you hear the term debugging in XAML code, it means try and find an error. In data binding, your data doesn't show up on screen and you don't know why In data binding, your data doesn't show up on screen and you don't know why Or an issue is related to complex layouts. Or an issue is related to complex layouts. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Debugging an XAML program is something you typically do to check if your bindings work; and if it is not working, then to check what's wrong. Unfortunately setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's take a look at the following XAML code to find the error in data binding. <Window x:Class = "DataBindingOneWay.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <Grid> <StackPanel Name = "Display"> <StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0"> <TextBlock Text = "Name: " Margin = "10" Width = "100"/> <TextBlock Margin = "10" Width = "100" Text = "{Binding FirstName}"/> </StackPanel> <StackPanel Orientation = "Horizontal" Margin = "50,0,50,0"> <TextBlock Text = "Title: " Margin = "10" Width = "100"/> <TextBlock Margin = "10" Width = "100" Text = "{Binding Title}" /> </StackPanel> </StackPanel> </Grid> </Window> Text properties of two text blocks are set to “Name” and “Title” statically, while other two text blocks Text properties are bind to “FirstName” and “Title” but class variables are Name and Title in Employee class which is shown below. We have intentionally written an incorrect variable name so as to understand where can we find this type of a mistake when the desired output is not shown. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataBindingOneWay { public class Employee { public string Name { get; set; } public string Title { get; set; } public static Employee GetEmployee() { var emp = new Employee() { Name = "Ali Ahmed", Title = "Developer" }; return emp; } } } Here is the implementation of MainWindow class in C# code. using System; using System.Windows; using System.Windows.Controls; namespace DataBindingOneWay { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = Employee.GetEmployee(); } } } Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound. To check what happened with the name, let’s look into the output window where a lot of log is generated. The easy to find an error is just to search for the error and you will find the following error which says “BindingExpression path error: 'FirstName' property not found on 'object' ''Employe” System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Employee' (HashCode=11611730)'. BindingExpression:Path = FirstName; DataItem = 'Employee' (HashCode = 11611730); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application. When you change the FirstName to Name again, then you will see the desired output. UI debugging tools were introduced for XAML with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of a visual tree of your running WPF application and also the different UI element properties in the tree. To enable these tools, follow the steps given below. Go to the Tools menu and select Options from the Tools menu. It will open the following dialog box. Go to the General Options under Debugging item on the left side. Tick the highlighted option, i.e., “Enable UI Debugging Tools for XAML” and click the OK button. Now run any XAML application or use the following XAML code. <Window x:Class = "XAMLTestBinding.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "604"> <StackPanel> <ComboBox Name = "comboBox" Margin = "50" Width = "100"> <ComboBoxItem Content = "Green" /> <ComboBoxItem Content = "Yellow" IsSelected = "True" /> <ComboBoxItem Content = "Orange" /> </ComboBox> <TextBox Name = "textBox" Margin = "50" Width = "100" Height = "23" VerticalAlignment = "Top" Text = "{Binding ElementName = comboBox, Path = SelectedItem.Content, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" Background = "{Binding ElementName = comboBox, Path = SelectedItem.Content}"> </TextBox> </StackPanel> </Window> When you execute the application, it will show the Live Visual Tree where all the elements are shown in a tree. This Live Visual Tree shows the complete layout structure to understand where the UI elements are located. But this option is only available in Visual Studio 2015. If you are using an older option of Visual Studio, then you can’t use this tool, however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from xamlspy 31 Lectures 2.5 hours Anadi Sharma 30 Lectures 2.5 hours Taurius Litvinavicius Print Add Notes Bookmark this page
[ { "code": null, "e": 2335, "s": 2020, "text": "It is a systematic mechanism of identifying and fixing the bugs or defects in a piece of code which are not behaving the same as you are expecting. Debugging a complex application where the subsystems are tightly coupled are not that easy, because fixing bugs in one subsystem can create bugs in another subsystem." }, { "code": null, "e": 2599, "s": 2335, "text": "In WPF applications, programmers deal with two languages such as C# and XAML. If you are familiar with debugging in any procedural language such as C# or C/C++ and you also know the usage of break points, then you can debug the C# part of your application easily." }, { "code": null, "e": 2831, "s": 2599, "text": "Let’s take a simple example to demonstrate how to debug a C# code. Create a new WPF project with the name WPFDebuggingDemo. Drag four labels, three textboxes, and one button from the toolbox. Take a look at the following XAML code." }, { "code": null, "e": 4411, "s": 2831, "text": "<Window x:Class = \"WPFDebuggingDemo.Window1\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"Window1\" Height = \"400\" Width = \"604\"> \n\t\n <Grid> \n <TextBox Height = \"23\" Margin = \"0,44,169,0\" Name = \"textBox1\" \n VerticalAlignment = \"Top\" HorizontalAlignment = \"Right\" Width = \"120\" /> \n\t\t\t\n <TextBox Height = \"23\" Margin = \"0,99,169,0\" Name = \"textBox2\" \n VerticalAlignment = \"Top\" HorizontalAlignment = \"Right\" Width = \"120\" /> \n\t\t\t\n <TextBox HorizontalAlignment = \"Right\" Margin = \"0,153,169,0\" \n Name = \"textBox3\" Width = \"120\" Height = \"23\" VerticalAlignment = \"Top\" /> \n\t\t\t\n <Label Height = \"28\" Margin = \"117,42,0,0\" Name = \"label1\" \n VerticalAlignment = \"Top\" HorizontalAlignment = \"Left\" Width = \"120\">\n Item 1</Label> \n\t\t\t\n <Label Height = \"28\" HorizontalAlignment = \"Left\" \n Margin = \"117,99,0,0\" Name = \"label2\" VerticalAlignment = \"Top\" Width = \"120\">\n Item 2</Label> \n\t\t\t\n <Label HorizontalAlignment = \"Left\" Margin = \"117,153,0,181\" \n Name = \"label3\" Width = \"120\">Item 3</Label>\n\t\t\t\n <Button Height = \"23\" HorizontalAlignment = \"Right\" Margin = \"0,0,214,127\"\n Name = \"button1\" VerticalAlignment = \"Bottom\" Width = \"75\" \n Click = \"button1_Click\">Total</Button> \n\t\t\t\n <Label Height = \"28\" HorizontalAlignment = \"Right\" \n Margin = \"0,0,169,66\" Name = \"label4\" VerticalAlignment = \"Bottom\" Width = \"120\"/> \n\t\t\t\n </Grid> \n\t\n</Window>" }, { "code": null, "e": 4484, "s": 4411, "text": "Given below is the C# code in which a button click event is implemented." }, { "code": null, "e": 5560, "s": 4484, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text;\n \nusing System.Windows; \nusing System.Windows.Controls; \nusing System.Windows.Data; \nusing System.Windows.Documents; \nusing System.Windows.Input; \nusing System.Windows.Media; \nusing System.Windows.Media.Imaging; \nusing System.Windows.Navigation; \nusing System.Windows.Shapes; \n\nnamespace WPFDebuggingDemo { \n /// <summary> \n /// Interaction logic for Window1.xaml \n /// </summary> \n\t\n public partial class Window1 : Window { \n\t\n public Window1() {\n InitializeComponent();\n }\n\t\t\n private void button1_Click(object sender, RoutedEventArgs e) {\n\t\t\n if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0 && textBox2.Text.Length > 0) {\n double total = Convert.ToDouble(textBox1.Text) + \n Convert.ToDouble(textBox2.Text) + Convert.ToDouble(textBox3.Text); \n label4.Content = total.ToString(); \n } \n else { \n MessageBox.Show(\"Enter the value in all field.\");\n } \n } \n } \n}" }, { "code": null, "e": 5794, "s": 5560, "text": "When you compile and execute the above code, it will produce the following window. Now enter values in the textboxes and press the Total button. You will get the total value after summation of all the values entered in the textboxes." }, { "code": null, "e": 5991, "s": 5794, "text": "If you try to enter values other than real values, then the above application will crash. To find and resolve the issue (why it is crashing), you can insert break points in the button click event." }, { "code": null, "e": 6035, "s": 5991, "text": "Let’s write \"abc\" in item 1 as shown below." }, { "code": null, "e": 6123, "s": 6035, "text": "Upon clicking the Total button, you will see that the program stops at the break point." }, { "code": null, "e": 6290, "s": 6123, "text": "Now move the cursor towards the textbox1.Text and you will see that the program is trying to add abc value with the other values which is why the program is crashing." }, { "code": null, "e": 6563, "s": 6290, "text": "If you are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug the XAML code like debugging any other procedural language code. When you hear the term debugging in XAML code, it means try and find an error." }, { "code": null, "e": 6639, "s": 6563, "text": "In data binding, your data doesn't show up on screen and you don't know why" }, { "code": null, "e": 6715, "s": 6639, "text": "In data binding, your data doesn't show up on screen and you don't know why" }, { "code": null, "e": 6758, "s": 6715, "text": "Or an issue is related to complex layouts." }, { "code": null, "e": 6801, "s": 6758, "text": "Or an issue is related to complex layouts." }, { "code": null, "e": 6923, "s": 6801, "text": "Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box." }, { "code": null, "e": 7045, "s": 6923, "text": "Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box." }, { "code": null, "e": 7423, "s": 7045, "text": "Debugging an XAML program is something you typically do to check if your bindings work; and if it is not working, then to check what's wrong. Unfortunately setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's take a look at the following XAML code to find the error in data binding." }, { "code": null, "e": 8261, "s": 7423, "text": "<Window x:Class = \"DataBindingOneWay.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <Grid> \n <StackPanel Name = \"Display\"> \n <StackPanel Orientation = \"Horizontal\" Margin = \"50, 50, 0, 0\"> \n <TextBlock Text = \"Name: \" Margin = \"10\" Width = \"100\"/> \n <TextBlock Margin = \"10\" Width = \"100\" Text = \"{Binding FirstName}\"/> \n </StackPanel> \n\t\t\t\n <StackPanel Orientation = \"Horizontal\" Margin = \"50,0,50,0\"> \n <TextBlock Text = \"Title: \" Margin = \"10\" Width = \"100\"/> \n <TextBlock Margin = \"10\" Width = \"100\" Text = \"{Binding Title}\" /> \n </StackPanel> \n\t\t\t\n </StackPanel> \n </Grid> \n\t\n</Window>" }, { "code": null, "e": 8497, "s": 8261, "text": "Text properties of two text blocks are set to “Name” and “Title” statically, while other two text blocks Text properties are bind to “FirstName” and “Title” but class variables are Name and Title in Employee class which is shown below." }, { "code": null, "e": 8653, "s": 8497, "text": "We have intentionally written an incorrect variable name so as to understand where can we find this type of a mistake when the desired output is not shown." }, { "code": null, "e": 9118, "s": 8653, "text": "using System; \nusing System.Collections.Generic; \nusing System.Linq; \nusing System.Text; \nusing System.Threading.Tasks; \n\nnamespace DataBindingOneWay { \n\n public class Employee { \n public string Name { get; set; } \n public string Title { get; set; } \n\t\t\n public static Employee GetEmployee() { \n\t\t\n var emp = new Employee() { \n Name = \"Ali Ahmed\", Title = \"Developer\" \n }; \n\t\t\t\n return emp; \n } \n } \n} " }, { "code": null, "e": 9177, "s": 9118, "text": "Here is the implementation of MainWindow class in C# code." }, { "code": null, "e": 9544, "s": 9177, "text": "using System; \nusing System.Windows; \nusing System.Windows.Controls; \n \nnamespace DataBindingOneWay { \n /// <summary> \n /// Interaction logic for MainWindow.xaml\n /// </summary> \n\t\n public partial class MainWindow : Window { \n\t\n public MainWindow() { \n InitializeComponent(); \n DataContext = Employee.GetEmployee(); \n } \n } \n} " }, { "code": null, "e": 9713, "s": 9544, "text": "Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound." }, { "code": null, "e": 9818, "s": 9713, "text": "To check what happened with the name, let’s look into the output window where a lot of log is generated." }, { "code": null, "e": 10010, "s": 9818, "text": "The easy to find an error is just to search for the error and you will find the following error which says “BindingExpression path error: 'FirstName' property not found on 'object' ''Employe”" }, { "code": null, "e": 10322, "s": 10010, "text": "System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName'\n property not found on 'object' ''Employee' (HashCode=11611730)'.\n BindingExpression:Path = FirstName; DataItem = 'Employee' (HashCode = 11611730);\n target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String')" }, { "code": null, "e": 10455, "s": 10322, "text": "Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application." }, { "code": null, "e": 10538, "s": 10455, "text": "When you change the FirstName to Name again, then you will see the desired output." }, { "code": null, "e": 10868, "s": 10538, "text": "UI debugging tools were introduced for XAML with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of a visual tree of your running WPF application and also the different UI element properties in the tree. To enable these tools, follow the steps given below." }, { "code": null, "e": 10929, "s": 10868, "text": "Go to the Tools menu and select Options from the Tools menu." }, { "code": null, "e": 10968, "s": 10929, "text": "It will open the following dialog box." }, { "code": null, "e": 11033, "s": 10968, "text": "Go to the General Options under Debugging item on the left side." }, { "code": null, "e": 11130, "s": 11033, "text": "Tick the highlighted option, i.e., “Enable UI Debugging Tools for XAML” and click the OK button." }, { "code": null, "e": 11191, "s": 11130, "text": "Now run any XAML application or use the following XAML code." }, { "code": null, "e": 12076, "s": 11191, "text": "<Window x:Class = \"XAMLTestBinding.MainWindow\" \n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" \n Title = \"MainWindow\" Height = \"350\" Width = \"604\"> \n\t\n <StackPanel> \n <ComboBox Name = \"comboBox\" Margin = \"50\" Width = \"100\"> \n <ComboBoxItem Content = \"Green\" /> \n <ComboBoxItem Content = \"Yellow\" IsSelected = \"True\" />\n <ComboBoxItem Content = \"Orange\" /> \n </ComboBox> \n\t\t\n <TextBox Name = \"textBox\" Margin = \"50\" Width = \"100\" Height = \"23\"\n VerticalAlignment = \"Top\" Text =\n \"{Binding ElementName = comboBox, Path = SelectedItem.Content, Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}\" \n Background = \"{Binding ElementName = comboBox, Path = SelectedItem.Content}\"> \n </TextBox> \n\t\t\n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 12188, "s": 12076, "text": "When you execute the application, it will show the Live Visual Tree where all the elements are shown in a tree." }, { "code": null, "e": 12575, "s": 12188, "text": "This Live Visual Tree shows the complete layout structure to understand where the UI elements are located. But this option is only available in Visual Studio 2015. If you are using an older option of Visual Studio, then you can’t use this tool, however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from xamlspy" }, { "code": null, "e": 12610, "s": 12575, "text": "\n 31 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12624, "s": 12610, "text": " Anadi Sharma" }, { "code": null, "e": 12659, "s": 12624, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 12682, "s": 12659, "text": " Taurius Litvinavicius" }, { "code": null, "e": 12689, "s": 12682, "text": " Print" }, { "code": null, "e": 12700, "s": 12689, "text": " Add Notes" } ]
Geoparsing with Python and Natural Language Processing | by Abdishakur | Towards Data Science
The massive amount of available text data has location features that can benefit from automated Information extraction. Natural Language Processing(NLP) has significantly advanced in the last five years. However, advances in Geographic information extraction from text is still in its nascency. In this tutorial, we use Python and NLP to Geoparse twitter dataset. Geoparsing is a toponym resolution process of converting free-text descriptions of places (such as “Two kilometres east of London”) into geographic identifiers (coordinates with latitude and longitude). Geoparsing is essential in many applications, including Geographic Information Retrieval (GIR), Geographic Information Extraction (GIE) and Geographic Information Analysis (GIA) tasks. We can use Geoparsing to determine a document’s geographic scope, decoding locational information for disaster response, business news analysis, as well as other multiple domains. To illustrate what geoparsing is, let us consider this satire headline example. “Protesters Steal NYC Sanitation Trucks, Use Them To Block Trump Tower” Typically, geoparsing contains two components: toponym recognition and toponym resolution. First, is the toponym extraction or recognition [NYC, Trump Tower]. The next step is linking toponyms to geographic coordinates [(40.768121, -73.981895), (40.762347, -73.973848)]. In the next section, we move into Geoparsing simple text with Mordecai, a Python Geoparsing library. For this tutorial, we will use Mordecai library for geoparsing. Mordecai is Full-text geoparsing Python library. With this library, you can extract the place names from a piece of text, resolve them to the correct place, and return their coordinates and structured geographic information. Let us start with a simple Geoparsing example. Mordecai Python Geoparsing library has Geoparse function that takes a text and returns structured geographic information from the text. from mordecai import Geoparsergeo = Geoparser()geo.geoparse(“Eiffel Tower is located in Paris”) With any text input, Mordecai returns the locational features present in the text. In this example, it predicts correctly both the Eiffel tower as well as the city of Paris. Interestingly, the latitude and longitude associated with these two locations differ. The Eiffel tower coordinates predicted are more specific than the city of Paris. [{'word': 'Eiffel Tower', 'spans': [{'start': 0, 'end': 12}], 'country_predicted': 'FRA', 'country_conf': 0.611725, 'geo': {'admin1': 'Île-de-France', 'lat': '48.85832', 'lon': '2.29452', 'country_code3': 'FRA', 'geonameid': '6254976', 'place_name': 'Tour Eiffel', 'feature_class': 'S', 'feature_code': 'MNMT'}}, {'word': 'Paris', 'spans': [{'start': 27, 'end': 32}], 'country_predicted': 'FRA', 'country_conf': 0.9881995, 'geo': {'admin1': 'Île-de-France', 'lat': '48.85339', 'lon': '2.34864', 'country_code3': 'FRA', 'geonameid': '2988506', 'place_name': 'Paris', 'feature_class': 'A', 'feature_code': 'ADM3'}}] Mordecai Python library takes different steps to achieve this result. First, it uses spaCy’s named entity recognition to extract place names from the text. Then, it uses Geonames gazetteer to find the potential coordinates for the place name. The final process uses neural networks to predict the country and placename from the gazetteer entries. To Geoparse tweets, first, we set up Tweepy API to scrape hashtags. The following piece of code takes a hashtag (#BlackLivesMatter) to scrape with Tweepy and saves all tweets from the hashtag into a local CSV file. scraping tweets with Tweepy Let us read the tweets CSV with Pandas and look at the first few columns. df = pd.read_csv(“tweets.csv”, header=None, names=[“date”, “tweet”])df.head() The data frame holds now the date of the tweet and the text. Let us use Mordecai Geoparsing functionality to extract locational information and assign coordinates. We set up this function that takes a data frame and results in a clean data frame with additional locational information from the geoparsing. Our clean dataset now has extracted place names and assigned coordinates to each place name in the tweet text with predictions and confidence level of the prediction. To plot the geographic extent of the #BlackLivesMatter hashtag extracted with Mordecai Geoparsing Python library, we can use now any of your favourite Geospatial data visualization python libraries. I am using Plotly Express to plot the data. fig = px.scatter_mapbox(df_clean, lat=”lat”, lon=”lon”, size_max=15, zoom=1, width=1000, height=800, mapbox_style=”dark”)fig.data[0].marker = dict(size = 5, color=”red”)fig Geoparsing is an essential component in automating location feature extraction from text. In this tutorial, we have seen how to Geoparse text, using Mordecai Geoparsing Python Library. To run Geoparsing with Mordecai, you need to install it. You also need to have a running docker container. You can find the installation instructions here. The code for this tutorial is available in this Jupyter Notebook.
[ { "code": null, "e": 536, "s": 172, "text": "The massive amount of available text data has location features that can benefit from automated Information extraction. Natural Language Processing(NLP) has significantly advanced in the last five years. However, advances in Geographic information extraction from text is still in its nascency. In this tutorial, we use Python and NLP to Geoparse twitter dataset." }, { "code": null, "e": 739, "s": 536, "text": "Geoparsing is a toponym resolution process of converting free-text descriptions of places (such as “Two kilometres east of London”) into geographic identifiers (coordinates with latitude and longitude)." }, { "code": null, "e": 924, "s": 739, "text": "Geoparsing is essential in many applications, including Geographic Information Retrieval (GIR), Geographic Information Extraction (GIE) and Geographic Information Analysis (GIA) tasks." }, { "code": null, "e": 1104, "s": 924, "text": "We can use Geoparsing to determine a document’s geographic scope, decoding locational information for disaster response, business news analysis, as well as other multiple domains." }, { "code": null, "e": 1184, "s": 1104, "text": "To illustrate what geoparsing is, let us consider this satire headline example." }, { "code": null, "e": 1256, "s": 1184, "text": "“Protesters Steal NYC Sanitation Trucks, Use Them To Block Trump Tower”" }, { "code": null, "e": 1527, "s": 1256, "text": "Typically, geoparsing contains two components: toponym recognition and toponym resolution. First, is the toponym extraction or recognition [NYC, Trump Tower]. The next step is linking toponyms to geographic coordinates [(40.768121, -73.981895), (40.762347, -73.973848)]." }, { "code": null, "e": 1628, "s": 1527, "text": "In the next section, we move into Geoparsing simple text with Mordecai, a Python Geoparsing library." }, { "code": null, "e": 1917, "s": 1628, "text": "For this tutorial, we will use Mordecai library for geoparsing. Mordecai is Full-text geoparsing Python library. With this library, you can extract the place names from a piece of text, resolve them to the correct place, and return their coordinates and structured geographic information." }, { "code": null, "e": 2100, "s": 1917, "text": "Let us start with a simple Geoparsing example. Mordecai Python Geoparsing library has Geoparse function that takes a text and returns structured geographic information from the text." }, { "code": null, "e": 2196, "s": 2100, "text": "from mordecai import Geoparsergeo = Geoparser()geo.geoparse(“Eiffel Tower is located in Paris”)" }, { "code": null, "e": 2537, "s": 2196, "text": "With any text input, Mordecai returns the locational features present in the text. In this example, it predicts correctly both the Eiffel tower as well as the city of Paris. Interestingly, the latitude and longitude associated with these two locations differ. The Eiffel tower coordinates predicted are more specific than the city of Paris." }, { "code": null, "e": 3189, "s": 2537, "text": "[{'word': 'Eiffel Tower', 'spans': [{'start': 0, 'end': 12}], 'country_predicted': 'FRA', 'country_conf': 0.611725, 'geo': {'admin1': 'Île-de-France', 'lat': '48.85832', 'lon': '2.29452', 'country_code3': 'FRA', 'geonameid': '6254976', 'place_name': 'Tour Eiffel', 'feature_class': 'S', 'feature_code': 'MNMT'}}, {'word': 'Paris', 'spans': [{'start': 27, 'end': 32}], 'country_predicted': 'FRA', 'country_conf': 0.9881995, 'geo': {'admin1': 'Île-de-France', 'lat': '48.85339', 'lon': '2.34864', 'country_code3': 'FRA', 'geonameid': '2988506', 'place_name': 'Paris', 'feature_class': 'A', 'feature_code': 'ADM3'}}]" }, { "code": null, "e": 3536, "s": 3189, "text": "Mordecai Python library takes different steps to achieve this result. First, it uses spaCy’s named entity recognition to extract place names from the text. Then, it uses Geonames gazetteer to find the potential coordinates for the place name. The final process uses neural networks to predict the country and placename from the gazetteer entries." }, { "code": null, "e": 3751, "s": 3536, "text": "To Geoparse tweets, first, we set up Tweepy API to scrape hashtags. The following piece of code takes a hashtag (#BlackLivesMatter) to scrape with Tweepy and saves all tweets from the hashtag into a local CSV file." }, { "code": null, "e": 3779, "s": 3751, "text": "scraping tweets with Tweepy" }, { "code": null, "e": 3853, "s": 3779, "text": "Let us read the tweets CSV with Pandas and look at the first few columns." }, { "code": null, "e": 3931, "s": 3853, "text": "df = pd.read_csv(“tweets.csv”, header=None, names=[“date”, “tweet”])df.head()" }, { "code": null, "e": 4237, "s": 3931, "text": "The data frame holds now the date of the tweet and the text. Let us use Mordecai Geoparsing functionality to extract locational information and assign coordinates. We set up this function that takes a data frame and results in a clean data frame with additional locational information from the geoparsing." }, { "code": null, "e": 4404, "s": 4237, "text": "Our clean dataset now has extracted place names and assigned coordinates to each place name in the tweet text with predictions and confidence level of the prediction." }, { "code": null, "e": 4647, "s": 4404, "text": "To plot the geographic extent of the #BlackLivesMatter hashtag extracted with Mordecai Geoparsing Python library, we can use now any of your favourite Geospatial data visualization python libraries. I am using Plotly Express to plot the data." }, { "code": null, "e": 4820, "s": 4647, "text": "fig = px.scatter_mapbox(df_clean, lat=”lat”, lon=”lon”, size_max=15, zoom=1, width=1000, height=800, mapbox_style=”dark”)fig.data[0].marker = dict(size = 5, color=”red”)fig" }, { "code": null, "e": 5005, "s": 4820, "text": "Geoparsing is an essential component in automating location feature extraction from text. In this tutorial, we have seen how to Geoparse text, using Mordecai Geoparsing Python Library." }, { "code": null, "e": 5161, "s": 5005, "text": "To run Geoparsing with Mordecai, you need to install it. You also need to have a running docker container. You can find the installation instructions here." } ]
Map get() method in Java with Examples - GeeksforGeeks
31 Dec, 2018 The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key. Syntax: thisMap.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched. Return Value: The method returns the value associated with the key_element in this Map collection. Below programs illustrates the working of java.util.Map.get() method: Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the get() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, "Geeks"); map.put(15, "4"); map.put(20, "Geeks"); map.put(25, "Welcomes"); map.put(30, "You"); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Getting the value of 25 System.out.println("The Value is: " + map.get(25)); // Getting the value of 10 System.out.println("The Value is: " + map.get(10)); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} The Value is: Welcomes The Value is: Geeks Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the get() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put("Geeks", 10); map.put("4", 15); map.put("Geeks", 20); map.put("Welcomes", 25); map.put("You", 30); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Getting the value of "Geeks" System.out.println("The Value is: " + map.get("Geeks")); // Getting the value of "You" System.out.println("The Value is: " + map.get("You")); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} The Value is: 20 The Value is: 30 Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#get(java.lang.Object) Java-Collections Java-Functions java-map Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Singleton Class in Java Stack Class in Java Multithreading in Java LinkedList in Java Collections in Java
[ { "code": null, "e": 24306, "s": 24278, "text": "\n31 Dec, 2018" }, { "code": null, "e": 24509, "s": 24306, "text": "The get() method of Map interface in Java is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key." }, { "code": null, "e": 24517, "s": 24509, "text": "Syntax:" }, { "code": null, "e": 24549, "s": 24517, "text": "thisMap.get(Object key_element)" }, { "code": null, "e": 24690, "s": 24549, "text": "Parameter: The method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched." }, { "code": null, "e": 24789, "s": 24690, "text": "Return Value: The method returns the value associated with the key_element in this Map collection." }, { "code": null, "e": 24859, "s": 24789, "text": "Below programs illustrates the working of java.util.Map.get() method:" }, { "code": null, "e": 24909, "s": 24859, "text": "Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the get() methodimport java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, \"Geeks\"); map.put(15, \"4\"); map.put(20, \"Geeks\"); map.put(25, \"Welcomes\"); map.put(30, \"You\"); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Getting the value of 25 System.out.println(\"The Value is: \" + map.get(25)); // Getting the value of 10 System.out.println(\"The Value is: \" + map.get(10)); }}", "e": 25616, "s": 24909, "text": null }, { "code": null, "e": 25730, "s": 25616, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nThe Value is: Welcomes\nThe Value is: Geeks\n" }, { "code": null, "e": 25780, "s": 25730, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the get() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put(\"Geeks\", 10); map.put(\"4\", 15); map.put(\"Geeks\", 20); map.put(\"Welcomes\", 25); map.put(\"You\", 30); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Getting the value of \"Geeks\" System.out.println(\"The Value is: \" + map.get(\"Geeks\")); // Getting the value of \"You\" System.out.println(\"The Value is: \" + map.get(\"You\")); }}", "e": 26505, "s": 25780, "text": null }, { "code": null, "e": 26600, "s": 26505, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nThe Value is: 20\nThe Value is: 30\n" }, { "code": null, "e": 26724, "s": 26600, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 26818, "s": 26724, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#get(java.lang.Object)" }, { "code": null, "e": 26835, "s": 26818, "text": "Java-Collections" }, { "code": null, "e": 26850, "s": 26835, "text": "Java-Functions" }, { "code": null, "e": 26859, "s": 26850, "text": "java-map" }, { "code": null, "e": 26864, "s": 26859, "text": "Java" }, { "code": null, "e": 26869, "s": 26864, "text": "Java" }, { "code": null, "e": 26886, "s": 26869, "text": "Java-Collections" }, { "code": null, "e": 26984, "s": 26886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26993, "s": 26984, "text": "Comments" }, { "code": null, "e": 27006, "s": 26993, "text": "Old Comments" }, { "code": null, "e": 27038, "s": 27006, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27089, "s": 27038, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27108, "s": 27089, "text": "Interfaces in Java" }, { "code": null, "e": 27126, "s": 27108, "text": "ArrayList in Java" }, { "code": null, "e": 27158, "s": 27126, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 27182, "s": 27158, "text": "Singleton Class in Java" }, { "code": null, "e": 27202, "s": 27182, "text": "Stack Class in Java" }, { "code": null, "e": 27225, "s": 27202, "text": "Multithreading in Java" }, { "code": null, "e": 27244, "s": 27225, "text": "LinkedList in Java" } ]
Correlation and Regression in Python
Correlation refers to some statistical relationships involving dependence between two data sets. While linear regression is a linear approach to establish the relationship between a dependent variable and one or more independent variables. A single independent variable is called linear regression whereas multiple independent variables is called multiple regression. Simple examples of dependent phenomena include the correlation between the physical appearance of parents and their offspring, and the correlation between the price for a product and its supplied quantity.We take example of the iris data set available in seaborn python library. In it we try to establish the correlation between the length and the width of the sepals and petals of three species of iris flower. Based on the correlation found, a strong model could be created which easily distinguishes one species from another. import matplotlib.pyplot as plt import seaborn as sns df = sns.load_dataset('iris') #without regression sns.pairplot(df, kind="scatter") plt.show() Running the above code gives us the following result − Mathematically a linear relationship represents a straight line when plotted as a graph. A non-linear relationship where the exponent of any variable is not equal to 1 creates a curve. The functions in Seaborn to find the linear regression relationship is regplot. The below example shows its use. import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('tips') sb.regplot(x = "total_bill", y = "tip", data = df) plt.show() Running the above code gives us the following result −
[ { "code": null, "e": 1430, "s": 1062, "text": "Correlation refers to some statistical relationships involving dependence between two data sets. While linear regression is a linear approach to establish the relationship between a dependent variable and one or more independent variables. A single independent variable is called linear regression whereas multiple independent variables is called multiple regression." }, { "code": null, "e": 1959, "s": 1430, "text": "Simple examples of dependent phenomena include the correlation between the physical appearance of parents and their offspring, and the correlation between the price for a product and its supplied quantity.We take example of the iris data set available in seaborn python library. In it we try to establish the correlation between the length and the width of the sepals and petals of three species of iris flower. Based on the correlation found, a strong model could be created which easily distinguishes one species from another." }, { "code": null, "e": 2107, "s": 1959, "text": "import matplotlib.pyplot as plt\nimport seaborn as sns\ndf = sns.load_dataset('iris')\n#without regression\nsns.pairplot(df, kind=\"scatter\")\nplt.show()" }, { "code": null, "e": 2162, "s": 2107, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2460, "s": 2162, "text": "Mathematically a linear relationship represents a straight line when plotted as a graph. A non-linear relationship where the exponent of any variable is not equal to 1 creates a curve.\nThe functions in Seaborn to find the linear regression relationship is regplot. The below example shows its use." }, { "code": null, "e": 2609, "s": 2460, "text": "import seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('tips')\nsb.regplot(x = \"total_bill\", y = \"tip\", data = df)\nplt.show()" }, { "code": null, "e": 2664, "s": 2609, "text": "Running the above code gives us the following result −" } ]
Design a Contact us Page using HTML and CSS - GeeksforGeeks
21 Feb, 2022 In this article, we will see how to design a Contact us page using HTML and CSS. Creating an attractive page may seem to be difficult for, who don’t know HTML and CSS. If someone does not know using CSS, then they will not be able to make the page look better or attractive. So the main focus of this article will be on the implementation of CSS. Creating structure: In this section, we will create a simple structure of a web page by using some tags like <li> and <section>. So this will help us to create a simple web page which we can check by running the following code. HTML <!DOCTYPE html><html> <head> <title>Contact Us page</title> <link rel="stylesheet" href="styles.css"></head> <body> <nav class="navbar background"> <!-- Creating the list of items --> <ul class="nav-list"> <li><a href="#Home">Home</a></li> <li><a href="#Topics">Topics</a></li> <li><a href="#ContactUs">Contact Us</a></li> <li><a href="#AboutUs">About Us</a></li> </ul> <!-- Create the search bar and the button--> <div class="rightNav"> <input type="text" name="search" id="search"> <button class="btn btn-sm">Search</button> </div> </nav> <section class="background firstsection"> <div class="box-main"> <div class="firstHalf"> <p class="text-big">Contact Us</p> <p class="text-small"> You can Contact Us if you face any problem </p> <br> <p class="center" style="text-decoration:none; color:white;"> Click on the below options to Contact us </p> </div> </div> </section> <section class="service"> <!-- Heading--> <h1 class="h-primary center" style="margin-top:30px;"> Options to Contact </h1> <div id="service"> <div class="box"> <!-- Form --> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211220070335/color.png" alt= "color_image"> <br> <!-- Displaying text at the center of the box--> <p class="center"> People can fill up the form and send us the problem </p> </div> <div class="box"> <!-- Email --> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211220070335/color.png" alt= "color_image"> <br> <!-- Displaying text at the center of the box--> <p class="center"> Use this Email to send us about the problem faced </p> </div> <div class="box"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20211220070335/color.png" alt= "color_image"> <br> <!-- Displaying text at the center of the box--> <p class="center"> Toll Free Number:+1800 200 300 400 </p> </div> </div> </section> <footer class="background"> <p class="text-footer"> Copyright @-All rights are reserved </p> </footer></body> </html> CSS Design: We will use CSS to design the simple interface page. Here the interesting part for creating this page is using the same background for the navbar and the background of the web page. In the footer also, we will use the same background by using the class that we have used for giving background images to the webpage and navbar. Another interesting of the webpage is that the navbar is fixed at one point, So When the user will scroll the webpage they will find the navbar to be fixed in one place. CSS * { margin: 0; padding: 0;} html { scroll-behaviour: smooth;} :root { --navbar-height: 59px;} .logo { width: 20%; display: flex; justify-content: center; align-items: center;} .logo img { width: 33%; border: 2px solid white; border-radius: 50px;} .navbar { display: flex; align-items: center; justify-content: center; position: sticky; top: 0; cursor: pointer;} .nav-list { width: 70%; display: flex;} .nav-list li { list-style: none; padding: 2px 6px;} .nav-list li a { text-decoration: none; color: white;} .nav-list li a:hover { color: grey;} .rightNav { width: 50; text-align: right;} #search { padding: 5px; font-size: 17px; border: 2px solid grey; border-radius: 9px;} .background { background-color: grey; background-blend-mode: darken; background-size: cover;} .firstsection { height: 100vh;} .box-main { display: flex; justify-content: center; align-items: center; color: white; max-width: 50%; margin: auto; height: 80%;} .firstHalf { width: 75%; display: flex; flex-direction: column; justify-content: center;} .firstHalf img { display: flex; border-radius: 9050px;} .text-big { font-family: "Piazzolla", serif; font-weight: bold; font-size: 41px; text-align: center;} .text-small { font-family: "Sansita Swashed", cursive; font-size: 18px; text-align: center;} #service { margin: 34px; display: flex;} #service .box { padding: 45px; margin: 3px 6px; border-radius: 28px;} #service .box img { margin-top: 20px; height: 100px; margin: auto; display: block; border-radius: 200px;} #service .box p { font-family: sans-serif; text-align: center;} .btn { padding: 8px 20px; margin: 7px 0; border: 2px solid white; border-radius: 8px; background: none; color: white; cursor: pointer;} .btn-sm { padding: 6px 10px; vertical-align: middle;} .center { text-align: center;} .text-footer { text-align: center; padding: 30px 0; font-family: "Ubuntu", sans-serif; display: flex; justify-content: center;} Combining the above two sections of code to make a contact us page using HTML and CSS. Output: Homepage Various available options to contact Supported Browser to run the code: Google Chrome Microsoft Edge Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ysachin2314 bhaskargeeksforgeeks CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to Create Time-Table schedule using HTML ? How to set the default value for an HTML <select> element ? 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)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n21 Feb, 2022" }, { "code": null, "e": 25723, "s": 25376, "text": "In this article, we will see how to design a Contact us page using HTML and CSS. Creating an attractive page may seem to be difficult for, who don’t know HTML and CSS. If someone does not know using CSS, then they will not be able to make the page look better or attractive. So the main focus of this article will be on the implementation of CSS." }, { "code": null, "e": 25743, "s": 25723, "text": "Creating structure:" }, { "code": null, "e": 25951, "s": 25743, "text": "In this section, we will create a simple structure of a web page by using some tags like <li> and <section>. So this will help us to create a simple web page which we can check by running the following code." }, { "code": null, "e": 25956, "s": 25951, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Contact Us page</title> <link rel=\"stylesheet\" href=\"styles.css\"></head> <body> <nav class=\"navbar background\"> <!-- Creating the list of items --> <ul class=\"nav-list\"> <li><a href=\"#Home\">Home</a></li> <li><a href=\"#Topics\">Topics</a></li> <li><a href=\"#ContactUs\">Contact Us</a></li> <li><a href=\"#AboutUs\">About Us</a></li> </ul> <!-- Create the search bar and the button--> <div class=\"rightNav\"> <input type=\"text\" name=\"search\" id=\"search\"> <button class=\"btn btn-sm\">Search</button> </div> </nav> <section class=\"background firstsection\"> <div class=\"box-main\"> <div class=\"firstHalf\"> <p class=\"text-big\">Contact Us</p> <p class=\"text-small\"> You can Contact Us if you face any problem </p> <br> <p class=\"center\" style=\"text-decoration:none; color:white;\"> Click on the below options to Contact us </p> </div> </div> </section> <section class=\"service\"> <!-- Heading--> <h1 class=\"h-primary center\" style=\"margin-top:30px;\"> Options to Contact </h1> <div id=\"service\"> <div class=\"box\"> <!-- Form --> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211220070335/color.png\" alt= \"color_image\"> <br> <!-- Displaying text at the center of the box--> <p class=\"center\"> People can fill up the form and send us the problem </p> </div> <div class=\"box\"> <!-- Email --> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211220070335/color.png\" alt= \"color_image\"> <br> <!-- Displaying text at the center of the box--> <p class=\"center\"> Use this Email to send us about the problem faced </p> </div> <div class=\"box\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20211220070335/color.png\" alt= \"color_image\"> <br> <!-- Displaying text at the center of the box--> <p class=\"center\"> Toll Free Number:+1800 200 300 400 </p> </div> </div> </section> <footer class=\"background\"> <p class=\"text-footer\"> Copyright @-All rights are reserved </p> </footer></body> </html>", "e": 28971, "s": 25956, "text": null }, { "code": null, "e": 29480, "s": 28971, "text": "CSS Design: We will use CSS to design the simple interface page. Here the interesting part for creating this page is using the same background for the navbar and the background of the web page. In the footer also, we will use the same background by using the class that we have used for giving background images to the webpage and navbar. Another interesting of the webpage is that the navbar is fixed at one point, So When the user will scroll the webpage they will find the navbar to be fixed in one place." }, { "code": null, "e": 29484, "s": 29480, "text": "CSS" }, { "code": "* { margin: 0; padding: 0;} html { scroll-behaviour: smooth;} :root { --navbar-height: 59px;} .logo { width: 20%; display: flex; justify-content: center; align-items: center;} .logo img { width: 33%; border: 2px solid white; border-radius: 50px;} .navbar { display: flex; align-items: center; justify-content: center; position: sticky; top: 0; cursor: pointer;} .nav-list { width: 70%; display: flex;} .nav-list li { list-style: none; padding: 2px 6px;} .nav-list li a { text-decoration: none; color: white;} .nav-list li a:hover { color: grey;} .rightNav { width: 50; text-align: right;} #search { padding: 5px; font-size: 17px; border: 2px solid grey; border-radius: 9px;} .background { background-color: grey; background-blend-mode: darken; background-size: cover;} .firstsection { height: 100vh;} .box-main { display: flex; justify-content: center; align-items: center; color: white; max-width: 50%; margin: auto; height: 80%;} .firstHalf { width: 75%; display: flex; flex-direction: column; justify-content: center;} .firstHalf img { display: flex; border-radius: 9050px;} .text-big { font-family: \"Piazzolla\", serif; font-weight: bold; font-size: 41px; text-align: center;} .text-small { font-family: \"Sansita Swashed\", cursive; font-size: 18px; text-align: center;} #service { margin: 34px; display: flex;} #service .box { padding: 45px; margin: 3px 6px; border-radius: 28px;} #service .box img { margin-top: 20px; height: 100px; margin: auto; display: block; border-radius: 200px;} #service .box p { font-family: sans-serif; text-align: center;} .btn { padding: 8px 20px; margin: 7px 0; border: 2px solid white; border-radius: 8px; background: none; color: white; cursor: pointer;} .btn-sm { padding: 6px 10px; vertical-align: middle;} .center { text-align: center;} .text-footer { text-align: center; padding: 30px 0; font-family: \"Ubuntu\", sans-serif; display: flex; justify-content: center;}", "e": 31630, "s": 29484, "text": null }, { "code": null, "e": 31717, "s": 31630, "text": "Combining the above two sections of code to make a contact us page using HTML and CSS." }, { "code": null, "e": 31725, "s": 31717, "text": "Output:" }, { "code": null, "e": 31734, "s": 31725, "text": "Homepage" }, { "code": null, "e": 31771, "s": 31734, "text": "Various available options to contact" }, { "code": null, "e": 31806, "s": 31771, "text": "Supported Browser to run the code:" }, { "code": null, "e": 31820, "s": 31806, "text": "Google Chrome" }, { "code": null, "e": 31835, "s": 31820, "text": "Microsoft Edge" }, { "code": null, "e": 31843, "s": 31835, "text": "Firefox" }, { "code": null, "e": 31849, "s": 31843, "text": "Opera" }, { "code": null, "e": 31856, "s": 31849, "text": "Safari" }, { "code": null, "e": 31993, "s": 31856, "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": 32005, "s": 31993, "text": "ysachin2314" }, { "code": null, "e": 32026, "s": 32005, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 32035, "s": 32026, "text": "CSS-Misc" }, { "code": null, "e": 32045, "s": 32035, "text": "HTML-Misc" }, { "code": null, "e": 32049, "s": 32045, "text": "CSS" }, { "code": null, "e": 32054, "s": 32049, "text": "HTML" }, { "code": null, "e": 32071, "s": 32054, "text": "Web Technologies" }, { "code": null, "e": 32098, "s": 32071, "text": "Web technologies Questions" }, { "code": null, "e": 32103, "s": 32098, "text": "HTML" }, { "code": null, "e": 32201, "s": 32103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32238, "s": 32201, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 32267, "s": 32238, "text": "Form validation using jQuery" }, { "code": null, "e": 32306, "s": 32267, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32348, "s": 32306, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 32395, "s": 32348, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 32455, "s": 32395, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32516, "s": 32455, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 32569, "s": 32516, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 32619, "s": 32569, "text": "How to Insert Form Data into Database using PHP ?" } ]
MariaDB - Delete Query
The DELETE command deletes table rows from the specified table, and returns the quantity deleted. Access the quantity deleted with the ROW_COUNT() function. A WHERE clause specifies rows, and in its absence, all rows are deleted. A LIMIT clause controls the number of rows deleted. In a DELETE statement for multiple rows, it deletes only those rows satisfying a condition; and LIMIT and WHERE clauses are not permitted. DELETE statements allow deleting rows from tables in different databases, but do not allow deleting from a table and then selecting from the same table within a subquery. Review the following DELETE syntax − DELETE FROM table_name [WHERE ...] Execute a DELETE command from either the command prompt or using a PHP script. At the command prompt, simply use a standard command − root@host# mysql –u root –p password; Enter password:******* mysql> use PRODUCTS; Database changed mysql> DELETE FROM products_tbl WHERE product_id=133; mysql> SELECT * from products_tbl WHERE ID_number='133'; ERROR 1032 (HY000): Can't find record in 'products_tbl' Use the mysql_query() function in DELETE command statements − <?php $dbhost = 'localhost:3036'; $dbuser = 'root'; $dbpass = 'rootpassword'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'DELETE FROM products_tbl WHERE product_id = 261'; mysql_select_db('PRODUCTS'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not delete data: ' . mysql_error()); } echo "Deleted data successfully\n"; mysql_close($conn); ?> On successful data deletion, you will see the following output − mysql> Deleted data successfully mysql> SELECT * from products_tbl WHERE ID_number='261'; ERROR 1032 (HY000): Can't find record in 'products_tbl' Print Add Notes Bookmark this page
[ { "code": null, "e": 2644, "s": 2362, "text": "The DELETE command deletes table rows from the specified table, and returns the quantity deleted. Access the quantity deleted with the ROW_COUNT() function. A WHERE clause specifies rows, and in its absence, all rows are deleted. A LIMIT clause controls the number of rows deleted." }, { "code": null, "e": 2954, "s": 2644, "text": "In a DELETE statement for multiple rows, it deletes only those rows satisfying a condition; and LIMIT and WHERE clauses are not permitted. DELETE statements allow deleting rows from tables in different databases, but do not allow deleting from a table and then selecting from the same table within a subquery." }, { "code": null, "e": 2991, "s": 2954, "text": "Review the following DELETE syntax −" }, { "code": null, "e": 3027, "s": 2991, "text": "DELETE FROM table_name [WHERE ...]\n" }, { "code": null, "e": 3106, "s": 3027, "text": "Execute a DELETE command from either the command prompt or using a PHP script." }, { "code": null, "e": 3161, "s": 3106, "text": "At the command prompt, simply use a standard command −" }, { "code": null, "e": 3428, "s": 3161, "text": "root@host# mysql –u root –p password;\nEnter password:*******\nmysql> use PRODUCTS;\nDatabase changed\nmysql> DELETE FROM products_tbl WHERE product_id=133;\nmysql> SELECT * from products_tbl WHERE ID_number='133';\nERROR 1032 (HY000): Can't find record in 'products_tbl'\n" }, { "code": null, "e": 3490, "s": 3428, "text": "Use the mysql_query() function in DELETE command statements −" }, { "code": null, "e": 3988, "s": 3490, "text": "<?php\n $dbhost = 'localhost:3036';\n $dbuser = 'root';\n $dbpass = 'rootpassword';\n $conn = mysql_connect($dbhost, $dbuser, $dbpass);\n \n if(! $conn ) {\n die('Could not connect: ' . mysql_error());\n }\n\n $sql = 'DELETE FROM products_tbl WHERE product_id = 261';\n mysql_select_db('PRODUCTS');\n $retval = mysql_query( $sql, $conn );\n\n if(! $retval ) {\n die('Could not delete data: ' . mysql_error());\n }\n\n echo \"Deleted data successfully\\n\";\n mysql_close($conn);\n?>" }, { "code": null, "e": 4053, "s": 3988, "text": "On successful data deletion, you will see the following output −" }, { "code": null, "e": 4200, "s": 4053, "text": "mysql> Deleted data successfully\nmysql> SELECT * from products_tbl WHERE ID_number='261';\nERROR 1032 (HY000): Can't find record in 'products_tbl'\n" }, { "code": null, "e": 4207, "s": 4200, "text": " Print" }, { "code": null, "e": 4218, "s": 4207, "text": " Add Notes" } ]
C Program to Minimum and Maximum prime numbers in an array
Given an array of n positive integers. We have to find the prime number with minimum and maximum value. If the given array is − arr [] = {10, 4, 1, 12, 13, 7, 6, 2, 27, 33} then minimum prime number is 2 and maximum prime number is 13 1. Find maximum number from given number. Let us call it maxNumber 2. Generate prime numbers from 1 to maxNumber and store them in a dynamic array 3. Iterate input array and use dynamic array to find prime number with minimum and maximum value #include <iostream> #include <vector> #include <climit> #define SIZE(arr) (sizeof(arr) / sizeof(arr[0])) using namespace std; void printMinAndMaxPrimes(int *arr, int n){ int maxNumber = *max_element(arr, arr + n); vector<bool> primes(maxNumber + 1, true); primes[0] = primes[1] = false; for (int p = 2; p * p <= maxNumber; ++i) { if (primes[p]) { for (int i = p * 2; i <= maxNumber; i += p) { primes[p] = false; } } } int minPrime = INT_MAX; int maxPrime = INT_MIN; for (int i = 0; i < n; ++i) { if (primes[arr[i]]) { minPrime = min(minPrime, arr[i]); maxPrime = max(maxPrime, arr[i]); } } cout << "Prime number of min value = " << minPrime << "\n"; cout << "Prime number of max value = " << maxPrime << "\n"; } int main(){ int arr [] = {10, 4, 1, 12, 13, 7, 6, 2, 27, 33}; printMinAndMaxPrimes(arr, SIZE(arr)); return 0; } When you compile and execute the above program. It generates the following output − Prime number of min value = 2 Prime number of max value = 13
[ { "code": null, "e": 1166, "s": 1062, "text": "Given an array of n positive integers. We have to find the prime\nnumber with minimum and maximum value." }, { "code": null, "e": 1190, "s": 1166, "text": "If the given array is −" }, { "code": null, "e": 1297, "s": 1190, "text": "arr [] = {10, 4, 1, 12, 13, 7, 6, 2, 27, 33}\nthen minimum prime number is 2 and maximum prime number is 13" }, { "code": null, "e": 1541, "s": 1297, "text": "1. Find maximum number from given number. Let us call it maxNumber\n2. Generate prime numbers from 1 to maxNumber and store them in a dynamic array\n3. Iterate input array and use dynamic array to find prime number with minimum and maximum value" }, { "code": null, "e": 2479, "s": 1541, "text": "#include <iostream>\n#include <vector>\n#include <climit>\n#define SIZE(arr) (sizeof(arr) / sizeof(arr[0]))\nusing namespace std;\nvoid printMinAndMaxPrimes(int *arr, int n){\n int maxNumber = *max_element(arr, arr + n);\n vector<bool> primes(maxNumber + 1, true);\n primes[0] = primes[1] = false;\n for (int p = 2; p * p <= maxNumber; ++i) {\n if (primes[p]) {\n for (int i = p * 2; i <= maxNumber; i += p) {\n primes[p] = false;\n }\n }\n }\n int minPrime = INT_MAX;\n int maxPrime = INT_MIN;\n for (int i = 0; i < n; ++i) {\n if (primes[arr[i]]) {\n minPrime = min(minPrime, arr[i]);\n maxPrime = max(maxPrime, arr[i]);\n }\n }\n cout << \"Prime number of min value = \" << minPrime << \"\\n\";\n cout << \"Prime number of max value = \" << maxPrime << \"\\n\";\n}\nint main(){\n int arr [] = {10, 4, 1, 12, 13, 7, 6, 2, 27, 33};\n printMinAndMaxPrimes(arr, SIZE(arr));\n return 0;\n}" }, { "code": null, "e": 2563, "s": 2479, "text": "When you compile and execute the above program. It generates the following output −" }, { "code": null, "e": 2624, "s": 2563, "text": "Prime number of min value = 2\nPrime number of max value = 13" } ]
Master the when and how of Pandas pivot_table() | Towards Data Science
Here is the worst-case scenario: You are watching a paid course and the instructor is talking about a certain topic. Then, all of sudden, he introduces a completely new function saying “This function/method is perfect in this case, it is very easy so just check out its documentation for more details”. You say OK, go to the documentation, and don’t even know what you are looking at. You feel frustrated, go to read some articles or StackOverflow threads, and sometimes come back feeling even worse. Believe me, that happens to everyone. This article is specifically about the case of hard pandas functions. Mostly, the reason why most sources do not cover some advanced functions of pandas is that they are very case-specific. When you learn the basic methods and functions, you learn them in their own context like on toy datasets. For harder functions, they are difficult to explain, and would be hard to create the context they are useful in. Such functions are often in the toolbox of more experienced scientists. They make the difference where you use them in such a way that the function solves the problem you are having with one line of code so elegantly. This post is about the three of them: pivot_table(), stack() and unstack(). 1. Introduction 2. Setup 3. Pandas pivot_table(), with comparison to groupby() 4. Pandas stack() 5. Pandas unstack() I hyperlinked the documentation for each function at their first appearance. Check them out for more details. There should be one — and preferably only one — obvious way to do it. The above is a quote from the Zen of python. Python wants to have only one obvious solution for a single problem. But, pandas deliberately avoids this. Often in pandas, there are several ways to do one operation. pivot_table() is an example. It is a complete and sometimes a better alternative to groupby() function. The difference is the shape of the result. groupby() returns a Series object while pivot_table() gives an easy-to-work dataframe. Let’s work on a problem and give the solutions using both functions. I will load the tips dataset from seaborn: tips = sns.load_dataset('tips')tips.head() We want to find the sum of all bills for each gender: Let’s compare the syntax of the two functions. In groupby(), we pass the column we want to group by in the parentheses and in pivot_table() the equivalent parameter is the index. In groupby(), to choose the column to aggregate, we use subsetting with brackets while in pivot_table() we pass it to values. Finally, to choose the aggregating function, we use method chaining in groupby() whereas, pivot_table() provides aggfunc argument. When I wrote an article about project setup for DS and ML, I researched a lot of notebooks. What I found surprising was that many people used groupby() and used .reset_index() function to turn the results of groupby() into a dataframe, let's explore further to find out why: result = tips.groupby('sex')['total_bill'].sum().reset_index()result If you use the pivot_table() you don't have to use reset_index() to convert the result into a dataframe. groupby() results are not as easy to work with as dataframes. Let's see how to group by multiple columns and aggregate with multiple functions: tips.groupby(['sex', 'day'])['total_bill']\ .agg([np.mean, np.median, np.sum]).reset_index() tips.pivot_table(values='total_bill', index=['sex', 'day'], aggfunc=[np.mean, np.median, np.sum]) Both functions return a dataframe for multiple columns. But, even though for a single column pivot_table() is better, using the reset_index() on the groupby result gives a much nicer dataframe. Maybe that's why Kagglers prefer groupby(). In pivot_table(), sometimes you can use columns parameter instead of index (or sometimes both) to display each group as a column. But if you pass multiple arguments to columns, the result will be a long dataframe with a single row. Another difference between groupby() and pivot_table() would be fill_value parameter. Sometimes, when you group by multiple variables, there won't be matching cells for the result. In such cases, groupby() puts NaNs but in pivot_table() you can control this behavior: tips.head() When would you want to use pivot_table()? As I said previously, it can sometimes be a better alternative for groupby(). It is also a personal preference when it comes to syntax. An obvious example would be choosing pivot_table() because it has some other parameters which are not available in groupby(). I already covered fill_value, but there are others like margins. You can learn more about it in the documentation 😁. Please, read the second part of the article to find out more differences between functions that compute grouped summary statistics: towardsdatascience.com When used, stack() returns a reshaped dataframe with a multi-level index. The inner-most levels are created by pivoting the columns of the dataframe. It is best we start with an example. I will load the cars dataset and subset it for better understanding: Let’s see how we pivot the dataframe so that the columns are now indexes: When we use the stack() function on this dataframe, the result will have multi-level indexes, name being the outer level and weight, horsepower in the inner-level: Here, the original dataframe had a single level column names. That’s why the resulting dataframe was pandas.Series rather than a dataframe. Remember that stack() function always pivots columns to the inner level index. If there are no columns left, meaning if the final data is a Series, stack() will not work. Let's try stacking the above Series: stacked_cars.stack()AttributeError: 'Series' object has no attribute 'stack' A more complex example of stack() would be when the column names are given as multi-level indexes. Let's get back to one of our pivoted tables: As you see, the column names have a two-level hierarchy. You can access a column with a multi-level name like this: Let’s use stack() on this dataframe and see what happens: multi_name.stack() Now, total_bill which is the inner-level column name became an index. You can control which column level you want to stack. Let's see how you would stack the outer level column name: multi_name.stack(level=0) As you see, using different levels gives differently-shaped dataframes. By default, level is set to 1. As the name suggests, unstack() does exactly the opposite of stack(). It takes multi-level indexed Series or a dataframe and pivots the indexes to become columns. If we unstack the stacked cars Series we will get back the original dataframe: >>> print('Unstacked Dataframe:')>>> stacked_cars.unstack()Unstacked Dataframe: Perhaps, the most obvious use case for unstacking is when we use the groupby() function. Although the process is not possible when we group by one variable, unstacking proves very useful for grouping by multiple variables. Let's get back to our tips dataset: tips.head() The result is a Series with 4-level indexes. This is not what we want. Let’s unstack so that it is easier to use: multiple_groups.unstack() The result still has multi-level indexes. That’s because unstack() works on one index-level at a time. Let's call it once more to get a dataframe with a single index level: multiple_groups.unstack().unstack() I think you already see the effect unstack() has when you use it with groupby(). Multi-level indexes are always hard to work with. Always try to avoid them unless you absolutely have to. One way you can do it is with unstack(). Although, stack() is not used often, I showed you the basic syntax and the general use so that you will have a better grasp on unstack(). This post was only about 3 functions. In the near future, I am planning to write similar articles for other functions which might be a little difficult to understand and integrate into daily use. So, stay tuned folks! Read more articles related to the topic:
[ { "code": null, "e": 556, "s": 171, "text": "Here is the worst-case scenario: You are watching a paid course and the instructor is talking about a certain topic. Then, all of sudden, he introduces a completely new function saying “This function/method is perfect in this case, it is very easy so just check out its documentation for more details”. You say OK, go to the documentation, and don’t even know what you are looking at." }, { "code": null, "e": 780, "s": 556, "text": "You feel frustrated, go to read some articles or StackOverflow threads, and sometimes come back feeling even worse. Believe me, that happens to everyone. This article is specifically about the case of hard pandas functions." }, { "code": null, "e": 1119, "s": 780, "text": "Mostly, the reason why most sources do not cover some advanced functions of pandas is that they are very case-specific. When you learn the basic methods and functions, you learn them in their own context like on toy datasets. For harder functions, they are difficult to explain, and would be hard to create the context they are useful in." }, { "code": null, "e": 1413, "s": 1119, "text": "Such functions are often in the toolbox of more experienced scientists. They make the difference where you use them in such a way that the function solves the problem you are having with one line of code so elegantly. This post is about the three of them: pivot_table(), stack() and unstack()." }, { "code": null, "e": 1531, "s": 1413, "text": "1. Introduction 2. Setup 3. Pandas pivot_table(), with comparison to groupby() 4. Pandas stack() 5. Pandas unstack()" }, { "code": null, "e": 1641, "s": 1531, "text": "I hyperlinked the documentation for each function at their first appearance. Check them out for more details." }, { "code": null, "e": 1711, "s": 1641, "text": "There should be one — and preferably only one — obvious way to do it." }, { "code": null, "e": 1924, "s": 1711, "text": "The above is a quote from the Zen of python. Python wants to have only one obvious solution for a single problem. But, pandas deliberately avoids this. Often in pandas, there are several ways to do one operation." }, { "code": null, "e": 2158, "s": 1924, "text": "pivot_table() is an example. It is a complete and sometimes a better alternative to groupby() function. The difference is the shape of the result. groupby() returns a Series object while pivot_table() gives an easy-to-work dataframe." }, { "code": null, "e": 2270, "s": 2158, "text": "Let’s work on a problem and give the solutions using both functions. I will load the tips dataset from seaborn:" }, { "code": null, "e": 2313, "s": 2270, "text": "tips = sns.load_dataset('tips')tips.head()" }, { "code": null, "e": 2367, "s": 2313, "text": "We want to find the sum of all bills for each gender:" }, { "code": null, "e": 2803, "s": 2367, "text": "Let’s compare the syntax of the two functions. In groupby(), we pass the column we want to group by in the parentheses and in pivot_table() the equivalent parameter is the index. In groupby(), to choose the column to aggregate, we use subsetting with brackets while in pivot_table() we pass it to values. Finally, to choose the aggregating function, we use method chaining in groupby() whereas, pivot_table() provides aggfunc argument." }, { "code": null, "e": 3078, "s": 2803, "text": "When I wrote an article about project setup for DS and ML, I researched a lot of notebooks. What I found surprising was that many people used groupby() and used .reset_index() function to turn the results of groupby() into a dataframe, let's explore further to find out why:" }, { "code": null, "e": 3147, "s": 3078, "text": "result = tips.groupby('sex')['total_bill'].sum().reset_index()result" }, { "code": null, "e": 3396, "s": 3147, "text": "If you use the pivot_table() you don't have to use reset_index() to convert the result into a dataframe. groupby() results are not as easy to work with as dataframes. Let's see how to group by multiple columns and aggregate with multiple functions:" }, { "code": null, "e": 3500, "s": 3396, "text": "tips.groupby(['sex', 'day'])['total_bill']\\ .agg([np.mean, np.median, np.sum]).reset_index()" }, { "code": null, "e": 3632, "s": 3500, "text": "tips.pivot_table(values='total_bill', index=['sex', 'day'], aggfunc=[np.mean, np.median, np.sum])" }, { "code": null, "e": 3870, "s": 3632, "text": "Both functions return a dataframe for multiple columns. But, even though for a single column pivot_table() is better, using the reset_index() on the groupby result gives a much nicer dataframe. Maybe that's why Kagglers prefer groupby()." }, { "code": null, "e": 4102, "s": 3870, "text": "In pivot_table(), sometimes you can use columns parameter instead of index (or sometimes both) to display each group as a column. But if you pass multiple arguments to columns, the result will be a long dataframe with a single row." }, { "code": null, "e": 4370, "s": 4102, "text": "Another difference between groupby() and pivot_table() would be fill_value parameter. Sometimes, when you group by multiple variables, there won't be matching cells for the result. In such cases, groupby() puts NaNs but in pivot_table() you can control this behavior:" }, { "code": null, "e": 4382, "s": 4370, "text": "tips.head()" }, { "code": null, "e": 4803, "s": 4382, "text": "When would you want to use pivot_table()? As I said previously, it can sometimes be a better alternative for groupby(). It is also a personal preference when it comes to syntax. An obvious example would be choosing pivot_table() because it has some other parameters which are not available in groupby(). I already covered fill_value, but there are others like margins. You can learn more about it in the documentation 😁." }, { "code": null, "e": 4935, "s": 4803, "text": "Please, read the second part of the article to find out more differences between functions that compute grouped summary statistics:" }, { "code": null, "e": 4958, "s": 4935, "text": "towardsdatascience.com" }, { "code": null, "e": 5214, "s": 4958, "text": "When used, stack() returns a reshaped dataframe with a multi-level index. The inner-most levels are created by pivoting the columns of the dataframe. It is best we start with an example. I will load the cars dataset and subset it for better understanding:" }, { "code": null, "e": 5288, "s": 5214, "text": "Let’s see how we pivot the dataframe so that the columns are now indexes:" }, { "code": null, "e": 5452, "s": 5288, "text": "When we use the stack() function on this dataframe, the result will have multi-level indexes, name being the outer level and weight, horsepower in the inner-level:" }, { "code": null, "e": 5592, "s": 5452, "text": "Here, the original dataframe had a single level column names. That’s why the resulting dataframe was pandas.Series rather than a dataframe." }, { "code": null, "e": 5800, "s": 5592, "text": "Remember that stack() function always pivots columns to the inner level index. If there are no columns left, meaning if the final data is a Series, stack() will not work. Let's try stacking the above Series:" }, { "code": null, "e": 5877, "s": 5800, "text": "stacked_cars.stack()AttributeError: 'Series' object has no attribute 'stack'" }, { "code": null, "e": 6021, "s": 5877, "text": "A more complex example of stack() would be when the column names are given as multi-level indexes. Let's get back to one of our pivoted tables:" }, { "code": null, "e": 6137, "s": 6021, "text": "As you see, the column names have a two-level hierarchy. You can access a column with a multi-level name like this:" }, { "code": null, "e": 6195, "s": 6137, "text": "Let’s use stack() on this dataframe and see what happens:" }, { "code": null, "e": 6214, "s": 6195, "text": "multi_name.stack()" }, { "code": null, "e": 6397, "s": 6214, "text": "Now, total_bill which is the inner-level column name became an index. You can control which column level you want to stack. Let's see how you would stack the outer level column name:" }, { "code": null, "e": 6423, "s": 6397, "text": "multi_name.stack(level=0)" }, { "code": null, "e": 6526, "s": 6423, "text": "As you see, using different levels gives differently-shaped dataframes. By default, level is set to 1." }, { "code": null, "e": 6768, "s": 6526, "text": "As the name suggests, unstack() does exactly the opposite of stack(). It takes multi-level indexed Series or a dataframe and pivots the indexes to become columns. If we unstack the stacked cars Series we will get back the original dataframe:" }, { "code": null, "e": 6848, "s": 6768, "text": ">>> print('Unstacked Dataframe:')>>> stacked_cars.unstack()Unstacked Dataframe:" }, { "code": null, "e": 7107, "s": 6848, "text": "Perhaps, the most obvious use case for unstacking is when we use the groupby() function. Although the process is not possible when we group by one variable, unstacking proves very useful for grouping by multiple variables. Let's get back to our tips dataset:" }, { "code": null, "e": 7119, "s": 7107, "text": "tips.head()" }, { "code": null, "e": 7233, "s": 7119, "text": "The result is a Series with 4-level indexes. This is not what we want. Let’s unstack so that it is easier to use:" }, { "code": null, "e": 7259, "s": 7233, "text": "multiple_groups.unstack()" }, { "code": null, "e": 7432, "s": 7259, "text": "The result still has multi-level indexes. That’s because unstack() works on one index-level at a time. Let's call it once more to get a dataframe with a single index level:" }, { "code": null, "e": 7468, "s": 7432, "text": "multiple_groups.unstack().unstack()" }, { "code": null, "e": 7696, "s": 7468, "text": "I think you already see the effect unstack() has when you use it with groupby(). Multi-level indexes are always hard to work with. Always try to avoid them unless you absolutely have to. One way you can do it is with unstack()." }, { "code": null, "e": 7834, "s": 7696, "text": "Although, stack() is not used often, I showed you the basic syntax and the general use so that you will have a better grasp on unstack()." }, { "code": null, "e": 8052, "s": 7834, "text": "This post was only about 3 functions. In the near future, I am planning to write similar articles for other functions which might be a little difficult to understand and integrate into daily use. So, stay tuned folks!" } ]
Extending CloudFormation using lambda-backed custom resources | by Harry Daniels | Towards Data Science
This article is split into two parts: Background on CloudFormation and an introduction to Custom Resources. Monitoring as Code: Managing Datadog monitors with CloudFormation. If you’d like to skip ahead, all the code discussed in this post is available on my GitHub HERE. CloudFormation is a fantastic ‘infrastructure as code’ offering from AWS which allows you to efficiently model a collection of resources and manage them throughout their lifecycles. The AWS ‘Spaghetti Bowl’ continues to grow at a rate of knots, meaning even CloudFormation cannot keep up with them all, but do not fear as we’re able to plug any gaps and more using custom resources. Infrastructure as code is the new normal when it comes to the cloud, it gives you an insight into how your environment came to be and the confidence to update your stack without causing any critical errors. Examples include CloudFormation and Terraform. CloudFormation provides a common language to describe and provision all infrastructure in your cloud environment, it provisions resources in a repeatable manner, and since everything is written as code can be version controlled. CloudFormation provisions and configures resources by making calls to the AWS services that are described in your template. After all the resources have been created, it reports that your stack has been created and is ready for use. If stack creation fails, CloudFormation rolls back your changes. Sometimes you’ll want to do something that isn’t supported out of the box by CloudFormation, this could be a manual step post deployment or even provision some infrastructure outside the AWS ecosystem. Fortunately, custom resources make this very easy to do. Custom resources enable you to write custom provisioning logic in templates that AWS CloudFormation runs anytime you create, update or delete a stack. If a Custom Resource has been defined in your template, CloudFormation will send an external request to the resource provider endpoint during a stack operation and wait for a response. Data from the response can subsequently be used to provision and configure other resources. A custom resource can be defined in your Cloudformation template as follows: CustomResource: Type: 'Custom::MyCustomResourceTypeName' Properties: ServiceToken: RequestAddress var1: variable1 var2: variable2 Custom resources only require one property: ServiceToken, which will tell Cloudformation where to send the request, however additional properties can also be included. For lambda-backed Custom resources the ServiceToken will be the lambda Arn and Cloudformation will send a request in the form of an event. An example request is shown below: { "RequestType": "Create", "ServiceToken": "lambda-arn", "ResponseURL": "http://pre-signed-S3-url-for-response", "StackId": "cloudformation-stack-id", "RequestId": "request-id", "LogicalResourceId": "CustomResource", "ResourceType": "Custom::MyCustomResourceTypeName", "ResourceProperties": { "ServiceToken": "lambda-arn", "var1": "variable1", "var2": "variable2" }} Once a request has been sent, Cloudformation will wait for a response in the pre-signed URL: ResponseURL. The RequestType can be either Create, Update or Delete depending on the type of operation. The Custom resource provider will process the request, perform whatever task you require, and return a response of SUCCESS or FAILED to the pre-signed URL. If a no response or a Failed status is returned the CloudFormation operation will fail and rollback. { "Status": "SUCCESS", "PhysicalResourceId": "function-return-value", "StackId": "cloudformation-stack-id", "RequestId": "request-id", "LogicalResourceId": "CustomResource", "Data": { "out1": "output1", "out2": "output2" }} Any values included in the Data field are stored in the pre-signed url location and can be referenced in the template using the !GetAtt function. To retrieve the out1 value from the above output, you would use the following command: !GetAtt CustomResource.out1 . When a lambda is used as a custom resource provider, the function is invoked whenever the custom resource is created, updated or deleted. CloudFormation invokes the function with the request data (as above) and waits for a response. Fortunately, there are a number of libraries that make writing custom resources very easy. The one I will be using is the custom-resource-helper: a Python-based library provided by AWS that uses decorators. The Custom Resource Helper is a wonderful package which drastically reduces the complexity of deploying lambda-backed custom resources. The code below can be used as a starting point for lambda development. It can be broken down into the following bullet points: First the CfnResource class is imported. A CfnResource object is instantiated and called helper. The create, update and delete decorators determine which function will be invoked for the difference CloudFormation stack actions. The resource properties, which are defined in the CloudFormation template are available in the ResourceProperties object within the lambda event. Anything saved in the Data object in the helper object can be referenced by other resources in the CloudFormation template using the !Get Att intrinsic function. Upon each successful execution of the functions, the helper object takes care of uploading the response to the ResponseUrl as defined in the lambda event. To truly demonstrate some of the benefits of CloudFormation custom resources, I’ve included a walkthrough of how you might use them to provision monitors in Datadog to send alerts if any of your resources fail. The example below only monitor for failed lambda invocations. The prerequisites to this walkthrough are as follows: All the resources in this post have been deployed using the AWS SAM CLI. To follow along, the CLI must be installed and the config file: samconfig.toml must be defined in the root of your project. version=0.1 [default.deploy.parameters] profile = "personal" stack_name = "datadog-monitor-dev" s3_bucket = "custom-resources-dev-20200318" s3_prefix = "datadog" region = "eu-west-1" capabilities = "CAPABILITY_IAM" confirm_changeset = true tags = "project=\"datadog-monitor-dev\" stage=\"dev\"" Setup the AWS Services integration in your Datadog account and ensure that the lambda tile is selected. This enables Datadog to collect Amazon lambda metrics. Once completed all lambda functions will be available in the Datadog serverless view. Retrieve the DataDog API key and create an Application key. These must be stored in AWS secrets manager as follows, you can choose any name for the secrets which is added to the CF template as a parameter: { "DD_CLIENT_API_KEY": "API KEY", "DD_CLIENT_APP_KEY": "APP KEY"} Datadog has a HTTP REST API that allows you to interact with the platform programmatically. The API has been used in the code below to create the Monitor class which will be used by the custom resource lambda. The code below has been summarised into the following key points: The base url of the API is: https://api.datadoghq.eu/api/v1 To authenticate calls to the API, the datadog API key and Application Key must be provided in the request headers. The keys are used to initialise the class object. The class has three methods to create, update and delete Datadog monitors, and one helper method to construct a simple monitor query. The create_monitor method takes the following arguments: name, message, priority, functionname and tags. The name is simply the name of the monitor as it appears in the Datadog UI. The message is what gets sent with each alert. The priority indicates the severity of the alert. The functionname is used by the _create_query method to construct a simple monitor query and the tags are used to tag the monitor. After a monitor is created its monitor_id is returned. The _create_query method uses the functionname argument to create a monitor query which checks for any lambda errors within the last hour. The update_monitor method takes all the same arguments as the create_monitor method, except with the addition of the monitor_id so it knows which monitor to update. The delete_monitor method uses the monitor_id to delete the monitor. Using the Datadog Monitor class and also the Custom resource skeleton code defined above, it is now possible to create a Custom resource which can create, update and manage Datadog monitors in tandem with CloudFormation stack operations. As mentioned in the prerequisites, the Datadog API and App keys are stored in AWS secrets manager. These are retrieved using the aws_lambda_powertools package. The CfnResource and DD_monitor objects are created. The create_monitor method is called within the create function which is executed when the stack is first created; as indicated by the @helper.create decorator. The required arguments are defined in the CloudFormation template and available in the ResourceProperties field in the event object. The update_monitor and delete_monitor methods are called within the update and delete function respectively. Both the create and delete functions return the monitor_id which will be assigned as the physical id of the resource. The test lambda is the lambda which will be monitored in Datadog. The lambda will only be used to generate some successful and failed invocation metrics. With the all the lambdas now defined, the next step is to create the CloudFormation (SAM) template to deploy them all. The template explicitly defines three resources, the DataDogMonitorLambda, aTestLambda, and the TestLambdaDDMonitor . The DataDogMonitorLambda is the lambda function that will be called by the custom resource. This is evident as the ServiceToken in the custom resource points to the DataDogMonitorLambda Arn. The TestLambda is the lambda that will be monitored. The TestLambdaDDMonitor is the Datadog monitor that is created by invoking the DataDogMonitorLambda. The arguments required to create the monitor are passed as additional properties. To deploy the stack with SAM, execute the following commands: sam build --use-container sam deploy Check everything looks right in the changeset and press y to continue with the deployment. Once the stack creation is complete, all the resources will have both Logical and Physical IDs. Since the create function in the Custom Resource lambda returns the monitor_id of the Datadog monitor it just created, this is set as the resource Physical ID. The monitor can be viewed in Datadog at the following address: https://datadoghq.eu/monitors/{MonitorID}. Initially the Datadog monitor will have no data as shown below, this is because the monitor requires either successful or failed lambda executions. The easiest way to generate some data is to manually invoke the TestLambda in the AWS UI. Since the monitor only checks for failed invocations each hour, its best to invoke the lambda successfully a few times and wait for the data to populate in Datadog and then cause the lambda to fail. Finally, if the monitor is working as expected, after a failed lambda execution, it should remain in an alert state. I hope you enjoyed reading this post as much as I enjoyed writing it. The simplicity of Lambda Functions and Custom Resources really open up the possibilities of CloudFormation. I’m planning on writing another article of how you might use Custom Resources to manage your Snowflake account, so watch this space! Checkout my other engineering posts: Connecting to an ec2 instance in a private subnet on AWS
[ { "code": null, "e": 210, "s": 172, "text": "This article is split into two parts:" }, { "code": null, "e": 280, "s": 210, "text": "Background on CloudFormation and an introduction to Custom Resources." }, { "code": null, "e": 347, "s": 280, "text": "Monitoring as Code: Managing Datadog monitors with CloudFormation." }, { "code": null, "e": 444, "s": 347, "text": "If you’d like to skip ahead, all the code discussed in this post is available on my GitHub HERE." }, { "code": null, "e": 827, "s": 444, "text": "CloudFormation is a fantastic ‘infrastructure as code’ offering from AWS which allows you to efficiently model a collection of resources and manage them throughout their lifecycles. The AWS ‘Spaghetti Bowl’ continues to grow at a rate of knots, meaning even CloudFormation cannot keep up with them all, but do not fear as we’re able to plug any gaps and more using custom resources." }, { "code": null, "e": 1081, "s": 827, "text": "Infrastructure as code is the new normal when it comes to the cloud, it gives you an insight into how your environment came to be and the confidence to update your stack without causing any critical errors. Examples include CloudFormation and Terraform." }, { "code": null, "e": 1608, "s": 1081, "text": "CloudFormation provides a common language to describe and provision all infrastructure in your cloud environment, it provisions resources in a repeatable manner, and since everything is written as code can be version controlled. CloudFormation provisions and configures resources by making calls to the AWS services that are described in your template. After all the resources have been created, it reports that your stack has been created and is ready for use. If stack creation fails, CloudFormation rolls back your changes." }, { "code": null, "e": 1867, "s": 1608, "text": "Sometimes you’ll want to do something that isn’t supported out of the box by CloudFormation, this could be a manual step post deployment or even provision some infrastructure outside the AWS ecosystem. Fortunately, custom resources make this very easy to do." }, { "code": null, "e": 2372, "s": 1867, "text": "Custom resources enable you to write custom provisioning logic in templates that AWS CloudFormation runs anytime you create, update or delete a stack. If a Custom Resource has been defined in your template, CloudFormation will send an external request to the resource provider endpoint during a stack operation and wait for a response. Data from the response can subsequently be used to provision and configure other resources. A custom resource can be defined in your Cloudformation template as follows:" }, { "code": null, "e": 2524, "s": 2372, "text": "CustomResource: Type: 'Custom::MyCustomResourceTypeName' Properties: ServiceToken: RequestAddress var1: variable1 var2: variable2" }, { "code": null, "e": 2866, "s": 2524, "text": "Custom resources only require one property: ServiceToken, which will tell Cloudformation where to send the request, however additional properties can also be included. For lambda-backed Custom resources the ServiceToken will be the lambda Arn and Cloudformation will send a request in the form of an event. An example request is shown below:" }, { "code": null, "e": 3281, "s": 2866, "text": "{ \"RequestType\": \"Create\", \"ServiceToken\": \"lambda-arn\", \"ResponseURL\": \"http://pre-signed-S3-url-for-response\", \"StackId\": \"cloudformation-stack-id\", \"RequestId\": \"request-id\", \"LogicalResourceId\": \"CustomResource\", \"ResourceType\": \"Custom::MyCustomResourceTypeName\", \"ResourceProperties\": { \"ServiceToken\": \"lambda-arn\", \"var1\": \"variable1\", \"var2\": \"variable2\" }}" }, { "code": null, "e": 3735, "s": 3281, "text": "Once a request has been sent, Cloudformation will wait for a response in the pre-signed URL: ResponseURL. The RequestType can be either Create, Update or Delete depending on the type of operation. The Custom resource provider will process the request, perform whatever task you require, and return a response of SUCCESS or FAILED to the pre-signed URL. If a no response or a Failed status is returned the CloudFormation operation will fail and rollback." }, { "code": null, "e": 3994, "s": 3735, "text": "{ \"Status\": \"SUCCESS\", \"PhysicalResourceId\": \"function-return-value\", \"StackId\": \"cloudformation-stack-id\", \"RequestId\": \"request-id\", \"LogicalResourceId\": \"CustomResource\", \"Data\": { \"out1\": \"output1\", \"out2\": \"output2\" }}" }, { "code": null, "e": 4257, "s": 3994, "text": "Any values included in the Data field are stored in the pre-signed url location and can be referenced in the template using the !GetAtt function. To retrieve the out1 value from the above output, you would use the following command: !GetAtt CustomResource.out1 ." }, { "code": null, "e": 4697, "s": 4257, "text": "When a lambda is used as a custom resource provider, the function is invoked whenever the custom resource is created, updated or deleted. CloudFormation invokes the function with the request data (as above) and waits for a response. Fortunately, there are a number of libraries that make writing custom resources very easy. The one I will be using is the custom-resource-helper: a Python-based library provided by AWS that uses decorators." }, { "code": null, "e": 4960, "s": 4697, "text": "The Custom Resource Helper is a wonderful package which drastically reduces the complexity of deploying lambda-backed custom resources. The code below can be used as a starting point for lambda development. It can be broken down into the following bullet points:" }, { "code": null, "e": 5057, "s": 4960, "text": "First the CfnResource class is imported. A CfnResource object is instantiated and called helper." }, { "code": null, "e": 5188, "s": 5057, "text": "The create, update and delete decorators determine which function will be invoked for the difference CloudFormation stack actions." }, { "code": null, "e": 5334, "s": 5188, "text": "The resource properties, which are defined in the CloudFormation template are available in the ResourceProperties object within the lambda event." }, { "code": null, "e": 5496, "s": 5334, "text": "Anything saved in the Data object in the helper object can be referenced by other resources in the CloudFormation template using the !Get Att intrinsic function." }, { "code": null, "e": 5651, "s": 5496, "text": "Upon each successful execution of the functions, the helper object takes care of uploading the response to the ResponseUrl as defined in the lambda event." }, { "code": null, "e": 5924, "s": 5651, "text": "To truly demonstrate some of the benefits of CloudFormation custom resources, I’ve included a walkthrough of how you might use them to provision monitors in Datadog to send alerts if any of your resources fail. The example below only monitor for failed lambda invocations." }, { "code": null, "e": 5978, "s": 5924, "text": "The prerequisites to this walkthrough are as follows:" }, { "code": null, "e": 6175, "s": 5978, "text": "All the resources in this post have been deployed using the AWS SAM CLI. To follow along, the CLI must be installed and the config file: samconfig.toml must be defined in the root of your project." }, { "code": null, "e": 6470, "s": 6175, "text": "version=0.1 [default.deploy.parameters] profile = \"personal\" stack_name = \"datadog-monitor-dev\" s3_bucket = \"custom-resources-dev-20200318\" s3_prefix = \"datadog\" region = \"eu-west-1\" capabilities = \"CAPABILITY_IAM\" confirm_changeset = true tags = \"project=\\\"datadog-monitor-dev\\\" stage=\\\"dev\\\"\"" }, { "code": null, "e": 6715, "s": 6470, "text": "Setup the AWS Services integration in your Datadog account and ensure that the lambda tile is selected. This enables Datadog to collect Amazon lambda metrics. Once completed all lambda functions will be available in the Datadog serverless view." }, { "code": null, "e": 6921, "s": 6715, "text": "Retrieve the DataDog API key and create an Application key. These must be stored in AWS secrets manager as follows, you can choose any name for the secrets which is added to the CF template as a parameter:" }, { "code": null, "e": 6989, "s": 6921, "text": "{ \"DD_CLIENT_API_KEY\": \"API KEY\", \"DD_CLIENT_APP_KEY\": \"APP KEY\"}" }, { "code": null, "e": 7265, "s": 6989, "text": "Datadog has a HTTP REST API that allows you to interact with the platform programmatically. The API has been used in the code below to create the Monitor class which will be used by the custom resource lambda. The code below has been summarised into the following key points:" }, { "code": null, "e": 7325, "s": 7265, "text": "The base url of the API is: https://api.datadoghq.eu/api/v1" }, { "code": null, "e": 7490, "s": 7325, "text": "To authenticate calls to the API, the datadog API key and Application Key must be provided in the request headers. The keys are used to initialise the class object." }, { "code": null, "e": 7624, "s": 7490, "text": "The class has three methods to create, update and delete Datadog monitors, and one helper method to construct a simple monitor query." }, { "code": null, "e": 8088, "s": 7624, "text": "The create_monitor method takes the following arguments: name, message, priority, functionname and tags. The name is simply the name of the monitor as it appears in the Datadog UI. The message is what gets sent with each alert. The priority indicates the severity of the alert. The functionname is used by the _create_query method to construct a simple monitor query and the tags are used to tag the monitor. After a monitor is created its monitor_id is returned." }, { "code": null, "e": 8227, "s": 8088, "text": "The _create_query method uses the functionname argument to create a monitor query which checks for any lambda errors within the last hour." }, { "code": null, "e": 8392, "s": 8227, "text": "The update_monitor method takes all the same arguments as the create_monitor method, except with the addition of the monitor_id so it knows which monitor to update." }, { "code": null, "e": 8461, "s": 8392, "text": "The delete_monitor method uses the monitor_id to delete the monitor." }, { "code": null, "e": 8699, "s": 8461, "text": "Using the Datadog Monitor class and also the Custom resource skeleton code defined above, it is now possible to create a Custom resource which can create, update and manage Datadog monitors in tandem with CloudFormation stack operations." }, { "code": null, "e": 8859, "s": 8699, "text": "As mentioned in the prerequisites, the Datadog API and App keys are stored in AWS secrets manager. These are retrieved using the aws_lambda_powertools package." }, { "code": null, "e": 8911, "s": 8859, "text": "The CfnResource and DD_monitor objects are created." }, { "code": null, "e": 9204, "s": 8911, "text": "The create_monitor method is called within the create function which is executed when the stack is first created; as indicated by the @helper.create decorator. The required arguments are defined in the CloudFormation template and available in the ResourceProperties field in the event object." }, { "code": null, "e": 9313, "s": 9204, "text": "The update_monitor and delete_monitor methods are called within the update and delete function respectively." }, { "code": null, "e": 9431, "s": 9313, "text": "Both the create and delete functions return the monitor_id which will be assigned as the physical id of the resource." }, { "code": null, "e": 9585, "s": 9431, "text": "The test lambda is the lambda which will be monitored in Datadog. The lambda will only be used to generate some successful and failed invocation metrics." }, { "code": null, "e": 9822, "s": 9585, "text": "With the all the lambdas now defined, the next step is to create the CloudFormation (SAM) template to deploy them all. The template explicitly defines three resources, the DataDogMonitorLambda, aTestLambda, and the TestLambdaDDMonitor ." }, { "code": null, "e": 10013, "s": 9822, "text": "The DataDogMonitorLambda is the lambda function that will be called by the custom resource. This is evident as the ServiceToken in the custom resource points to the DataDogMonitorLambda Arn." }, { "code": null, "e": 10066, "s": 10013, "text": "The TestLambda is the lambda that will be monitored." }, { "code": null, "e": 10249, "s": 10066, "text": "The TestLambdaDDMonitor is the Datadog monitor that is created by invoking the DataDogMonitorLambda. The arguments required to create the monitor are passed as additional properties." }, { "code": null, "e": 10311, "s": 10249, "text": "To deploy the stack with SAM, execute the following commands:" }, { "code": null, "e": 10337, "s": 10311, "text": "sam build --use-container" }, { "code": null, "e": 10348, "s": 10337, "text": "sam deploy" }, { "code": null, "e": 10439, "s": 10348, "text": "Check everything looks right in the changeset and press y to continue with the deployment." }, { "code": null, "e": 10801, "s": 10439, "text": "Once the stack creation is complete, all the resources will have both Logical and Physical IDs. Since the create function in the Custom Resource lambda returns the monitor_id of the Datadog monitor it just created, this is set as the resource Physical ID. The monitor can be viewed in Datadog at the following address: https://datadoghq.eu/monitors/{MonitorID}." }, { "code": null, "e": 10949, "s": 10801, "text": "Initially the Datadog monitor will have no data as shown below, this is because the monitor requires either successful or failed lambda executions." }, { "code": null, "e": 11238, "s": 10949, "text": "The easiest way to generate some data is to manually invoke the TestLambda in the AWS UI. Since the monitor only checks for failed invocations each hour, its best to invoke the lambda successfully a few times and wait for the data to populate in Datadog and then cause the lambda to fail." }, { "code": null, "e": 11355, "s": 11238, "text": "Finally, if the monitor is working as expected, after a failed lambda execution, it should remain in an alert state." }, { "code": null, "e": 11666, "s": 11355, "text": "I hope you enjoyed reading this post as much as I enjoyed writing it. The simplicity of Lambda Functions and Custom Resources really open up the possibilities of CloudFormation. I’m planning on writing another article of how you might use Custom Resources to manage your Snowflake account, so watch this space!" }, { "code": null, "e": 11703, "s": 11666, "text": "Checkout my other engineering posts:" } ]
Output of C Programs | Set 1
26 Nov, 2021 Predict the output of below programs. Question 1 c #include<stdio.h>int main(){ int n; for(n = 7; n!=0; n--) printf("n = %d", n--); getchar(); return 0;} Output:Above program goes in infinite loop because n is never zero when loop condition (n != 0) is checked.Question 2 c #include<stdio.h>int main(){ printf("%x", -1<<1); getchar(); return 0;} Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe.Question 3 c # include <stdio.h># define scanf "%s Geeks For Geeks "main(){ printf(scanf, scanf); getchar(); return 0;} Output: %s Geeks For Geeks Geeks For Geeks Explanation: After pre-processing phase of compilation, printf statement will become. printf("%s Geeks For Geeks ", "%s Geeks For Geeks "); Now you can easily guess why output is %s Geeks For Geeks Geeks For Geeks.Question 4 c #include <stdlib.h>#include <stdio.h>enum {false, true};int main(){ int i = 1; do { printf("%d\n", i); i++; if (i < 15) continue; } while (false); getchar(); return 0;} Output: 1 Explanation: The do while loop checks condition after each iteration. So after continue statement, control transfers to the statement while(false). Since the condition is false ‘i’ is printed only once.Now try below program. c #include <stdlib.h>#include <stdio.h>enum {false, true};int main(){ int i = 1; do { printf("%d\n", i); i++; if (i < 15) break; } while (true); getchar(); return 0;} Question 5 c char *getString(){ char *str = "Nice test for strings"; return str;} int main(){ printf("%s", getString()); getchar(); return 0;} Output: “Nice test for strings” The above program works because string constants are stored in Data Section (not in Stack Section). So, when getString returns *str is not lost. surindertarika1234 Output of C Programs Program Output Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Runtime Errors Different ways to copy a string in C/C++ Output of C++ Program | Set 1 Output of Java Program | Set 2 Output of Java Program | Set 3 Output of C++ programs | Set 47 (Pointers) Output of Java Programs | Set 12 Output of Java Program | Set 7 Output of C programs | Set 59 (Loops and Control Statements) unsigned specifier (%u) in C with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Nov, 2021" }, { "code": null, "e": 91, "s": 52, "text": "Predict the output of below programs. " }, { "code": null, "e": 103, "s": 91, "text": "Question 1 " }, { "code": null, "e": 105, "s": 103, "text": "c" }, { "code": "#include<stdio.h>int main(){ int n; for(n = 7; n!=0; n--) printf(\"n = %d\", n--); getchar(); return 0;}", "e": 220, "s": 105, "text": null }, { "code": null, "e": 339, "s": 220, "text": "Output:Above program goes in infinite loop because n is never zero when loop condition (n != 0) is checked.Question 2 " }, { "code": null, "e": 341, "s": 339, "text": "c" }, { "code": "#include<stdio.h>int main(){ printf(\"%x\", -1<<1); getchar(); return 0;}", "e": 419, "s": 341, "text": null }, { "code": null, "e": 541, "s": 419, "text": "Output is dependent on the compiler. For 32 bit compiler it would be fffffffe and for 16 bit it would be fffe.Question 3 " }, { "code": null, "e": 543, "s": 541, "text": "c" }, { "code": "# include <stdio.h># define scanf \"%s Geeks For Geeks \"main(){ printf(scanf, scanf); getchar(); return 0;}", "e": 657, "s": 543, "text": null }, { "code": null, "e": 788, "s": 657, "text": "Output: %s Geeks For Geeks Geeks For Geeks Explanation: After pre-processing phase of compilation, printf statement will become. " }, { "code": null, "e": 846, "s": 788, "text": " printf(\"%s Geeks For Geeks \", \"%s Geeks For Geeks \");" }, { "code": null, "e": 932, "s": 846, "text": "Now you can easily guess why output is %s Geeks For Geeks Geeks For Geeks.Question 4 " }, { "code": null, "e": 934, "s": 932, "text": "c" }, { "code": "#include <stdlib.h>#include <stdio.h>enum {false, true};int main(){ int i = 1; do { printf(\"%d\\n\", i); i++; if (i < 15) continue; } while (false); getchar(); return 0;}", "e": 1138, "s": 934, "text": null }, { "code": null, "e": 1374, "s": 1138, "text": "Output: 1 Explanation: The do while loop checks condition after each iteration. So after continue statement, control transfers to the statement while(false). Since the condition is false ‘i’ is printed only once.Now try below program. " }, { "code": null, "e": 1376, "s": 1374, "text": "c" }, { "code": "#include <stdlib.h>#include <stdio.h>enum {false, true};int main(){ int i = 1; do { printf(\"%d\\n\", i); i++; if (i < 15) break; } while (true); getchar(); return 0;}", "e": 1578, "s": 1376, "text": null }, { "code": null, "e": 1590, "s": 1578, "text": "Question 5 " }, { "code": null, "e": 1592, "s": 1590, "text": "c" }, { "code": "char *getString(){ char *str = \"Nice test for strings\"; return str;} int main(){ printf(\"%s\", getString()); getchar(); return 0;}", "e": 1732, "s": 1592, "text": null }, { "code": null, "e": 1910, "s": 1732, "text": "Output: “Nice test for strings” The above program works because string constants are stored in Data Section (not in Stack Section). So, when getString returns *str is not lost. " }, { "code": null, "e": 1929, "s": 1910, "text": "surindertarika1234" }, { "code": null, "e": 1950, "s": 1929, "text": "Output of C Programs" }, { "code": null, "e": 1965, "s": 1950, "text": "Program Output" }, { "code": null, "e": 2063, "s": 1965, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2078, "s": 2063, "text": "Runtime Errors" }, { "code": null, "e": 2119, "s": 2078, "text": "Different ways to copy a string in C/C++" }, { "code": null, "e": 2149, "s": 2119, "text": "Output of C++ Program | Set 1" }, { "code": null, "e": 2180, "s": 2149, "text": "Output of Java Program | Set 2" }, { "code": null, "e": 2211, "s": 2180, "text": "Output of Java Program | Set 3" }, { "code": null, "e": 2254, "s": 2211, "text": "Output of C++ programs | Set 47 (Pointers)" }, { "code": null, "e": 2287, "s": 2254, "text": "Output of Java Programs | Set 12" }, { "code": null, "e": 2318, "s": 2287, "text": "Output of Java Program | Set 7" }, { "code": null, "e": 2379, "s": 2318, "text": "Output of C programs | Set 59 (Loops and Control Statements)" } ]
Super Constructor in Dart
20 Jul, 2020 In dart, the subclass can inherit all the variables and methods of the parent class, with the use of extends keyword but it can’t inherit constructor of the parent class. To do so we make use of super constructor in the dart. There are two ways to call super constructor: ImplicitlyExplicitly Implicitly Explicitly When calling explicitly we make use of super constructor as: Child_class_constructor() :super() { ... } Implicit super: In this case, the parent class is called implicitly, when there is object creation of child class. Here we don’t make use of the super constructor but when the child class constructor is invoked then it calls default parent class constructor. Example: Calling parent constructor taking no parameter(s). Dart // Dart program for calling parent// constructor taking no parameterclass SuperGeek { // Creating parent constructor SuperGeek(){ print("You are inside Parent constructor!!"); }} class SubGeek extends SuperGeek { // Creating child constructor SubGeek(){ print("You are inside Child constructor!!"); }} void main() { SubGeek geek = new SubGeek();} Output: You are inside Parent constructor!! You are inside Child constructor!! Explicit super: If the parent constructor is default then we call it as followed in implicit super, but if it takes parameters then the superclass is invoked as shown in the syntax mentioned above. Example: Calling parent constructor taking parameter(s). Dart class SuperGeek { // Creating parent constructor SuperGeek(String geek_name){ print("You are inside Parent constructor!!"); print("Welcome to $geek_name"); }} class SubGeek extends SuperGeek { // Creating child constructor // and calling parent class constructor SubGeek() : super("Geeks for Geeks"){ print("You are inside Child constructor!!"); }} void main() { SubGeek geek = new SubGeek();} Output: You are inside Parent constructor!! Welcome to Geeks for Geeks You are inside Child constructor!! Dart-OOPs Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jul, 2020" }, { "code": null, "e": 325, "s": 52, "text": "In dart, the subclass can inherit all the variables and methods of the parent class, with the use of extends keyword but it can’t inherit constructor of the parent class. To do so we make use of super constructor in the dart. There are two ways to call super constructor: " }, { "code": null, "e": 346, "s": 325, "text": "ImplicitlyExplicitly" }, { "code": null, "e": 357, "s": 346, "text": "Implicitly" }, { "code": null, "e": 368, "s": 357, "text": "Explicitly" }, { "code": null, "e": 431, "s": 368, "text": "When calling explicitly we make use of super constructor as: " }, { "code": null, "e": 475, "s": 431, "text": "Child_class_constructor() :super() {\n...\n}\n" }, { "code": null, "e": 735, "s": 475, "text": "Implicit super: In this case, the parent class is called implicitly, when there is object creation of child class. Here we don’t make use of the super constructor but when the child class constructor is invoked then it calls default parent class constructor. " }, { "code": null, "e": 797, "s": 735, "text": "Example: Calling parent constructor taking no parameter(s). " }, { "code": null, "e": 802, "s": 797, "text": "Dart" }, { "code": "// Dart program for calling parent// constructor taking no parameterclass SuperGeek { // Creating parent constructor SuperGeek(){ print(\"You are inside Parent constructor!!\"); }} class SubGeek extends SuperGeek { // Creating child constructor SubGeek(){ print(\"You are inside Child constructor!!\"); }} void main() { SubGeek geek = new SubGeek();}", "e": 1174, "s": 802, "text": null }, { "code": null, "e": 1186, "s": 1176, "text": "Output: " }, { "code": null, "e": 1258, "s": 1186, "text": "You are inside Parent constructor!!\nYou are inside Child constructor!!\n" }, { "code": null, "e": 1457, "s": 1258, "text": "Explicit super: If the parent constructor is default then we call it as followed in implicit super, but if it takes parameters then the superclass is invoked as shown in the syntax mentioned above. " }, { "code": null, "e": 1515, "s": 1457, "text": "Example: Calling parent constructor taking parameter(s). " }, { "code": null, "e": 1520, "s": 1515, "text": "Dart" }, { "code": "class SuperGeek { // Creating parent constructor SuperGeek(String geek_name){ print(\"You are inside Parent constructor!!\"); print(\"Welcome to $geek_name\"); }} class SubGeek extends SuperGeek { // Creating child constructor // and calling parent class constructor SubGeek() : super(\"Geeks for Geeks\"){ print(\"You are inside Child constructor!!\"); }} void main() { SubGeek geek = new SubGeek();}", "e": 1943, "s": 1520, "text": null }, { "code": null, "e": 1954, "s": 1945, "text": "Output: " }, { "code": null, "e": 2053, "s": 1954, "text": "You are inside Parent constructor!!\nWelcome to Geeks for Geeks\nYou are inside Child constructor!!\n" }, { "code": null, "e": 2063, "s": 2053, "text": "Dart-OOPs" }, { "code": null, "e": 2068, "s": 2063, "text": "Dart" } ]
Output of Java programs | Set 13 (Collections)
31 Mar, 2021 Prerequisite – Collections in Java 1) What is the output of the following program? Java import java.util.*; public class priorityQueue { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.add(11); queue.add(10); queue.add(22); queue.add(5); queue.add(12); queue.add(2); while (queue.isEmpty() == false) System.out.printf("%d ", queue.remove()); System.out.println("\n"); }} a) 11 10 22 5 12 2 b) 2 12 5 22 10 11 c) 2 5 10 11 12 22 d) 22 12 11 10 5 2 Ans. (c) Explanation: Priority queue always outputs the minimum element from the queue when remove() method is called, no matter what the sequence of input is. 2) What is the output of the following program? Java import java.util.*; public class Treeset { public static void main(String[] args) { TreeSet<String> treeSet = new TreeSet<>(); treeSet.add("Geeks"); treeSet.add("For"); treeSet.add("Geeks"); treeSet.add("GeeksforGeeks"); for (String temp : treeSet) System.out.printf(temp + " "); System.out.println("\n"); }} a) Geeks For Geeks GeeksforGeeks b) Geeks For GeeksforGeeks c) For Geeks GeeksforGeeks d) For GeeksforGeeks Geeks Ans. (c) Explanation: A TreeSet sorts the data in ascending order that is inserted in it. Therefore, the output string contains all the strings arranged in ascending order. A TreeSet does not contain any duplicate element as it is a set. So in the output, there is just a single occurrence of string ‘Geeks’. 3) What is the output of the following program? Java import java.util.*; public class linkedList { public static void main(String[] args) { List<String> list1 = new LinkedList<>(); list1.add("Geeks"); list1.add("For"); list1.add("Geeks"); list1.add("GFG"); list1.add("GeeksforGeeks"); List<String> list2 = new LinkedList<>(); list2.add("Geeks"); list1.removeAll(list2); for (String temp : list1) System.out.printf(temp + " "); System.out.println(); }} a) For Geeks GFG GeeksforGeeks b) For GeeksforGeeks GFG c) For GFG for d) For GFG GeeksforGeeks Ans. (d) Explanation: list1.removeAll(list2) function deletes all the occurrence of string in list2 from list1. Here, the string ‘Geeks’ appears in list2, so all the nodes of linked list in list1 that contains ‘Geeks’ as its data is removed from list1. 4) Which of the given choices is a possible output? Java import java.util.*; public class hashSet { public static void main(String[] args) { HashSet<String> hashSet = new HashSet<>(); hashSet.add("Geeks"); hashSet.add("For"); hashSet.add("Geeks"); hashSet.add("GeeksforGeeks"); System.out.println(hashSet); }} a) [Geeks, For, Geeks, GeeksforGeeks] b) [GeeksforGeeks, Geeks, For] Ans. (b) Explanation: A HashSet is a set and as a set doesn’t contain any duplicate element therefore, the string ‘Geeks’ appears only once in the output. 5) What is the output of the following program? Java import java.util.*; public class stack { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("Geeks"); list.add("For"); list.add("Geeks"); list.add("GeeksforGeeks"); Iterator<Integer> iter = list.iterator(); while (iter.hasNext()) System.out.printf(iter.next() + " "); System.out.println(); }} a) Geeks for Geeks GeeksforGeeks b) GeeksforGeeks Geeks for Geeks c) Runtime Error d) Compilation Error Ans. (d) Explanation: An iterator made for iterating over Integer cannot be used to iterate over String data type. Corrected program: https://ide.geeksforgeeks.org/DgeN0P This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jacob341 nidhi_biet shubhashish_soni aktmishra143 Java-Collections Java-Output Java Program Output Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java ArrayList in Java Stream In Java Collections in Java Singleton Class in Java Arrow operator -> in C/C++ with Examples Output of C Programs | Set 1 Output of Java Program | Set 1 delete keyword in C++ Output of C++ programs | Set 50
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Mar, 2021" }, { "code": null, "e": 89, "s": 54, "text": "Prerequisite – Collections in Java" }, { "code": null, "e": 138, "s": 89, "text": "1) What is the output of the following program? " }, { "code": null, "e": 143, "s": 138, "text": "Java" }, { "code": "import java.util.*; public class priorityQueue { public static void main(String[] args) { PriorityQueue<Integer> queue = new PriorityQueue<>(); queue.add(11); queue.add(10); queue.add(22); queue.add(5); queue.add(12); queue.add(2); while (queue.isEmpty() == false) System.out.printf(\"%d \", queue.remove()); System.out.println(\"\\n\"); }}", "e": 575, "s": 143, "text": null }, { "code": null, "e": 652, "s": 575, "text": "a) 11 10 22 5 12 2 b) 2 12 5 22 10 11 c) 2 5 10 11 12 22 d) 22 12 11 10 5 2 " }, { "code": null, "e": 662, "s": 652, "text": "Ans. (c) " }, { "code": null, "e": 861, "s": 662, "text": "Explanation: Priority queue always outputs the minimum element from the queue when remove() method is called, no matter what the sequence of input is. 2) What is the output of the following program?" }, { "code": null, "e": 866, "s": 861, "text": "Java" }, { "code": "import java.util.*; public class Treeset { public static void main(String[] args) { TreeSet<String> treeSet = new TreeSet<>(); treeSet.add(\"Geeks\"); treeSet.add(\"For\"); treeSet.add(\"Geeks\"); treeSet.add(\"GeeksforGeeks\"); for (String temp : treeSet) System.out.printf(temp + \" \"); System.out.println(\"\\n\"); }}", "e": 1247, "s": 866, "text": null }, { "code": null, "e": 1361, "s": 1247, "text": "a) Geeks For Geeks GeeksforGeeks b) Geeks For GeeksforGeeks c) For Geeks GeeksforGeeks d) For GeeksforGeeks Geeks" }, { "code": null, "e": 1371, "s": 1361, "text": "Ans. (c) " }, { "code": null, "e": 1720, "s": 1371, "text": "Explanation: A TreeSet sorts the data in ascending order that is inserted in it. Therefore, the output string contains all the strings arranged in ascending order. A TreeSet does not contain any duplicate element as it is a set. So in the output, there is just a single occurrence of string ‘Geeks’. 3) What is the output of the following program? " }, { "code": null, "e": 1725, "s": 1720, "text": "Java" }, { "code": "import java.util.*; public class linkedList { public static void main(String[] args) { List<String> list1 = new LinkedList<>(); list1.add(\"Geeks\"); list1.add(\"For\"); list1.add(\"Geeks\"); list1.add(\"GFG\"); list1.add(\"GeeksforGeeks\"); List<String> list2 = new LinkedList<>(); list2.add(\"Geeks\"); list1.removeAll(list2); for (String temp : list1) System.out.printf(temp + \" \"); System.out.println(); }}", "e": 2225, "s": 1725, "text": null }, { "code": null, "e": 2321, "s": 2225, "text": "a) For Geeks GFG GeeksforGeeks b) For GeeksforGeeks GFG c) For GFG for d) For GFG GeeksforGeeks" }, { "code": null, "e": 2331, "s": 2321, "text": "Ans. (d) " }, { "code": null, "e": 2629, "s": 2331, "text": "Explanation: list1.removeAll(list2) function deletes all the occurrence of string in list2 from list1. Here, the string ‘Geeks’ appears in list2, so all the nodes of linked list in list1 that contains ‘Geeks’ as its data is removed from list1. 4) Which of the given choices is a possible output? " }, { "code": null, "e": 2634, "s": 2629, "text": "Java" }, { "code": "import java.util.*; public class hashSet { public static void main(String[] args) { HashSet<String> hashSet = new HashSet<>(); hashSet.add(\"Geeks\"); hashSet.add(\"For\"); hashSet.add(\"Geeks\"); hashSet.add(\"GeeksforGeeks\"); System.out.println(hashSet); }}", "e": 2939, "s": 2634, "text": null }, { "code": null, "e": 3009, "s": 2939, "text": "a) [Geeks, For, Geeks, GeeksforGeeks] b) [GeeksforGeeks, Geeks, For] " }, { "code": null, "e": 3019, "s": 3009, "text": "Ans. (b) " }, { "code": null, "e": 3214, "s": 3019, "text": "Explanation: A HashSet is a set and as a set doesn’t contain any duplicate element therefore, the string ‘Geeks’ appears only once in the output. 5) What is the output of the following program? " }, { "code": null, "e": 3219, "s": 3214, "text": "Java" }, { "code": "import java.util.*; public class stack { public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add(\"Geeks\"); list.add(\"For\"); list.add(\"Geeks\"); list.add(\"GeeksforGeeks\"); Iterator<Integer> iter = list.iterator(); while (iter.hasNext()) System.out.printf(iter.next() + \" \"); System.out.println(); }}", "e": 3629, "s": 3219, "text": null }, { "code": null, "e": 3733, "s": 3629, "text": "a) Geeks for Geeks GeeksforGeeks b) GeeksforGeeks Geeks for Geeks c) Runtime Error d) Compilation Error" }, { "code": null, "e": 3743, "s": 3733, "text": "Ans. (d) " }, { "code": null, "e": 3905, "s": 3743, "text": "Explanation: An iterator made for iterating over Integer cannot be used to iterate over String data type. Corrected program: https://ide.geeksforgeeks.org/DgeN0P" }, { "code": null, "e": 4205, "s": 3905, "text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 4330, "s": 4205, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 4339, "s": 4330, "text": "jacob341" }, { "code": null, "e": 4350, "s": 4339, "text": "nidhi_biet" }, { "code": null, "e": 4367, "s": 4350, "text": "shubhashish_soni" }, { "code": null, "e": 4380, "s": 4367, "text": "aktmishra143" }, { "code": null, "e": 4397, "s": 4380, "text": "Java-Collections" }, { "code": null, "e": 4409, "s": 4397, "text": "Java-Output" }, { "code": null, "e": 4414, "s": 4409, "text": "Java" }, { "code": null, "e": 4429, "s": 4414, "text": "Program Output" }, { "code": null, "e": 4434, "s": 4429, "text": "Java" }, { "code": null, "e": 4451, "s": 4434, "text": "Java-Collections" }, { "code": null, "e": 4549, "s": 4451, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4568, "s": 4549, "text": "Interfaces in Java" }, { "code": null, "e": 4586, "s": 4568, "text": "ArrayList in Java" }, { "code": null, "e": 4601, "s": 4586, "text": "Stream In Java" }, { "code": null, "e": 4621, "s": 4601, "text": "Collections in Java" }, { "code": null, "e": 4645, "s": 4621, "text": "Singleton Class in Java" }, { "code": null, "e": 4686, "s": 4645, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 4715, "s": 4686, "text": "Output of C Programs | Set 1" }, { "code": null, "e": 4746, "s": 4715, "text": "Output of Java Program | Set 1" }, { "code": null, "e": 4768, "s": 4746, "text": "delete keyword in C++" } ]
ReactJS | Props – Set 1
22 Jan, 2021 We have already discussed Components and it’s type in our previous articles on ReactJS | Components. Till now we were working with components using static data only. In this article, we will learn about how we can pass information to a Component.React allows us to pass information to a Component using something called props (stands for properties). Props are basically kind of global variable or object. We will learn about these in detail in this article. Passing and Accessing props We can pass props to any component as we declare attributes for any HTML tag. Have a look at the below code snippet: <DemoComponent sampleProp = "HelloProp" /> In the above code snippet, we are passing a prop named sampleProp to the component named DemoComponent. This prop has the value “HelloProp”. Let us now see how can we access these props. We can access any props inside from the component’s class to which the props is passed. The props can be accessed as shown below: this.props.propName; We can access any prop from inside a component’s class using the above syntax. The ‘this.props’ is a kind of global object which stores all of a components props. The propName, that is the names of props are keys of this object.Below is a sample program to illustrate how to pass and access props from a component: 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. Open your react project and edit the App.js file in the src folder: src App.js: javascript import React from 'react';import ReactDOM from 'react-dom'; // sample component to illustrate propsclass DemoComponent extends React.Component{ render(){ return( <div> {/*accessing information from props */} <h2>Hello {this.props.user}</h2> <h3>Welcome to GeeksforGeeks</h3> </div> ); }} ReactDOM.render( // passing props <DemoComponent user = "Harsh Agarwal" />, document.getElementById("root")); Output: In the above example, we have used a class-based component to illustrate props. But we can pass props to a function-based component also just like we did in the above example. But to access a prop from a function we do not need to use the ‘this’ keyword anymore. Functional components accept props as parameters and can be accessed directly. Below is the same example as above but this time using a function-based component instead of a class-based component. Open your react project and edit the App.js file in the src folder: src App.js: javascript import React from 'react';import ReactDOM from 'react-dom'; // functional component to illustrate propsfunction DemoComponent(props){ return( <div> {/*accessing information from props */} <h2>Hello {props.user}</h2> <h3>Welcome to GeeksforGeeks</h3> </div> );} ReactDOM.render( // passing props <DemoComponent user = "Harsh Agarwal" />, document.getElementById("root")); The output of this program will be the same as that of the above program. The only difference is that we have used a function-based component instead of a class-based component. Passing information from one component to other This is one of the coolest features of React. We can make components to interact among themselves. We will consider two components Parent and Children to explain this. We will pass some information as props from our Parent component to the Child component. We can pass as many props as we want to a component.Look at the below code: Open your react project and edit the App.js file in the src folder: src App.js: javascript import React from 'react';import ReactDOM from 'react-dom'; // Parent Componentclass Parent extends React.Component{ render(){ return( <div> <h2>You are inside Parent Component</h2> <Child name="User" userId = "5555"/> </div> ); }} // Child Componentclass Child extends React.Component{ render(){ return( <div> <h2>Hello, {this.props.name}</h2> <h3>You are inside Child Component</h3> <h3>Your user id is: {this.props.userId}</h3> </div> ); }} ReactDOM.render( // passing props <Parent />, document.getElementById("root")); Output: So we have seen props in React and also have learned about how props are used, how they can be passed to a component, how they are accessed inside a component, and much more. We have used the thing “this.props.propName” very often in this complete scenario to access props. Let us now check what is actually being stored in this. We will console.log “this.props” in the above program inside the child component and will try to observe what is logged into the console. Below is the modified program with console.log() statement: Open your react project and edit the App.js file in the src folder: src App.js: javascript import React from 'react';import ReactDOM from 'react-dom'; // Parent Componentclass Parent extends React.Component{ render(){ return( <div> <h2>You are inside Parent Component</h2> <Child name="User" userId = "5555"/> </div> ); }} // Child Componentclass Child extends React.Component{ render(){ console.log(this.props); return( <div> <h2>Hello, {this.props.name}</h2> <h3>You are inside Child Component</h3> <h3>Your user id is: {this.props.userId}</h3> </div> ); }} ReactDOM.render( // passing props <Parent />, document.getElementById("root")); You can clearly see in the above image that in the console it is shown that the this.props is an object and it contains all of the props passed to the child component. The props name of the child component are keys of this object and their values are values of these keys. So, it is clear now that whatever information is carried to a component using props is stored inside an object.Note: Props are read-only. We are not allowed to modify the content of a prop. Whatever the type of Component is – functional or class-based, none of them is allowed to modify their props. We will learn about this in details in the next article Reactjs | props set-2 Reference: https://reactjs.org/docs/components-and-props.html shubhamyadav4 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 ? Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jan, 2021" }, { "code": null, "e": 512, "s": 52, "text": "We have already discussed Components and it’s type in our previous articles on ReactJS | Components. Till now we were working with components using static data only. In this article, we will learn about how we can pass information to a Component.React allows us to pass information to a Component using something called props (stands for properties). Props are basically kind of global variable or object. We will learn about these in detail in this article. " }, { "code": null, "e": 540, "s": 512, "text": "Passing and Accessing props" }, { "code": null, "e": 659, "s": 540, "text": "We can pass props to any component as we declare attributes for any HTML tag. Have a look at the below code snippet: " }, { "code": null, "e": 702, "s": 659, "text": "<DemoComponent sampleProp = \"HelloProp\" />" }, { "code": null, "e": 1021, "s": 702, "text": "In the above code snippet, we are passing a prop named sampleProp to the component named DemoComponent. This prop has the value “HelloProp”. Let us now see how can we access these props. We can access any props inside from the component’s class to which the props is passed. The props can be accessed as shown below: " }, { "code": null, "e": 1042, "s": 1021, "text": "this.props.propName;" }, { "code": null, "e": 1359, "s": 1042, "text": "We can access any prop from inside a component’s class using the above syntax. The ‘this.props’ is a kind of global object which stores all of a components props. The propName, that is the names of props are keys of this object.Below is a sample program to illustrate how to pass and access props from a component: " }, { "code": null, "e": 1368, "s": 1359, "text": "Chapters" }, { "code": null, "e": 1395, "s": 1368, "text": "descriptions off, selected" }, { "code": null, "e": 1445, "s": 1395, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1468, "s": 1445, "text": "captions off, selected" }, { "code": null, "e": 1476, "s": 1468, "text": "English" }, { "code": null, "e": 1500, "s": 1476, "text": "This is a modal window." }, { "code": null, "e": 1569, "s": 1500, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1591, "s": 1569, "text": "End of dialog window." }, { "code": null, "e": 1659, "s": 1591, "text": "Open your react project and edit the App.js file in the src folder:" }, { "code": null, "e": 1671, "s": 1659, "text": "src App.js:" }, { "code": null, "e": 1682, "s": 1671, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; // sample component to illustrate propsclass DemoComponent extends React.Component{ render(){ return( <div> {/*accessing information from props */} <h2>Hello {this.props.user}</h2> <h3>Welcome to GeeksforGeeks</h3> </div> ); }} ReactDOM.render( // passing props <DemoComponent user = \"Harsh Agarwal\" />, document.getElementById(\"root\"));", "e": 2201, "s": 1682, "text": null }, { "code": null, "e": 2211, "s": 2201, "text": "Output: " }, { "code": null, "e": 2672, "s": 2211, "text": "In the above example, we have used a class-based component to illustrate props. But we can pass props to a function-based component also just like we did in the above example. But to access a prop from a function we do not need to use the ‘this’ keyword anymore. Functional components accept props as parameters and can be accessed directly. Below is the same example as above but this time using a function-based component instead of a class-based component. " }, { "code": null, "e": 2740, "s": 2672, "text": "Open your react project and edit the App.js file in the src folder:" }, { "code": null, "e": 2753, "s": 2740, "text": "src App.js: " }, { "code": null, "e": 2764, "s": 2753, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; // functional component to illustrate propsfunction DemoComponent(props){ return( <div> {/*accessing information from props */} <h2>Hello {props.user}</h2> <h3>Welcome to GeeksforGeeks</h3> </div> );} ReactDOM.render( // passing props <DemoComponent user = \"Harsh Agarwal\" />, document.getElementById(\"root\"));", "e": 3198, "s": 2764, "text": null }, { "code": null, "e": 3377, "s": 3198, "text": "The output of this program will be the same as that of the above program. The only difference is that we have used a function-based component instead of a class-based component. " }, { "code": null, "e": 3425, "s": 3377, "text": "Passing information from one component to other" }, { "code": null, "e": 3826, "s": 3425, "text": "This is one of the coolest features of React. We can make components to interact among themselves. We will consider two components Parent and Children to explain this. We will pass some information as props from our Parent component to the Child component. We can pass as many props as we want to a component.Look at the below code: Open your react project and edit the App.js file in the src folder:" }, { "code": null, "e": 3838, "s": 3826, "text": "src App.js:" }, { "code": null, "e": 3849, "s": 3838, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; // Parent Componentclass Parent extends React.Component{ render(){ return( <div> <h2>You are inside Parent Component</h2> <Child name=\"User\" userId = \"5555\"/> </div> ); }} // Child Componentclass Child extends React.Component{ render(){ return( <div> <h2>Hello, {this.props.name}</h2> <h3>You are inside Child Component</h3> <h3>Your user id is: {this.props.userId}</h3> </div> ); }} ReactDOM.render( // passing props <Parent />, document.getElementById(\"root\"));", "e": 4585, "s": 3849, "text": null }, { "code": null, "e": 4595, "s": 4585, "text": "Output: " }, { "code": null, "e": 5124, "s": 4595, "text": "So we have seen props in React and also have learned about how props are used, how they can be passed to a component, how they are accessed inside a component, and much more. We have used the thing “this.props.propName” very often in this complete scenario to access props. Let us now check what is actually being stored in this. We will console.log “this.props” in the above program inside the child component and will try to observe what is logged into the console. Below is the modified program with console.log() statement: " }, { "code": null, "e": 5192, "s": 5124, "text": "Open your react project and edit the App.js file in the src folder:" }, { "code": null, "e": 5205, "s": 5192, "text": "src App.js: " }, { "code": null, "e": 5216, "s": 5205, "text": "javascript" }, { "code": "import React from 'react';import ReactDOM from 'react-dom'; // Parent Componentclass Parent extends React.Component{ render(){ return( <div> <h2>You are inside Parent Component</h2> <Child name=\"User\" userId = \"5555\"/> </div> ); }} // Child Componentclass Child extends React.Component{ render(){ console.log(this.props); return( <div> <h2>Hello, {this.props.name}</h2> <h3>You are inside Child Component</h3> <h3>Your user id is: {this.props.userId}</h3> </div> ); }} ReactDOM.render( // passing props <Parent />, document.getElementById(\"root\"));", "e": 5984, "s": 5216, "text": null }, { "code": null, "e": 6635, "s": 5984, "text": "You can clearly see in the above image that in the console it is shown that the this.props is an object and it contains all of the props passed to the child component. The props name of the child component are keys of this object and their values are values of these keys. So, it is clear now that whatever information is carried to a component using props is stored inside an object.Note: Props are read-only. We are not allowed to modify the content of a prop. Whatever the type of Component is – functional or class-based, none of them is allowed to modify their props. We will learn about this in details in the next article Reactjs | props set-2" }, { "code": null, "e": 6698, "s": 6635, "text": "Reference: https://reactjs.org/docs/components-and-props.html " }, { "code": null, "e": 6712, "s": 6698, "text": "shubhamyadav4" }, { "code": null, "e": 6721, "s": 6712, "text": "react-js" }, { "code": null, "e": 6738, "s": 6721, "text": "Web Technologies" }, { "code": null, "e": 6836, "s": 6738, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6869, "s": 6836, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 6931, "s": 6869, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 6992, "s": 6931, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7042, "s": 6992, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7085, "s": 7042, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 7125, "s": 7085, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 7149, "s": 7125, "text": "REST API (Introduction)" }, { "code": null, "e": 7182, "s": 7149, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 7242, "s": 7182, "text": "How to set the default value for an HTML <select> element ?" } ]
reflect.Type() Function in Golang with Examples
05 May, 2020 Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Type() Function in Golang is used to get v’s type. To access this function, one needs to imports the reflect package in the program. Syntax: func (v Value) Type() Type Parameters: This function does not accept any parameter. Return Value: This function returns the v’s type. Below examples illustrate the use of above method in Golang: Example 1: // Golang program to illustrate// reflect.Type() Function package main import ( "fmt" "reflect") // Main functionfunc main() { var val chan int // use of Type() method value := reflect.MakeChan(reflect.Indirect(reflect.ValueOf(&val)).Type(), 0) fmt.Println("Value :", value)} Output: Value : 0xc00010c000 Example 2: // Golang program to illustrate// reflect.Type() Function package main import ( "fmt" "reflect") // Main functionfunc main() { var str map[int]string var strValue reflect.Value = reflect.ValueOf(&str) indirectStr := reflect.Indirect(strValue) //Use of Type() method valueMap := reflect.MakeMap(indirectStr.Type()) fmt.Printf("ValueMap is [%v] .", valueMap) } Output: ValueMap is [map[]] . Golang-reflect Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 May, 2020" }, { "code": null, "e": 348, "s": 28, "text": "Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.Type() Function in Golang is used to get v’s type. To access this function, one needs to imports the reflect package in the program." }, { "code": null, "e": 356, "s": 348, "text": "Syntax:" }, { "code": null, "e": 384, "s": 356, "text": "func (v Value) Type() Type\n" }, { "code": null, "e": 441, "s": 384, "text": "Parameters: This function does not accept any parameter." }, { "code": null, "e": 491, "s": 441, "text": "Return Value: This function returns the v’s type." }, { "code": null, "e": 552, "s": 491, "text": "Below examples illustrate the use of above method in Golang:" }, { "code": null, "e": 563, "s": 552, "text": "Example 1:" }, { "code": "// Golang program to illustrate// reflect.Type() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { var val chan int // use of Type() method value := reflect.MakeChan(reflect.Indirect(reflect.ValueOf(&val)).Type(), 0) fmt.Println(\"Value :\", value)}", "e": 872, "s": 563, "text": null }, { "code": null, "e": 880, "s": 872, "text": "Output:" }, { "code": null, "e": 902, "s": 880, "text": "Value : 0xc00010c000\n" }, { "code": null, "e": 913, "s": 902, "text": "Example 2:" }, { "code": "// Golang program to illustrate// reflect.Type() Function package main import ( \"fmt\" \"reflect\") // Main functionfunc main() { var str map[int]string var strValue reflect.Value = reflect.ValueOf(&str) indirectStr := reflect.Indirect(strValue) //Use of Type() method valueMap := reflect.MakeMap(indirectStr.Type()) fmt.Printf(\"ValueMap is [%v] .\", valueMap) }", "e": 1335, "s": 913, "text": null }, { "code": null, "e": 1343, "s": 1335, "text": "Output:" }, { "code": null, "e": 1366, "s": 1343, "text": "ValueMap is [map[]] .\n" }, { "code": null, "e": 1381, "s": 1366, "text": "Golang-reflect" }, { "code": null, "e": 1393, "s": 1381, "text": "Go Language" } ]
Find One’s Complement of an Integer
06 Jul, 2022 Given an integer n, find the one’s complement of the integer. Examples: Input : n = 5 Output : 2 Input : n = 255 Output : 0 Input : n = 26 Output : 5 Basic Approach : The naïve approach to solve the problem would be to first convert the given number into its binary representation and then change every 1’s to 0 and 0’s to 1. After changing all 0’s and 1’s convert the binary representation to number. Implementation of the above approach : C++ Java Python3 Javascript // CPP program to find 1's complement of n.#include <bits/stdc++.h>using namespace std; unsigned int onesComplement(unsigned int n){ vector<int> v; // convert to binary representation while (n != 0) { v.push_back(n % 2); n = n / 2; } reverse(v.begin(), v.end()); // change 1's to 0 and 0's to 1 for (int i = 0; i < v.size(); i++) { if (v[i] == 0) v[i] = 1; else v[i] = 0; } // convert back to number representation int two = 1; for (int i = v.size() - 1; i >= 0; i--) { n = n + v[i] * two; two = two * 2; } return n;} int main(){ unsigned int n = 22; cout << onesComplement(n); return 0;} // Java program to find 1's complement of n. import java.util.*; class GFG { static int onesComplement(int n) { ArrayList<Integer> v = new ArrayList<Integer>(); // convert to binary representation while (n != 0) { v.add(n % 2); n = n / 2; } Collections.reverse(v); // change 1's to 0 and 0's to 1 for (int i = 0; i < v.size(); i++) { if (v.get(i) == 0) v.set(i, 1); else v.set(i, 0); } // convert back to number representation int two = 1; for (int i = v.size() - 1; i >= 0; i--) { n = n + v.get(i) * two; two = two * 2; } return n; } // Driver code public static void main(String[] args) { int n = 22; // Function call System.out.println(onesComplement(n)); }} // This code is contributed by phasing17 # Python3 program to find 1's complement of n.def onesComplement(n): v = [] # convert to binary representation while (n != 0): v.append(n % 2) n = n // 2 v.reverse() # change 1's to 0 and 0's to 1 for i in range(len(v)): if (v[i] == 0): v[i] = 1 else: v[i] = 0 # convert back to number representation two = 1 for i in range(len(v) - 1, -1, -1): n = n + v[i] * two two = two * 2 return n # Driver coden = 22 # Function callprint(onesComplement(n)) # This code is contributed by phasing17 // JavaScript program to find 1's complement of n.function onesComplement(n){ let v = []; // convert to binary representation while (n != 0) { v.push(n % 2); n = Math.floor(n / 2); } v.reverse(); // change 1's to 0 and 0's to 1 for (var i = 0; i < v.length; i++) { if (v[i] == 0) v[i] = 1; else v[i] = 0; } // convert back to number representation let two = 1; for (let i = v.length - 1; i >= 0; i--) { n = n + v[i] * two; two = two * 2; } return n;} // Driver codelet n = 22;console.log(onesComplement(n)); // This code is contributed by phasing17 9 Time Complexity : O(log n) Auxiliary Space : O(log n) An efficient approach to this problem is as follows: 1. Find the number of bits in the given integer 2. XOR the given integer with 2^number_of_bits-1 C++ Java Python3 C# PHP Javascript // CPP program to find 1's complement of n.#include<bits/stdc++.h>using namespace std; unsigned int onesComplement(unsigned int n){ // Find number of bits in the given integer int number_of_bits = floor(log2(n))+1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n;} int main(){ unsigned int n = 22; cout << onesComplement(n); return 0;} // Java program to find 1's complement of n.class GFG { static int onesComplement(int n) { // Find number of bits in the // given integer int number_of_bits = (int)(Math.floor(Math.log(n) / Math.log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } // Driver code public static void main(String[] args) { int n = 22; System.out.print(onesComplement(n)); }} // This code is contributed by Anant Agarwal. # Python3 program to find# 1's complement of n.import math def onesComplement(n): # Find number of bits in # the given integer number_of_bits = (int)(math.floor(math.log(n) / math.log(2))) + 1; # XOR the given integer with poe(2, # number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; # Driver coden = 22print(onesComplement(n)) # This code is contributed by Anant Agarwal. // C# program to find 1's complement of n.using System; class GFG { static int onesComplement(int n) { // Find number of bits in the given integer int number_of_bits = (int)(Math.Floor( Math.Log(n) / Math.Log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } //Driver code public static void Main () { int n = 22; Console.WriteLine(onesComplement(n)); }} // This code is contributed by Anant Agarwal. <?php// PHP program to find 1's// complement of n. function Log2($x){ return (log10($x) / log10(2));} function onesComplement($n){ // Find number of bits in// the given integer$number_of_bits = floor(log2($n)) + 1; // XOR the given integer with// number_of_bits-1 and print the resultreturn ((1 << $number_of_bits) - 1) ^ $n;} // Driver Code$n = 22;echo onesComplement($n); // This code is contributed by ihritik?> <script> // Javascript program to find// 1's complement of n. // Function to check whether a// number is power of 2 or notfunction onesComplement(n) { // Find number of bits in the // given integer let number_of_bits = (Math.floor(Math.log(n) / Math.log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } // driver program let n = 22; document.write(onesComplement(n)); </script> 9 Time Complexity : O(log n) Auxiliary Space : O(1) Find One’s Complement of an Integer | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind One’s Complement of an Integer | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:48•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=bcA-52W5vAk" 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 Amit S K. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. ihritik sanjoy_62 parthagarwal1962000 ranjanrohit840 phasing17 Bitwise-XOR complement Bit Magic Mathematical Mathematical Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Little and Big Endian Mystery Bits manipulation (Important tactics) Program to find whether a given number is power of 2 Binary representation of a given number Josephus problem | Set 1 (A O(n) Solution) Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 128, "s": 54, "text": "Given an integer n, find the one’s complement of the integer. Examples: " }, { "code": null, "e": 211, "s": 128, "text": "Input : n = 5\nOutput : 2\n\nInput : n = 255\nOutput : 0\n\nInput : n = 26\nOutput : 5" }, { "code": null, "e": 230, "s": 213, "text": "Basic Approach :" }, { "code": null, "e": 466, "s": 230, "text": "The naïve approach to solve the problem would be to first convert the given number into its binary representation and then change every 1’s to 0 and 0’s to 1. After changing all 0’s and 1’s convert the binary representation to number." }, { "code": null, "e": 505, "s": 466, "text": "Implementation of the above approach :" }, { "code": null, "e": 509, "s": 505, "text": "C++" }, { "code": null, "e": 514, "s": 509, "text": "Java" }, { "code": null, "e": 522, "s": 514, "text": "Python3" }, { "code": null, "e": 533, "s": 522, "text": "Javascript" }, { "code": "// CPP program to find 1's complement of n.#include <bits/stdc++.h>using namespace std; unsigned int onesComplement(unsigned int n){ vector<int> v; // convert to binary representation while (n != 0) { v.push_back(n % 2); n = n / 2; } reverse(v.begin(), v.end()); // change 1's to 0 and 0's to 1 for (int i = 0; i < v.size(); i++) { if (v[i] == 0) v[i] = 1; else v[i] = 0; } // convert back to number representation int two = 1; for (int i = v.size() - 1; i >= 0; i--) { n = n + v[i] * two; two = two * 2; } return n;} int main(){ unsigned int n = 22; cout << onesComplement(n); return 0;}", "e": 1234, "s": 533, "text": null }, { "code": "// Java program to find 1's complement of n. import java.util.*; class GFG { static int onesComplement(int n) { ArrayList<Integer> v = new ArrayList<Integer>(); // convert to binary representation while (n != 0) { v.add(n % 2); n = n / 2; } Collections.reverse(v); // change 1's to 0 and 0's to 1 for (int i = 0; i < v.size(); i++) { if (v.get(i) == 0) v.set(i, 1); else v.set(i, 0); } // convert back to number representation int two = 1; for (int i = v.size() - 1; i >= 0; i--) { n = n + v.get(i) * two; two = two * 2; } return n; } // Driver code public static void main(String[] args) { int n = 22; // Function call System.out.println(onesComplement(n)); }} // This code is contributed by phasing17", "e": 2170, "s": 1234, "text": null }, { "code": "# Python3 program to find 1's complement of n.def onesComplement(n): v = [] # convert to binary representation while (n != 0): v.append(n % 2) n = n // 2 v.reverse() # change 1's to 0 and 0's to 1 for i in range(len(v)): if (v[i] == 0): v[i] = 1 else: v[i] = 0 # convert back to number representation two = 1 for i in range(len(v) - 1, -1, -1): n = n + v[i] * two two = two * 2 return n # Driver coden = 22 # Function callprint(onesComplement(n)) # This code is contributed by phasing17", "e": 2760, "s": 2170, "text": null }, { "code": "// JavaScript program to find 1's complement of n.function onesComplement(n){ let v = []; // convert to binary representation while (n != 0) { v.push(n % 2); n = Math.floor(n / 2); } v.reverse(); // change 1's to 0 and 0's to 1 for (var i = 0; i < v.length; i++) { if (v[i] == 0) v[i] = 1; else v[i] = 0; } // convert back to number representation let two = 1; for (let i = v.length - 1; i >= 0; i--) { n = n + v[i] * two; two = two * 2; } return n;} // Driver codelet n = 22;console.log(onesComplement(n)); // This code is contributed by phasing17", "e": 3427, "s": 2760, "text": null }, { "code": null, "e": 3429, "s": 3427, "text": "9" }, { "code": null, "e": 3456, "s": 3429, "text": "Time Complexity : O(log n)" }, { "code": null, "e": 3483, "s": 3456, "text": "Auxiliary Space : O(log n)" }, { "code": null, "e": 3634, "s": 3483, "text": "An efficient approach to this problem is as follows: 1. Find the number of bits in the given integer 2. XOR the given integer with 2^number_of_bits-1 " }, { "code": null, "e": 3638, "s": 3634, "text": "C++" }, { "code": null, "e": 3643, "s": 3638, "text": "Java" }, { "code": null, "e": 3651, "s": 3643, "text": "Python3" }, { "code": null, "e": 3654, "s": 3651, "text": "C#" }, { "code": null, "e": 3658, "s": 3654, "text": "PHP" }, { "code": null, "e": 3669, "s": 3658, "text": "Javascript" }, { "code": "// CPP program to find 1's complement of n.#include<bits/stdc++.h>using namespace std; unsigned int onesComplement(unsigned int n){ // Find number of bits in the given integer int number_of_bits = floor(log2(n))+1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n;} int main(){ unsigned int n = 22; cout << onesComplement(n); return 0;}", "e": 4088, "s": 3669, "text": null }, { "code": "// Java program to find 1's complement of n.class GFG { static int onesComplement(int n) { // Find number of bits in the // given integer int number_of_bits = (int)(Math.floor(Math.log(n) / Math.log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } // Driver code public static void main(String[] args) { int n = 22; System.out.print(onesComplement(n)); }} // This code is contributed by Anant Agarwal.", "e": 4719, "s": 4088, "text": null }, { "code": "# Python3 program to find# 1's complement of n.import math def onesComplement(n): # Find number of bits in # the given integer number_of_bits = (int)(math.floor(math.log(n) / math.log(2))) + 1; # XOR the given integer with poe(2, # number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; # Driver coden = 22print(onesComplement(n)) # This code is contributed by Anant Agarwal.", "e": 5169, "s": 4719, "text": null }, { "code": "// C# program to find 1's complement of n.using System; class GFG { static int onesComplement(int n) { // Find number of bits in the given integer int number_of_bits = (int)(Math.Floor( Math.Log(n) / Math.Log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } //Driver code public static void Main () { int n = 22; Console.WriteLine(onesComplement(n)); }} // This code is contributed by Anant Agarwal.", "e": 5776, "s": 5169, "text": null }, { "code": "<?php// PHP program to find 1's// complement of n. function Log2($x){ return (log10($x) / log10(2));} function onesComplement($n){ // Find number of bits in// the given integer$number_of_bits = floor(log2($n)) + 1; // XOR the given integer with// number_of_bits-1 and print the resultreturn ((1 << $number_of_bits) - 1) ^ $n;} // Driver Code$n = 22;echo onesComplement($n); // This code is contributed by ihritik?>", "e": 6198, "s": 5776, "text": null }, { "code": "<script> // Javascript program to find// 1's complement of n. // Function to check whether a// number is power of 2 or notfunction onesComplement(n) { // Find number of bits in the // given integer let number_of_bits = (Math.floor(Math.log(n) / Math.log(2))) + 1; // XOR the given integer with poe(2, // number_of_bits-1 and print the result return ((1 << number_of_bits) - 1) ^ n; } // driver program let n = 22; document.write(onesComplement(n)); </script>", "e": 6789, "s": 6198, "text": null }, { "code": null, "e": 6791, "s": 6789, "text": "9" }, { "code": null, "e": 6818, "s": 6791, "text": "Time Complexity : O(log n)" }, { "code": null, "e": 6842, "s": 6818, "text": "Auxiliary Space : O(1) " }, { "code": null, "e": 7730, "s": 6842, "text": "Find One’s Complement of an Integer | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind One’s Complement of an Integer | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 1:48•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=bcA-52W5vAk\" 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": 8148, "s": 7730, "text": " This article is contributed by Amit S K. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8156, "s": 8148, "text": "ihritik" }, { "code": null, "e": 8166, "s": 8156, "text": "sanjoy_62" }, { "code": null, "e": 8186, "s": 8166, "text": "parthagarwal1962000" }, { "code": null, "e": 8201, "s": 8186, "text": "ranjanrohit840" }, { "code": null, "e": 8211, "s": 8201, "text": "phasing17" }, { "code": null, "e": 8223, "s": 8211, "text": "Bitwise-XOR" }, { "code": null, "e": 8234, "s": 8223, "text": "complement" }, { "code": null, "e": 8244, "s": 8234, "text": "Bit Magic" }, { "code": null, "e": 8257, "s": 8244, "text": "Mathematical" }, { "code": null, "e": 8270, "s": 8257, "text": "Mathematical" }, { "code": null, "e": 8280, "s": 8270, "text": "Bit Magic" }, { "code": null, "e": 8378, "s": 8280, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8408, "s": 8378, "text": "Little and Big Endian Mystery" }, { "code": null, "e": 8446, "s": 8408, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 8499, "s": 8446, "text": "Program to find whether a given number is power of 2" }, { "code": null, "e": 8539, "s": 8499, "text": "Binary representation of a given number" }, { "code": null, "e": 8582, "s": 8539, "text": "Josephus problem | Set 1 (A O(n) Solution)" }, { "code": null, "e": 8612, "s": 8582, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 8655, "s": 8612, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 8715, "s": 8655, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 8730, "s": 8715, "text": "C++ Data Types" } ]
How to redirect to another page in ReactJS ?
18 Oct, 2021 In this article, we are going to learn How to redirect to another page in ReactJS using react-router-dom package. ReactJS is a free and open source front-end library used for building single page applications. react-router-dom: react-router-dom is a reactJS package, It enables you to implement dynamic routing in a web page. Approach: Create basic react app. Make different pages for routing. Install react-router-dom package. Implement routing using react-router-dom package. Step 1: Create a basic react app using the following command in your terminal. npx create-react-app <project_name> Project Structure: After creating the basic react app, the folder structure looks like this, Folder structure of react-app Step 2: Make different pages for routing. Here, We are going to create different components for our react-app. So that we route over them for demonstration. Components: Home Page, About Page, ContactUs Page. After creating components, the Folder structure looks like this, Folder structure after making components Home.jsx import React from "react"; const Home = () => { return ( <div> <h1>Home Page</h1> </div> );}; export default Home; About.jsx import React from "react"; const About = () => { return ( <div> <h1>About Page</h1> </div> );}; export default About; ContactUs.jsx import React from "react"; const ContactUs = () => { return ( <div> <h1>Contact Us Page</h1> </div> );}; export default ContactUs; Step 3: Install react-router-dom package. Here, We are going to install the react-router-dom package in our react-app, using the following command. npm i react-router-dom Installing react-router-dom After installing react-router-dom package package.json file looks like this, Package.json Step 3: Implement routing using the react-router-dom package. Here, We are going to implement the react-router-dom package in our react-app. To implement this, We have to import some components from the react-router-dom package i.e. BrowserRouter, Switch, Route, and Redirect. import { BrowserRouter as Router, Switch, Route, Redirect,} from "react-router-dom"; Note: We make an alias of BrowserRouter as Router, just make things simple. Let’s see all the imported components one by one: BrowserRouter: It uses the HTML5 history API to keep the UI in sync with the URL. Route: Its responsibility is to render UI, when its path matches the current URL. Switch: It renders the first child Route or Redirect that matches the location. Redirect: It renders the new location irrespective of the current location in history stack. Here, is the code of the App.js file where We are going to implement the react-router-dom package. App.js import "./App.css";// importing components from react-router-dom packageimport { BrowserRouter as Router, Switch, Route, Redirect,} from "react-router-dom"; // import Home componentimport Home from "./components/Home";// import About componentimport About from "./components/About";// import ContactUs componentimport ContactUs from "./components/ContactUs"; function App() { return ( <> {/* This is the alias of BrowserRouter i.e. Router */} <Router> <Switch> {/* This route is for home component with exact path "/", in component props we passes the imported component*/} <Route exact path="/" component={Home} /> {/* This route is for about component with exact path "/about", in component props we passes the imported component*/} <Route path="/about" component={About} /> {/* This route is for contactus component with exact path "/contactus", in component props we passes the imported component*/} <Route path="/contactus" component={ContactUs} /> {/* If any route mismatches the upper route endpoints then, redirect triggers and redirects app to home component with to="/" */} <Redirect to="/" /> </Switch> </Router> </> );} export default App; Step 4: After implementing routing in App.js file, We have to give the routing end points at user side. So, We are going to give the routing endpoints in Home.jsx file. Here is the updated Home.jsx file. Home.jsx import React from "react";// importing Link from react-router-dom to navigate to // different end points.import { Link } from "react-router-dom"; const Home = () => { return ( <div> <h1>Home Page</h1> <br /> <ul> <li> {/* Endpoint to route to Home component */} <Link to="/">Home</Link> </li> <li> {/* Endpoint to route to About component */} <Link to="/about">About</Link> </li> <li> {/* Endpoint to route to Contact Us component */} <Link to="/contactus">Contact Us</Link> </li> </ul> </div> );}; export default Home; Step to run the application: Open the terminal and run the following command. npm start Output: React-app output Picked React-Questions routing TrueGeek-2021 ReactJS TrueGeek Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps How to remove duplicate elements from JavaScript Array ? Basics of API Testing Using Postman How to Convert Char to String in Java? Types of Internet Protocols SQL Statement to Remove Part of a String
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Oct, 2021" }, { "code": null, "e": 264, "s": 53, "text": "In this article, we are going to learn How to redirect to another page in ReactJS using react-router-dom package. ReactJS is a free and open source front-end library used for building single page applications. " }, { "code": null, "e": 380, "s": 264, "text": "react-router-dom: react-router-dom is a reactJS package, It enables you to implement dynamic routing in a web page." }, { "code": null, "e": 390, "s": 380, "text": "Approach:" }, { "code": null, "e": 414, "s": 390, "text": "Create basic react app." }, { "code": null, "e": 448, "s": 414, "text": "Make different pages for routing." }, { "code": null, "e": 482, "s": 448, "text": "Install react-router-dom package." }, { "code": null, "e": 532, "s": 482, "text": "Implement routing using react-router-dom package." }, { "code": null, "e": 611, "s": 532, "text": "Step 1: Create a basic react app using the following command in your terminal." }, { "code": null, "e": 647, "s": 611, "text": "npx create-react-app <project_name>" }, { "code": null, "e": 742, "s": 649, "text": "Project Structure: After creating the basic react app, the folder structure looks like this," }, { "code": null, "e": 772, "s": 742, "text": "Folder structure of react-app" }, { "code": null, "e": 929, "s": 772, "text": "Step 2: Make different pages for routing. Here, We are going to create different components for our react-app. So that we route over them for demonstration." }, { "code": null, "e": 981, "s": 929, "text": "Components: Home Page, About Page, ContactUs Page. " }, { "code": null, "e": 1046, "s": 981, "text": "After creating components, the Folder structure looks like this," }, { "code": null, "e": 1087, "s": 1046, "text": "Folder structure after making components" }, { "code": null, "e": 1096, "s": 1087, "text": "Home.jsx" }, { "code": "import React from \"react\"; const Home = () => { return ( <div> <h1>Home Page</h1> </div> );}; export default Home;", "e": 1226, "s": 1096, "text": null }, { "code": null, "e": 1236, "s": 1226, "text": "About.jsx" }, { "code": "import React from \"react\"; const About = () => { return ( <div> <h1>About Page</h1> </div> );}; export default About;", "e": 1369, "s": 1236, "text": null }, { "code": null, "e": 1383, "s": 1369, "text": "ContactUs.jsx" }, { "code": "import React from \"react\"; const ContactUs = () => { return ( <div> <h1>Contact Us Page</h1> </div> );}; export default ContactUs;", "e": 1529, "s": 1383, "text": null }, { "code": null, "e": 1571, "s": 1529, "text": "Step 3: Install react-router-dom package." }, { "code": null, "e": 1677, "s": 1571, "text": "Here, We are going to install the react-router-dom package in our react-app, using the following command." }, { "code": null, "e": 1700, "s": 1677, "text": "npm i react-router-dom" }, { "code": null, "e": 1728, "s": 1700, "text": "Installing react-router-dom" }, { "code": null, "e": 1805, "s": 1728, "text": "After installing react-router-dom package package.json file looks like this," }, { "code": null, "e": 1818, "s": 1805, "text": "Package.json" }, { "code": null, "e": 2096, "s": 1818, "text": "Step 3: Implement routing using the react-router-dom package. Here, We are going to implement the react-router-dom package in our react-app. To implement this, We have to import some components from the react-router-dom package i.e. BrowserRouter, Switch, Route, and Redirect." }, { "code": null, "e": 2186, "s": 2096, "text": "import { BrowserRouter as Router, Switch, \n Route, Redirect,} from \"react-router-dom\";" }, { "code": null, "e": 2263, "s": 2186, "text": "Note: We make an alias of BrowserRouter as Router, just make things simple." }, { "code": null, "e": 2313, "s": 2263, "text": "Let’s see all the imported components one by one:" }, { "code": null, "e": 2395, "s": 2313, "text": "BrowserRouter: It uses the HTML5 history API to keep the UI in sync with the URL." }, { "code": null, "e": 2477, "s": 2395, "text": "Route: Its responsibility is to render UI, when its path matches the current URL." }, { "code": null, "e": 2557, "s": 2477, "text": "Switch: It renders the first child Route or Redirect that matches the location." }, { "code": null, "e": 2650, "s": 2557, "text": "Redirect: It renders the new location irrespective of the current location in history stack." }, { "code": null, "e": 2749, "s": 2650, "text": "Here, is the code of the App.js file where We are going to implement the react-router-dom package." }, { "code": null, "e": 2756, "s": 2749, "text": "App.js" }, { "code": "import \"./App.css\";// importing components from react-router-dom packageimport { BrowserRouter as Router, Switch, Route, Redirect,} from \"react-router-dom\"; // import Home componentimport Home from \"./components/Home\";// import About componentimport About from \"./components/About\";// import ContactUs componentimport ContactUs from \"./components/ContactUs\"; function App() { return ( <> {/* This is the alias of BrowserRouter i.e. Router */} <Router> <Switch> {/* This route is for home component with exact path \"/\", in component props we passes the imported component*/} <Route exact path=\"/\" component={Home} /> {/* This route is for about component with exact path \"/about\", in component props we passes the imported component*/} <Route path=\"/about\" component={About} /> {/* This route is for contactus component with exact path \"/contactus\", in component props we passes the imported component*/} <Route path=\"/contactus\" component={ContactUs} /> {/* If any route mismatches the upper route endpoints then, redirect triggers and redirects app to home component with to=\"/\" */} <Redirect to=\"/\" /> </Switch> </Router> </> );} export default App;", "e": 4139, "s": 2756, "text": null }, { "code": null, "e": 4308, "s": 4139, "text": "Step 4: After implementing routing in App.js file, We have to give the routing end points at user side. So, We are going to give the routing endpoints in Home.jsx file." }, { "code": null, "e": 4344, "s": 4308, "text": "Here is the updated Home.jsx file. " }, { "code": null, "e": 4353, "s": 4344, "text": "Home.jsx" }, { "code": "import React from \"react\";// importing Link from react-router-dom to navigate to // different end points.import { Link } from \"react-router-dom\"; const Home = () => { return ( <div> <h1>Home Page</h1> <br /> <ul> <li> {/* Endpoint to route to Home component */} <Link to=\"/\">Home</Link> </li> <li> {/* Endpoint to route to About component */} <Link to=\"/about\">About</Link> </li> <li> {/* Endpoint to route to Contact Us component */} <Link to=\"/contactus\">Contact Us</Link> </li> </ul> </div> );}; export default Home;", "e": 4999, "s": 4353, "text": null }, { "code": null, "e": 5077, "s": 4999, "text": "Step to run the application: Open the terminal and run the following command." }, { "code": null, "e": 5087, "s": 5077, "text": "npm start" }, { "code": null, "e": 5096, "s": 5087, "text": "Output: " }, { "code": null, "e": 5113, "s": 5096, "text": "React-app output" }, { "code": null, "e": 5120, "s": 5113, "text": "Picked" }, { "code": null, "e": 5136, "s": 5120, "text": "React-Questions" }, { "code": null, "e": 5144, "s": 5136, "text": "routing" }, { "code": null, "e": 5158, "s": 5144, "text": "TrueGeek-2021" }, { "code": null, "e": 5166, "s": 5158, "text": "ReactJS" }, { "code": null, "e": 5175, "s": 5166, "text": "TrueGeek" }, { "code": null, "e": 5192, "s": 5175, "text": "Web Technologies" }, { "code": null, "e": 5290, "s": 5192, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5328, "s": 5290, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 5347, "s": 5328, "text": "ReactJS setState()" }, { "code": null, "e": 5415, "s": 5347, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 5450, "s": 5415, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 5471, "s": 5450, "text": "ReactJS defaultProps" }, { "code": null, "e": 5528, "s": 5471, "text": "How to remove duplicate elements from JavaScript Array ?" }, { "code": null, "e": 5564, "s": 5528, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 5603, "s": 5564, "text": "How to Convert Char to String in Java?" }, { "code": null, "e": 5631, "s": 5603, "text": "Types of Internet Protocols" } ]
Zoom Scroll View in Android
21 Apr, 2021 In this article, we are going to implement zoom on ScrollView. Most of the time when we create a scroll view then it contains a lot of data and if we want to view any content on zooming then we can implement this feature. This feature can be useful when we are scroll in an App and that contains data using RecyclerView. There we can implement this feature to see the data inside RecyclerView by zoom in. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Working with the 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" tools:context=".MainActivity"> <ScrollView android:id="@+id/scrollView" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#1B5E20"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Zoom Scroll View" android:textSize="32sp" /> </ScrollView> </RelativeLayout> Step 3: Working with the MainActivity.java file Below is the code for the implementation of this feature. // implementation of this feature mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener(){ @Override public boolean onScale(ScaleGestureDetector detector) { // firstly we will get the scale factor by which we want to zoom float scale = 1 - detector.getScaleFactor(); float prevScale = mScale; mScale += scale; // we can maximise our focus to 10f only if (mScale > 10f) mScale = 10f; ScaleAnimation scaleAnimation = new ScaleAnimation(1f / prevScale, 1f / mScale, 1f / prevScale, 1f / mScale, detector.getFocusX(), detector.getFocusY()); // duration of animation will be 0.It will not change by self after that scaleAnimation.setDuration(0); scaleAnimation.setFillAfter(true); // initialising the scrollview ScrollView layout = (ScrollView) findViewById(R.id.scrollView); // we are setting it as animation layout.startAnimation(scaleAnimation); return true; } }); Below is the complete 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.view.GestureDetector;import android.view.MotionEvent;import android.view.ScaleGestureDetector;import android.view.animation.ScaleAnimation;import android.widget.ScrollView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; private float mScale = 1f; private ScaleGestureDetector mScaleGestureDetector; GestureDetector gestureDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialising the values gestureDetector = new GestureDetector(this, new GestureListener()); mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { // firstly we will get the scale factor float scale = 1 - detector.getScaleFactor(); float prevScale = mScale; mScale += scale; // we can maximise our focus to 10f only if (mScale > 10f) mScale = 10f; ScaleAnimation scaleAnimation = new ScaleAnimation(1f / prevScale, 1f / mScale, 1f / prevScale, 1f / mScale, detector.getFocusX(), detector.getFocusY()); // duration of animation will be 0.It will // not change by self after that scaleAnimation.setDuration(0); scaleAnimation.setFillAfter(true); // initialising the scrollview ScrollView layout = (ScrollView) findViewById(R.id.scrollView); // we are setting it as animation layout.startAnimation(scaleAnimation); return true; } }); } @Override public boolean dispatchTouchEvent(MotionEvent event) { super.dispatchTouchEvent(event); // special types of touch screen events such as pinch , // double tap, scrolls , long presses and flinch, // onTouch event is called if found any of these mScaleGestureDetector.onTouchEvent(event); gestureDetector.onTouchEvent(event); return gestureDetector.onTouchEvent(event); } private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onDoubleTap(MotionEvent e) { return true; } }} Output: Android-View Android Java 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": "\n21 Apr, 2021" }, { "code": null, "e": 598, "s": 28, "text": "In this article, we are going to implement zoom on ScrollView. Most of the time when we create a scroll view then it contains a lot of data and if we want to view any content on zooming then we can implement this feature. This feature can be useful when we are scroll in an App and that contains data using RecyclerView. There we can implement this feature to see the data inside RecyclerView by zoom in. A sample GIF 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": 627, "s": 598, "text": "Step 1: Create a New Project" }, { "code": null, "e": 789, "s": 627, "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": 837, "s": 789, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 980, "s": 837, "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": 984, "s": 980, "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\" tools:context=\".MainActivity\"> <ScrollView android:id=\"@+id/scrollView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#1B5E20\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Zoom Scroll View\" android:textSize=\"32sp\" /> </ScrollView> </RelativeLayout>", "e": 1682, "s": 984, "text": null }, { "code": null, "e": 1730, "s": 1682, "text": "Step 3: Working with the MainActivity.java file" }, { "code": null, "e": 1788, "s": 1730, "text": "Below is the code for the implementation of this feature." }, { "code": null, "e": 3098, "s": 1788, "text": "// implementation of this feature\nmScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener(){\n @Override\n public boolean onScale(ScaleGestureDetector detector) {\n // firstly we will get the scale factor by which we want to zoom\n float scale = 1 - detector.getScaleFactor();\n float prevScale = mScale;\n mScale += scale;\n \n // we can maximise our focus to 10f only\n if (mScale > 10f)\n mScale = 10f;\n \n ScaleAnimation scaleAnimation = new ScaleAnimation(1f / prevScale, 1f / mScale, 1f / prevScale, 1f / mScale, detector.getFocusX(), detector.getFocusY());\n \n // duration of animation will be 0.It will not change by self after that \n scaleAnimation.setDuration(0);\n \n scaleAnimation.setFillAfter(true);\n \n // initialising the scrollview\n ScrollView layout = (ScrollView) findViewById(R.id.scrollView);\n \n // we are setting it as animation\n layout.startAnimation(scaleAnimation);\n return true;\n }\n });" }, { "code": null, "e": 3231, "s": 3098, "text": "Below is the complete code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3236, "s": 3231, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.GestureDetector;import android.view.MotionEvent;import android.view.ScaleGestureDetector;import android.view.animation.ScaleAnimation;import android.widget.ScrollView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private static final String TAG = \"MainActivity\"; private float mScale = 1f; private ScaleGestureDetector mScaleGestureDetector; GestureDetector gestureDetector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initialising the values gestureDetector = new GestureDetector(this, new GestureListener()); mScaleGestureDetector = new ScaleGestureDetector(this, new ScaleGestureDetector.SimpleOnScaleGestureListener() { @Override public boolean onScale(ScaleGestureDetector detector) { // firstly we will get the scale factor float scale = 1 - detector.getScaleFactor(); float prevScale = mScale; mScale += scale; // we can maximise our focus to 10f only if (mScale > 10f) mScale = 10f; ScaleAnimation scaleAnimation = new ScaleAnimation(1f / prevScale, 1f / mScale, 1f / prevScale, 1f / mScale, detector.getFocusX(), detector.getFocusY()); // duration of animation will be 0.It will // not change by self after that scaleAnimation.setDuration(0); scaleAnimation.setFillAfter(true); // initialising the scrollview ScrollView layout = (ScrollView) findViewById(R.id.scrollView); // we are setting it as animation layout.startAnimation(scaleAnimation); return true; } }); } @Override public boolean dispatchTouchEvent(MotionEvent event) { super.dispatchTouchEvent(event); // special types of touch screen events such as pinch , // double tap, scrolls , long presses and flinch, // onTouch event is called if found any of these mScaleGestureDetector.onTouchEvent(event); gestureDetector.onTouchEvent(event); return gestureDetector.onTouchEvent(event); } private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDown(MotionEvent e) { return true; } @Override public boolean onDoubleTap(MotionEvent e) { return true; } }}", "e": 6011, "s": 3236, "text": null }, { "code": null, "e": 6019, "s": 6011, "text": "Output:" }, { "code": null, "e": 6032, "s": 6019, "text": "Android-View" }, { "code": null, "e": 6040, "s": 6032, "text": "Android" }, { "code": null, "e": 6045, "s": 6040, "text": "Java" }, { "code": null, "e": 6050, "s": 6045, "text": "Java" }, { "code": null, "e": 6058, "s": 6050, "text": "Android" } ]
Python | Pandas dataframe.isna()
19 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.isna() function is used to detect missing values. It return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings ” or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True). Syntax: DataFrame.isna() Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value. For link to the CSV file used in the example, click here Example #1: Use isna() function to detect the missing values in a dataframe. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv("nba.csv") # Print the dataframedf Lets use the isna() function to detect the missing values. # detect the missing valuesdf.isna() Output :In the output, cells corresponding to the missing values contains true value else false. Example #2: Use isna() function to detect missing values in a pandas series object # importing pandas as pdimport pandas as pd # Creating the series sr = pd.Series([12, 5, None, 5, None, 11]) # Print the seriessr Let’s detect all the missing values in the series. # to detect the missing valuessr.isna() Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas 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 Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Nov, 2018" }, { "code": null, "e": 242, "s": 28, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 627, "s": 242, "text": "Pandas dataframe.isna() function is used to detect missing values. It return a boolean same-sized object indicating if the values are NA. NA values, such as None or numpy.NaN, gets mapped to True values. Everything else gets mapped to False values. Characters such as empty strings ” or numpy.inf are not considered NA values (unless you set pandas.options.mode.use_inf_as_na = True)." }, { "code": null, "e": 652, "s": 627, "text": "Syntax: DataFrame.isna()" }, { "code": null, "e": 766, "s": 652, "text": "Returns : Mask of bool values for each element in DataFrame that indicates whether an element is not an NA value." }, { "code": null, "e": 823, "s": 766, "text": "For link to the CSV file used in the example, click here" }, { "code": null, "e": 900, "s": 823, "text": "Example #1: Use isna() function to detect the missing values in a dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv(\"nba.csv\") # Print the dataframedf", "e": 1023, "s": 900, "text": null }, { "code": null, "e": 1082, "s": 1023, "text": "Lets use the isna() function to detect the missing values." }, { "code": "# detect the missing valuesdf.isna()", "e": 1119, "s": 1082, "text": null }, { "code": null, "e": 1299, "s": 1119, "text": "Output :In the output, cells corresponding to the missing values contains true value else false. Example #2: Use isna() function to detect missing values in a pandas series object" }, { "code": "# importing pandas as pdimport pandas as pd # Creating the series sr = pd.Series([12, 5, None, 5, None, 11]) # Print the seriessr", "e": 1431, "s": 1299, "text": null }, { "code": null, "e": 1482, "s": 1431, "text": "Let’s detect all the missing values in the series." }, { "code": "# to detect the missing valuessr.isna()", "e": 1522, "s": 1482, "text": null }, { "code": null, "e": 1531, "s": 1522, "text": "Output :" }, { "code": null, "e": 1555, "s": 1531, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1587, "s": 1555, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 1601, "s": 1587, "text": "Python-pandas" }, { "code": null, "e": 1608, "s": 1601, "text": "Python" }, { "code": null, "e": 1706, "s": 1608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1724, "s": 1706, "text": "Python Dictionary" }, { "code": null, "e": 1766, "s": 1724, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1788, "s": 1766, "text": "Enumerate() in Python" }, { "code": null, "e": 1823, "s": 1788, "text": "Read a file line by line in Python" }, { "code": null, "e": 1849, "s": 1823, "text": "Python String | replace()" }, { "code": null, "e": 1881, "s": 1849, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1910, "s": 1881, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1937, "s": 1910, "text": "Python Classes and Objects" }, { "code": null, "e": 1958, "s": 1937, "text": "Python OOPs Concepts" } ]
Java Program to Convert String to String Array
19 May, 2022 Given a String, the task is to convert the string into an Array of Strings in Java. It is illustrated in the below illustration which is as follows: Illustration: Input: String : "Geeks for Geeks" Output: String[]: [Geeks for Geeks] Input: String : "A computer science portal" Output: String[] : [A computer science portal] Methods: They are as follows: Using str.split() methodUsing loopsUsing Set.toArray() methodUsing String tokenizerUsing pattern.split() method Using str.split() method Using loops Using Set.toArray() method Using String tokenizer Using pattern.split() method Lets us now discuss every method in depth implementing the same to get a better understanding of the same. They are as follows: Method 1: Using str.split() method Approach: Create an array with string type. Split the given string using string_name.split(). Store splitted array into string array. Print the above string array. Example Java // Java Program to Convert String to String Array// Using str.split() method // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input string to be convert to string array String str = "Geeks for Geeks"; String strArray[] = str.split(" "); System.out.println("String : " + str); System.out.println("String array : [ "); // Iterating over the string for (int i = 0; i < strArray.length; i++) { // Printing the elements of String array System.out.print(strArray[i] + ", "); } System.out.print("]"); }} String : Geeks for Geeks String array : [ Geeks, for, Geeks, ] Method 2: Using loops Approach: Get the set of strings. Create an empty string array Use advanced for loop, copy each element of set to the string array Print the string array. Example: Java // Java Program to Convert String to String Array// Using HashSet and Set classes // Importing required classes from respective packagesimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set; // Main classclass GFG { // Method 1 // To convert Set<String> to String[] public static String[] method(Set<String> string) { // Create String[] of size of setOfString String[] string_array = new String[string.size()]; // Copy elements from set to string array // using advanced for loop int index = 0; for (String str : string) { string_array[index++] = str; } // Return the formed String[] return string_array; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string String str = "Geeks for Geeks"; // Getting the Set of String Set<String> string_set = new HashSet<>(Arrays.asList(str)); // Printing the setOfString System.out.println("String: " + str); // Converting Set to String array String[] String_array = method(string_set); // Lastly printing the arrayOfString // using Arrays.toString() method System.out.println("Array of String: " + Arrays.toString(String_array)); }} String: Geeks for Geeks Array of String: [Geeks for Geeks] Method 3: Using Set.toArray() method Approach: Convert the given string into set of string. Now create an empty string array. Convert the string set to Array of string using set.toArray() by passing an empty array of type string. Print the array of string. Example: Java // Java Program to Convert String to String Array// Using Set.toArray() method // Importing required classes from respective packagesimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set; // Main classpublic class GFG { // Method 1 // To convert Set<String> to string array public static String[] convert(Set<String> setOfString) { // Create String[] from setOfString String[] arrayOfString = setOfString.toArray(new String[0]); // return the formed String[] return arrayOfString; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string as input String str = "Geeks for Geeks"; // Getting the Set of String Set<String> string = new HashSet<>(Arrays.asList(str)); // Printing the setOfString System.out.println("String: " + str); // Converting Set to String array String[] string_array = convert(string); // Print the arrayOfString // using Arrays.toString() method System.out.println("String array : " + Arrays.toString(string_array)); }} String: Geeks for Geeks String array : [Geeks for Geeks] Method 4: Using String tokenizer String tokenizer helps to split a string object into smaller and smaller parts. These smaller parts are known as tokens. Tokenize the given stringCreate an array of type string with the size of token counts.Store these tokens into a string array.Print the string array. Tokenize the given string Create an array of type string with the size of token counts. Store these tokens into a string array. Print the string array. Example: Java // Java Program to Convert String to String Array// Using Set.toArray() method // Importing required classes from respective packagesimport java.io.*;import java.util.StringTokenizer; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing integer variable // to zero int i = 0; // Custom input string as input String str = "Geeks for Geeks"; // Tokenize a given string using the default // delimiter StringTokenizer str_tokenizer = new StringTokenizer(str); String[] string_array = new String[str_tokenizer.countTokens()]; // Add tokens to our array while (str_tokenizer.hasMoreTokens()) { string_array[i] = str_tokenizer.nextToken(); i++; } // Print and display the string System.out.print("String :" + str); // Display message System.out.print("\nString array : [ "); // Printing the string array // using for each loop for (String string : string_array) { System.out.print(string + " "); } System.out.print("]"); }} String :Geeks for Geeks String array : [ Geeks for Geeks ] Method 5: Using pattern.split() method The purpose of this pattern.split() method is to break the given string into an array according to a given pattern. We can split our string by giving some specific pattern. Approach: Define pattern (REGEX)Then create a pattern using the compilation methodThen split the string using pattern.split() with a specific pattern and store it in the array.Print the string array Define pattern (REGEX) Then create a pattern using the compilation method Then split the string using pattern.split() with a specific pattern and store it in the array. Print the string array Example: Java // Java Program to Convert String to String Array// Using Set.toArray() method // Importing required classes from respective packagesimport java.io.*;import java.util.regex.Pattern; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom string as input String str = "Geeks for Geeks"; // Step 1: Define REGEX String my_pattern = "\\s"; // Step 2: Create a pattern using compile method Pattern pattern = Pattern.compile(my_pattern); // Step 3: Create an array of strings using the // pattern we already defined String[] string_array = pattern.split(str); // Print and display string and // its corresponding string array System.out.print("String : " + str); System.out.print("\nString array : [ "); // Iterating over the string for (int i = 0; i < string_array.length; i++) { // Printing the string array System.out.print(string_array[i] + " "); } System.out.print("]"); }} String : Geeks for Geeks String array : [ Geeks for Geeks ] anikakapoor surindertarika1234 kapoorsagar226 saurabh1990aror sumitgumber28 Java-String-Programs Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 53, "s": 25, "text": "\n19 May, 2022" }, { "code": null, "e": 202, "s": 53, "text": "Given a String, the task is to convert the string into an Array of Strings in Java. It is illustrated in the below illustration which is as follows:" }, { "code": null, "e": 216, "s": 202, "text": "Illustration:" }, { "code": null, "e": 287, "s": 216, "text": "Input: String : \"Geeks for Geeks\"\nOutput: String[]: [Geeks for Geeks]" }, { "code": null, "e": 381, "s": 287, "text": "Input: String : \"A computer science portal\"\nOutput: String[] : [A computer science portal]" }, { "code": null, "e": 390, "s": 381, "text": "Methods:" }, { "code": null, "e": 411, "s": 390, "text": "They are as follows:" }, { "code": null, "e": 523, "s": 411, "text": "Using str.split() methodUsing loopsUsing Set.toArray() methodUsing String tokenizerUsing pattern.split() method" }, { "code": null, "e": 548, "s": 523, "text": "Using str.split() method" }, { "code": null, "e": 560, "s": 548, "text": "Using loops" }, { "code": null, "e": 587, "s": 560, "text": "Using Set.toArray() method" }, { "code": null, "e": 610, "s": 587, "text": "Using String tokenizer" }, { "code": null, "e": 639, "s": 610, "text": "Using pattern.split() method" }, { "code": null, "e": 768, "s": 639, "text": "Lets us now discuss every method in depth implementing the same to get a better understanding of the same. They are as follows: " }, { "code": null, "e": 804, "s": 768, "text": "Method 1: Using str.split() method " }, { "code": null, "e": 814, "s": 804, "text": "Approach:" }, { "code": null, "e": 848, "s": 814, "text": "Create an array with string type." }, { "code": null, "e": 898, "s": 848, "text": "Split the given string using string_name.split()." }, { "code": null, "e": 938, "s": 898, "text": "Store splitted array into string array." }, { "code": null, "e": 968, "s": 938, "text": "Print the above string array." }, { "code": null, "e": 976, "s": 968, "text": "Example" }, { "code": null, "e": 981, "s": 976, "text": "Java" }, { "code": "// Java Program to Convert String to String Array// Using str.split() method // Importing input output classesimport java.io.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input string to be convert to string array String str = \"Geeks for Geeks\"; String strArray[] = str.split(\" \"); System.out.println(\"String : \" + str); System.out.println(\"String array : [ \"); // Iterating over the string for (int i = 0; i < strArray.length; i++) { // Printing the elements of String array System.out.print(strArray[i] + \", \"); } System.out.print(\"]\"); }}", "e": 1679, "s": 981, "text": null }, { "code": null, "e": 1743, "s": 1679, "text": "String : Geeks for Geeks\nString array : [ \nGeeks, for, Geeks, ]" }, { "code": null, "e": 1766, "s": 1743, "text": "Method 2: Using loops " }, { "code": null, "e": 1777, "s": 1766, "text": "Approach: " }, { "code": null, "e": 1801, "s": 1777, "text": "Get the set of strings." }, { "code": null, "e": 1830, "s": 1801, "text": "Create an empty string array" }, { "code": null, "e": 1898, "s": 1830, "text": "Use advanced for loop, copy each element of set to the string array" }, { "code": null, "e": 1922, "s": 1898, "text": "Print the string array." }, { "code": null, "e": 1931, "s": 1922, "text": "Example:" }, { "code": null, "e": 1936, "s": 1931, "text": "Java" }, { "code": "// Java Program to Convert String to String Array// Using HashSet and Set classes // Importing required classes from respective packagesimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set; // Main classclass GFG { // Method 1 // To convert Set<String> to String[] public static String[] method(Set<String> string) { // Create String[] of size of setOfString String[] string_array = new String[string.size()]; // Copy elements from set to string array // using advanced for loop int index = 0; for (String str : string) { string_array[index++] = str; } // Return the formed String[] return string_array; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string String str = \"Geeks for Geeks\"; // Getting the Set of String Set<String> string_set = new HashSet<>(Arrays.asList(str)); // Printing the setOfString System.out.println(\"String: \" + str); // Converting Set to String array String[] String_array = method(string_set); // Lastly printing the arrayOfString // using Arrays.toString() method System.out.println(\"Array of String: \" + Arrays.toString(String_array)); }}", "e": 3315, "s": 1936, "text": null }, { "code": null, "e": 3374, "s": 3315, "text": "String: Geeks for Geeks\nArray of String: [Geeks for Geeks]" }, { "code": null, "e": 3411, "s": 3374, "text": "Method 3: Using Set.toArray() method" }, { "code": null, "e": 3421, "s": 3411, "text": "Approach:" }, { "code": null, "e": 3466, "s": 3421, "text": "Convert the given string into set of string." }, { "code": null, "e": 3500, "s": 3466, "text": "Now create an empty string array." }, { "code": null, "e": 3604, "s": 3500, "text": "Convert the string set to Array of string using set.toArray() by passing an empty array of type string." }, { "code": null, "e": 3631, "s": 3604, "text": "Print the array of string." }, { "code": null, "e": 3640, "s": 3631, "text": "Example:" }, { "code": null, "e": 3645, "s": 3640, "text": "Java" }, { "code": "// Java Program to Convert String to String Array// Using Set.toArray() method // Importing required classes from respective packagesimport java.io.*;import java.util.Arrays;import java.util.HashSet;import java.util.Set; // Main classpublic class GFG { // Method 1 // To convert Set<String> to string array public static String[] convert(Set<String> setOfString) { // Create String[] from setOfString String[] arrayOfString = setOfString.toArray(new String[0]); // return the formed String[] return arrayOfString; } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string as input String str = \"Geeks for Geeks\"; // Getting the Set of String Set<String> string = new HashSet<>(Arrays.asList(str)); // Printing the setOfString System.out.println(\"String: \" + str); // Converting Set to String array String[] string_array = convert(string); // Print the arrayOfString // using Arrays.toString() method System.out.println(\"String array : \" + Arrays.toString(string_array)); }}", "e": 4853, "s": 3645, "text": null }, { "code": null, "e": 4910, "s": 4853, "text": "String: Geeks for Geeks\nString array : [Geeks for Geeks]" }, { "code": null, "e": 4943, "s": 4910, "text": "Method 4: Using String tokenizer" }, { "code": null, "e": 5064, "s": 4943, "text": "String tokenizer helps to split a string object into smaller and smaller parts. These smaller parts are known as tokens." }, { "code": null, "e": 5213, "s": 5064, "text": "Tokenize the given stringCreate an array of type string with the size of token counts.Store these tokens into a string array.Print the string array." }, { "code": null, "e": 5239, "s": 5213, "text": "Tokenize the given string" }, { "code": null, "e": 5301, "s": 5239, "text": "Create an array of type string with the size of token counts." }, { "code": null, "e": 5341, "s": 5301, "text": "Store these tokens into a string array." }, { "code": null, "e": 5365, "s": 5341, "text": "Print the string array." }, { "code": null, "e": 5374, "s": 5365, "text": "Example:" }, { "code": null, "e": 5379, "s": 5374, "text": "Java" }, { "code": "// Java Program to Convert String to String Array// Using Set.toArray() method // Importing required classes from respective packagesimport java.io.*;import java.util.StringTokenizer; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Declaring and initializing integer variable // to zero int i = 0; // Custom input string as input String str = \"Geeks for Geeks\"; // Tokenize a given string using the default // delimiter StringTokenizer str_tokenizer = new StringTokenizer(str); String[] string_array = new String[str_tokenizer.countTokens()]; // Add tokens to our array while (str_tokenizer.hasMoreTokens()) { string_array[i] = str_tokenizer.nextToken(); i++; } // Print and display the string System.out.print(\"String :\" + str); // Display message System.out.print(\"\\nString array : [ \"); // Printing the string array // using for each loop for (String string : string_array) { System.out.print(string + \" \"); } System.out.print(\"]\"); }}", "e": 6591, "s": 5379, "text": null }, { "code": null, "e": 6650, "s": 6591, "text": "String :Geeks for Geeks\nString array : [ Geeks for Geeks ]" }, { "code": null, "e": 6689, "s": 6650, "text": "Method 5: Using pattern.split() method" }, { "code": null, "e": 6863, "s": 6689, "text": "The purpose of this pattern.split() method is to break the given string into an array according to a given pattern. We can split our string by giving some specific pattern. " }, { "code": null, "e": 6873, "s": 6863, "text": "Approach:" }, { "code": null, "e": 7062, "s": 6873, "text": "Define pattern (REGEX)Then create a pattern using the compilation methodThen split the string using pattern.split() with a specific pattern and store it in the array.Print the string array" }, { "code": null, "e": 7085, "s": 7062, "text": "Define pattern (REGEX)" }, { "code": null, "e": 7136, "s": 7085, "text": "Then create a pattern using the compilation method" }, { "code": null, "e": 7231, "s": 7136, "text": "Then split the string using pattern.split() with a specific pattern and store it in the array." }, { "code": null, "e": 7254, "s": 7231, "text": "Print the string array" }, { "code": null, "e": 7263, "s": 7254, "text": "Example:" }, { "code": null, "e": 7268, "s": 7263, "text": "Java" }, { "code": "// Java Program to Convert String to String Array// Using Set.toArray() method // Importing required classes from respective packagesimport java.io.*;import java.util.regex.Pattern; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom string as input String str = \"Geeks for Geeks\"; // Step 1: Define REGEX String my_pattern = \"\\\\s\"; // Step 2: Create a pattern using compile method Pattern pattern = Pattern.compile(my_pattern); // Step 3: Create an array of strings using the // pattern we already defined String[] string_array = pattern.split(str); // Print and display string and // its corresponding string array System.out.print(\"String : \" + str); System.out.print(\"\\nString array : [ \"); // Iterating over the string for (int i = 0; i < string_array.length; i++) { // Printing the string array System.out.print(string_array[i] + \" \"); } System.out.print(\"]\"); }}", "e": 8350, "s": 7268, "text": null }, { "code": null, "e": 8410, "s": 8350, "text": "String : Geeks for Geeks\nString array : [ Geeks for Geeks ]" }, { "code": null, "e": 8422, "s": 8410, "text": "anikakapoor" }, { "code": null, "e": 8441, "s": 8422, "text": "surindertarika1234" }, { "code": null, "e": 8456, "s": 8441, "text": "kapoorsagar226" }, { "code": null, "e": 8472, "s": 8456, "text": "saurabh1990aror" }, { "code": null, "e": 8486, "s": 8472, "text": "sumitgumber28" }, { "code": null, "e": 8507, "s": 8486, "text": "Java-String-Programs" }, { "code": null, "e": 8514, "s": 8507, "text": "Picked" }, { "code": null, "e": 8519, "s": 8514, "text": "Java" }, { "code": null, "e": 8533, "s": 8519, "text": "Java Programs" }, { "code": null, "e": 8538, "s": 8533, "text": "Java" }, { "code": null, "e": 8636, "s": 8538, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8651, "s": 8636, "text": "Stream In Java" }, { "code": null, "e": 8672, "s": 8651, "text": "Introduction to Java" }, { "code": null, "e": 8693, "s": 8672, "text": "Constructors in Java" }, { "code": null, "e": 8712, "s": 8693, "text": "Exceptions in Java" }, { "code": null, "e": 8729, "s": 8712, "text": "Generics in Java" }, { "code": null, "e": 8755, "s": 8729, "text": "Java Programming Examples" }, { "code": null, "e": 8789, "s": 8755, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 8836, "s": 8789, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 8874, "s": 8836, "text": "Factory method design pattern in Java" } ]
Flutter – Staggered Grid View
15 Feb, 2021 Staggered Grid View is a type of layout that is used to display images and posts. As you see in various social platforms such as Pinterest and many more. The main feature of Staggered Grid View is that it makes the layout beautiful and develop a great User Experience. Staggered Grid View consists of containers present in Rows and columns of different sizes. Which displays images and posts of various sizes. Set crossAxiscount & minAxiscount to the Grid view Main_axis extent of tiles may be fixed or multiple of cell’s length. Configurable main-axis and cross-axis margins between tiles. SliverStaggeredGrid for using in a CustomScrollView. Staggered and Spannable grid layouts. In this article, we are going to see how to implement Staggered Grid View in our Flutter Application. To build this follow the below steps. Add the dependency to pubspec.yaml file. dependencies: flutter_staggered_grid_view: ^0.3.2 Import the dependency to the main.dart file import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; Now, Let’s look into the implementation of Staggered Grid View. To do so follow the below steps: Step 1:For Implementing Staggered Grid View in your project first you have to add the dependency in your pubspec.yaml file in the lib folder. Now click on pub.get and wait to configure it. Step 2: Return Material App in main.dart() file. First, create MyApp() in StatelessWidget and in it return MaterialApp(). Now in MaterialApp() give the title of the app and add debugShowCheckModeBanner as false which will remove the debug banner in the app. Now add the Theme as Dark theme and after that represent first screen home: Homepage() Dart void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, //Title of an App title: 'GFG APP', //Theme of an App theme: ThemeData( primarySwatch: Colors.green, ), darkTheme: ThemeData.dark(), // First Screen of App home: HomePage(), ); }} Step 3: Now Import dependencies for Staggered Grid View in HomePage(). After Importing dependency create app bar inside the Scaffold. Now create a new Container() in the body. In that Container now implement Staggered Grid View as shown in the code below. Inside the Staggered Grid view, there is staggeredTiles. For which we have declared a List of 10 _cardTile which specify the size of your cards. After that, we have created a class BackGroundTile in StatelessWidget. In which we have declared two final variables backgroundColor and icon data. We have created a constructor for these variables. And returned Card which consists of backgroundColor and icondata. In Staggered Grid View we have declared children as _listTile. For which we have created a List which inherits properties from class BackGroundTile. Which consist of backgroundColor and icondata. Dart import 'package:flutter/material.dart';import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; //List of Cards with sizeList<StaggeredTile> _cardTile = <StaggeredTile> [ StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2),]; //List of Cards with color and iconList<Widget>_listTile = <Widget>[ BackGroundTile(backgroundColor: Colors.red, icondata: Icons.home), BackGroundTile(backgroundColor: Colors.orange, icondata: Icons.ac_unit), BackGroundTile(backgroundColor: Colors.pink, icondata: Icons.landscape), BackGroundTile(backgroundColor: Colors.green, icondata: Icons.portrait), BackGroundTile(backgroundColor: Colors.deepPurpleAccent, icondata: Icons.music_note), BackGroundTile(backgroundColor: Colors.blue, icondata: Icons.access_alarms), BackGroundTile(backgroundColor: Colors.indigo, icondata: Icons.satellite_outlined), BackGroundTile(backgroundColor: Colors.cyan, icondata: Icons.search_sharp), BackGroundTile(backgroundColor: Colors.yellowAccent, icondata: Icons.adjust_rounded), BackGroundTile(backgroundColor: Colors.deepOrange, icondata: Icons.attach_money),]; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("GFG App"), ), body: Container( // Staggered Grid View starts here child: StaggeredGridView.count( crossAxisCount: 4, staggeredTiles: _cardTile, children: _listTile, mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, ), ), ); }}class BackGroundTile extends StatelessWidget { final Color backgroundColor; final IconData icondata; BackGroundTile({this.backgroundColor, this.icondata}); @override Widget build(BuildContext context) { return Card( color: backgroundColor, child: Icon(icondata, color: Colors.white), ); }} Output: android Flutter Flutter UI-components Dart Flutter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Flutter - DropDownButton Widget Listview.builder in Flutter Flutter - Custom Bottom Navigation Bar Splash Screen in Flutter Flutter - Asset Image Flutter - DropDownButton Widget Flutter - Custom Bottom Navigation Bar Flutter - Checkbox Widget Flutter - Stack Widget Flutter - Search Bar
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Feb, 2021" }, { "code": null, "e": 438, "s": 28, "text": "Staggered Grid View is a type of layout that is used to display images and posts. As you see in various social platforms such as Pinterest and many more. The main feature of Staggered Grid View is that it makes the layout beautiful and develop a great User Experience. Staggered Grid View consists of containers present in Rows and columns of different sizes. Which displays images and posts of various sizes." }, { "code": null, "e": 489, "s": 438, "text": "Set crossAxiscount & minAxiscount to the Grid view" }, { "code": null, "e": 558, "s": 489, "text": "Main_axis extent of tiles may be fixed or multiple of cell’s length." }, { "code": null, "e": 619, "s": 558, "text": "Configurable main-axis and cross-axis margins between tiles." }, { "code": null, "e": 672, "s": 619, "text": "SliverStaggeredGrid for using in a CustomScrollView." }, { "code": null, "e": 710, "s": 672, "text": "Staggered and Spannable grid layouts." }, { "code": null, "e": 850, "s": 710, "text": "In this article, we are going to see how to implement Staggered Grid View in our Flutter Application. To build this follow the below steps." }, { "code": null, "e": 891, "s": 850, "text": "Add the dependency to pubspec.yaml file." }, { "code": null, "e": 946, "s": 891, "text": "dependencies:\n flutter_staggered_grid_view: ^0.3.2\n" }, { "code": null, "e": 990, "s": 946, "text": "Import the dependency to the main.dart file" }, { "code": null, "e": 1069, "s": 990, "text": "import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';" }, { "code": null, "e": 1166, "s": 1069, "text": "Now, Let’s look into the implementation of Staggered Grid View. To do so follow the below steps:" }, { "code": null, "e": 1355, "s": 1166, "text": "Step 1:For Implementing Staggered Grid View in your project first you have to add the dependency in your pubspec.yaml file in the lib folder. Now click on pub.get and wait to configure it." }, { "code": null, "e": 1700, "s": 1355, "text": "Step 2: Return Material App in main.dart() file. First, create MyApp() in StatelessWidget and in it return MaterialApp(). Now in MaterialApp() give the title of the app and add debugShowCheckModeBanner as false which will remove the debug banner in the app. Now add the Theme as Dark theme and after that represent first screen home: Homepage()" }, { "code": null, "e": 1705, "s": 1700, "text": "Dart" }, { "code": "void main() { runApp(MyApp());} class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, //Title of an App title: 'GFG APP', //Theme of an App theme: ThemeData( primarySwatch: Colors.green, ), darkTheme: ThemeData.dark(), // First Screen of App home: HomePage(), ); }}", "e": 2192, "s": 1705, "text": null }, { "code": null, "e": 3054, "s": 2192, "text": "Step 3: Now Import dependencies for Staggered Grid View in HomePage(). After Importing dependency create app bar inside the Scaffold. Now create a new Container() in the body. In that Container now implement Staggered Grid View as shown in the code below. Inside the Staggered Grid view, there is staggeredTiles. For which we have declared a List of 10 _cardTile which specify the size of your cards. After that, we have created a class BackGroundTile in StatelessWidget. In which we have declared two final variables backgroundColor and icon data. We have created a constructor for these variables. And returned Card which consists of backgroundColor and icondata. In Staggered Grid View we have declared children as _listTile. For which we have created a List which inherits properties from class BackGroundTile. Which consist of backgroundColor and icondata." }, { "code": null, "e": 3059, "s": 3054, "text": "Dart" }, { "code": "import 'package:flutter/material.dart';import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; //List of Cards with sizeList<StaggeredTile> _cardTile = <StaggeredTile> [ StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2), StaggeredTile.count(2, 3), StaggeredTile.count(2, 2),]; //List of Cards with color and iconList<Widget>_listTile = <Widget>[ BackGroundTile(backgroundColor: Colors.red, icondata: Icons.home), BackGroundTile(backgroundColor: Colors.orange, icondata: Icons.ac_unit), BackGroundTile(backgroundColor: Colors.pink, icondata: Icons.landscape), BackGroundTile(backgroundColor: Colors.green, icondata: Icons.portrait), BackGroundTile(backgroundColor: Colors.deepPurpleAccent, icondata: Icons.music_note), BackGroundTile(backgroundColor: Colors.blue, icondata: Icons.access_alarms), BackGroundTile(backgroundColor: Colors.indigo, icondata: Icons.satellite_outlined), BackGroundTile(backgroundColor: Colors.cyan, icondata: Icons.search_sharp), BackGroundTile(backgroundColor: Colors.yellowAccent, icondata: Icons.adjust_rounded), BackGroundTile(backgroundColor: Colors.deepOrange, icondata: Icons.attach_money),]; class HomePage extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(\"GFG App\"), ), body: Container( // Staggered Grid View starts here child: StaggeredGridView.count( crossAxisCount: 4, staggeredTiles: _cardTile, children: _listTile, mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, ), ), ); }}class BackGroundTile extends StatelessWidget { final Color backgroundColor; final IconData icondata; BackGroundTile({this.backgroundColor, this.icondata}); @override Widget build(BuildContext context) { return Card( color: backgroundColor, child: Icon(icondata, color: Colors.white), ); }}", "e": 5175, "s": 3059, "text": null }, { "code": null, "e": 5183, "s": 5175, "text": "Output:" }, { "code": null, "e": 5191, "s": 5183, "text": "android" }, { "code": null, "e": 5199, "s": 5191, "text": "Flutter" }, { "code": null, "e": 5221, "s": 5199, "text": "Flutter UI-components" }, { "code": null, "e": 5226, "s": 5221, "text": "Dart" }, { "code": null, "e": 5234, "s": 5226, "text": "Flutter" }, { "code": null, "e": 5332, "s": 5234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5364, "s": 5332, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 5392, "s": 5364, "text": "Listview.builder in Flutter" }, { "code": null, "e": 5431, "s": 5392, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5456, "s": 5431, "text": "Splash Screen in Flutter" }, { "code": null, "e": 5478, "s": 5456, "text": "Flutter - Asset Image" }, { "code": null, "e": 5510, "s": 5478, "text": "Flutter - DropDownButton Widget" }, { "code": null, "e": 5549, "s": 5510, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5575, "s": 5549, "text": "Flutter - Checkbox Widget" }, { "code": null, "e": 5598, "s": 5575, "text": "Flutter - Stack Widget" } ]
Implement DELETE query in MySQL stored procedure
You can use stored procedure and can pass the value via parameter. Let us first create a table − mysql> create table DemoTable1464 -> ( -> Id int, -> FirstName varchar(20) -> ); Query OK, 0 rows affected (0.51 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1464 values(101,'Chris Brown'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1464 values(102,'John Doe'); Query OK, 1 row affected (0.09 sec) Display all records from the table using select statement − mysql> select * from DemoTable1464; This will produce the following output − +------+-------------+ | Id | FirstName | +------+-------------+ | 101 | Chris Brown | | 102 | John Doe | +------+-------------+ 2 rows in set (0.00 sec) Here is the query to implement delete query in stored procedure − mysql> DELIMITER // mysql> CREATE PROCEDURE delete_demo(IN local_Id int, IN local_Name varchar(20)) -> BEGIN -> delete from DemoTable1464 -> where Id=local_Id and -> FirstName=local_Name; -> END // Query OK, 0 rows affected (0.24 sec) mysql> DELIMITER ; Now you can call the stored procedure using CALL command − mysql> call delete_demo(102,'John Doe'); Query OK, 1 row affected, 1 warning (0.11 sec) Let us check the table records once again − mysql> select * from DemoTable1464; This will produce the following output − +------+-------------+ | Id | FirstName | +------+-------------+ | 101 | Chris Brown | +------+-------------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1159, "s": 1062, "text": "You can use stored procedure and can pass the value via parameter. Let us first create a table −" }, { "code": null, "e": 1289, "s": 1159, "text": "mysql> create table DemoTable1464\n -> (\n -> Id int,\n -> FirstName varchar(20)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1345, "s": 1289, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1534, "s": 1345, "text": "mysql> insert into DemoTable1464 values(101,'Chris Brown');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable1464 values(102,'John Doe');\nQuery OK, 1 row affected (0.09 sec)" }, { "code": null, "e": 1594, "s": 1534, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1630, "s": 1594, "text": "mysql> select * from DemoTable1464;" }, { "code": null, "e": 1671, "s": 1630, "text": "This will produce the following output −" }, { "code": null, "e": 1834, "s": 1671, "text": "+------+-------------+\n| Id | FirstName |\n+------+-------------+\n| 101 | Chris Brown |\n| 102 | John Doe |\n+------+-------------+\n2 rows in set (0.00 sec)" }, { "code": null, "e": 1900, "s": 1834, "text": "Here is the query to implement delete query in stored procedure −" }, { "code": null, "e": 2180, "s": 1900, "text": "mysql> DELIMITER //\nmysql> CREATE PROCEDURE delete_demo(IN local_Id int, IN local_Name varchar(20))\n -> BEGIN\n -> delete from DemoTable1464\n -> where Id=local_Id and\n -> FirstName=local_Name;\n -> END //\nQuery OK, 0 rows affected (0.24 sec)\nmysql> DELIMITER ;" }, { "code": null, "e": 2239, "s": 2180, "text": "Now you can call the stored procedure using CALL command −" }, { "code": null, "e": 2327, "s": 2239, "text": "mysql> call delete_demo(102,'John Doe');\nQuery OK, 1 row affected, 1 warning (0.11 sec)" }, { "code": null, "e": 2371, "s": 2327, "text": "Let us check the table records once again −" }, { "code": null, "e": 2407, "s": 2371, "text": "mysql> select * from DemoTable1464;" }, { "code": null, "e": 2448, "s": 2407, "text": "This will produce the following output −" }, { "code": null, "e": 2587, "s": 2448, "text": "+------+-------------+\n| Id | FirstName |\n+------+-------------+\n| 101 | Chris Brown |\n+------+-------------+\n1 row in set (0.00 sec)" } ]
Sentiment Analysis using TextBlob | by Parthvi Shah | Towards Data Science
Sentiment Analysis can help us decipher the mood and emotions of general public and gather insightful information regarding the context. Sentiment Analysis is a process of analyzing data and classifying it based on the need of the research. These sentiments can be used for a better understanding of various events and impact caused by it. L. Bing [1] highlights that in the research literature it is possible to see many different names, e.g. “sentiment analysis, opinion mining, opinion extraction, sentiment mining, subjectivity analysis, affect analysis, emotion analysis, review mining”, however all of them have similar purposes and belong to the subject of sentiment analysis or opinion mining. By analysing these sentiments, we may find what people like, what they want and what their major concerns are. TextBlob is a python library for Natural Language Processing (NLP).TextBlob actively used Natural Language ToolKit (NLTK) to achieve its tasks. NLTK is a library which gives an easy access to a lot of lexical resources and allows users to work with categorization, classification and many other tasks. TextBlob is a simple library which supports complex analysis and operations on textual data. For lexicon-based approaches, a sentiment is defined by its semantic orientation and the intensity of each word in the sentence. This requires a pre-defined dictionary classifying negative and positive words. Generally, a text message will be represented by bag of words. After assigning individual scores to all the words, final sentiment is calculated by some pooling operation like taking an average of all the sentiments. TextBlob returns polarity and subjectivity of a sentence. Polarity lies between [-1,1], -1 defines a negative sentiment and 1 defines a positive sentiment. Negation words reverse the polarity. TextBlob has semantic labels that help with fine-grained analysis. For example — emoticons, exclamation mark, emojis, etc. Subjectivity lies between [0,1]. Subjectivity quantifies the amount of personal opinion and factual information contained in the text. The higher subjectivity means that the text contains personal opinion rather than factual information. TextBlob has one more parameter — intensity. TextBlob calculates subjectivity by looking at the ‘intensity’. Intensity determines if a word modifies the next word. For English, adverbs are used as modifiers (‘very good’). For example: We calculated polarity and subjectivity for “I do not like this example at all, it is too boring”. For this particular example, polarity = -1 and subjectivity is 1, which is fair. However, for the sentence “This was a helpful example but I would prefer another one”. It returns 0.0 for both subjectivity and polarity which is not the finest answer we’d expect. It is expected that if the library returns exactly 0.0 either if your sentence didn’t contain any words that had a polarity in the NLTK training set or because TextBlob uses a weighted average sentiment score over all the words in each sample. This easily diffuses out the effect of sentences with widely varying polarities between words in our case : ‘helpful’ and ‘but’. More often than not, for simple cases, TextBlob works just fine. Steps to apply Sentiment Analysis using TextBlob – 1. Import textblob from textblob import TextBlob 2. Define a function that calculates subjectivity, polarity and give it a score based on the threshold you want to set. Another useful article that I came across is: https://neptune.ai/blog/sentiment-analysis-python-textblob-vs-vader-vs-flair
[ { "code": null, "e": 413, "s": 172, "text": "Sentiment Analysis can help us decipher the mood and emotions of general public and gather insightful information regarding the context. Sentiment Analysis is a process of analyzing data and classifying it based on the need of the research." }, { "code": null, "e": 985, "s": 413, "text": "These sentiments can be used for a better understanding of various events and impact caused by it. L. Bing [1] highlights that in the research literature it is possible to see many different names, e.g. “sentiment analysis, opinion mining, opinion extraction, sentiment mining, subjectivity analysis, affect analysis, emotion analysis, review mining”, however all of them have similar purposes and belong to the subject of sentiment analysis or opinion mining. By analysing these sentiments, we may find what people like, what they want and what their major concerns are." }, { "code": null, "e": 1380, "s": 985, "text": "TextBlob is a python library for Natural Language Processing (NLP).TextBlob actively used Natural Language ToolKit (NLTK) to achieve its tasks. NLTK is a library which gives an easy access to a lot of lexical resources and allows users to work with categorization, classification and many other tasks. TextBlob is a simple library which supports complex analysis and operations on textual data." }, { "code": null, "e": 1806, "s": 1380, "text": "For lexicon-based approaches, a sentiment is defined by its semantic orientation and the intensity of each word in the sentence. This requires a pre-defined dictionary classifying negative and positive words. Generally, a text message will be represented by bag of words. After assigning individual scores to all the words, final sentiment is calculated by some pooling operation like taking an average of all the sentiments." }, { "code": null, "e": 2582, "s": 1806, "text": "TextBlob returns polarity and subjectivity of a sentence. Polarity lies between [-1,1], -1 defines a negative sentiment and 1 defines a positive sentiment. Negation words reverse the polarity. TextBlob has semantic labels that help with fine-grained analysis. For example — emoticons, exclamation mark, emojis, etc. Subjectivity lies between [0,1]. Subjectivity quantifies the amount of personal opinion and factual information contained in the text. The higher subjectivity means that the text contains personal opinion rather than factual information. TextBlob has one more parameter — intensity. TextBlob calculates subjectivity by looking at the ‘intensity’. Intensity determines if a word modifies the next word. For English, adverbs are used as modifiers (‘very good’)." }, { "code": null, "e": 2775, "s": 2582, "text": "For example: We calculated polarity and subjectivity for “I do not like this example at all, it is too boring”. For this particular example, polarity = -1 and subjectivity is 1, which is fair." }, { "code": null, "e": 2956, "s": 2775, "text": "However, for the sentence “This was a helpful example but I would prefer another one”. It returns 0.0 for both subjectivity and polarity which is not the finest answer we’d expect." }, { "code": null, "e": 3329, "s": 2956, "text": "It is expected that if the library returns exactly 0.0 either if your sentence didn’t contain any words that had a polarity in the NLTK training set or because TextBlob uses a weighted average sentiment score over all the words in each sample. This easily diffuses out the effect of sentences with widely varying polarities between words in our case : ‘helpful’ and ‘but’." }, { "code": null, "e": 3394, "s": 3329, "text": "More often than not, for simple cases, TextBlob works just fine." }, { "code": null, "e": 3445, "s": 3394, "text": "Steps to apply Sentiment Analysis using TextBlob –" }, { "code": null, "e": 3464, "s": 3445, "text": "1. Import textblob" }, { "code": null, "e": 3494, "s": 3464, "text": "from textblob import TextBlob" }, { "code": null, "e": 3614, "s": 3494, "text": "2. Define a function that calculates subjectivity, polarity and give it a score based on the threshold you want to set." } ]
Apache HttpClient - Response Handlers
Processing the HTTP responses using the response handlers is recommended. In this chapter, we are going to discuss how to create response handlers and how to use them to process a response. If you use the response handler, all the HTTP connections will be released automatically. The HttpClient API provides an interface known as ResponseHandler in the package org.apache.http.client. In order to create a response handler, implement this interface and override its handleResponse() method. Every response has a status code and if the status code is in between 200 and 300, that means the action was successfully received, understood, and accepted. Therefore, in our example, we will handle the entities of the responses with such status codes. Follow the steps given below to execute the request using a response handler. The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); Instantiate the response handler object created above using the following line of code − ResponseHandler<String> responseHandler = new MyResponseHandler(); The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI. Create an HttpGet request by instantiating the HttpGet class and by passing a string representing the URI as a parameter to its constructor. ResponseHandler<String> responseHandler = new MyResponseHandler(); The CloseableHttpClient class has a variant of execute() method which accepts two objects ResponseHandler and HttpUriRequest, and returns a response object. String httpResponse = httpclient.execute(httpget, responseHandler); Following example demonstrates the usage of response handlers. import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; class MyResponseHandler implements ResponseHandler<String>{ public String handleResponse(final HttpResponse response) throws IOException{ //Get the status of the response int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); if(entity == null) { return ""; } else { return EntityUtils.toString(entity); } } else { return ""+status; } } } public class ResponseHandlerExample { public static void main(String args[]) throws Exception{ //Create an HttpClient object CloseableHttpClient httpclient = HttpClients.createDefault(); //instantiate the response handler ResponseHandler<String> responseHandler = new MyResponseHandler(); //Create an HttpGet object HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/"); //Execute the Get request by passing the response handler object and HttpGet object String httpresponse = httpclient.execute(httpget, responseHandler); System.out.println(httpresponse); } } The above programs generate the following output − <!DOCTYPE html> <!--[if IE 8]><html class = "ie ie8"> <![endif]--> <!--[if IE 9]><html class = "ie ie9"> <![endif]--> <!--[if gt IE 9]><!--> <html lang = "en-US"> <!--<![endif]--> <head> <!-- Basic --> <meta charset = "utf-8"> <meta http-equiv = "X-UA-Compatible" content = "IE = edge"> <meta name = "viewport" content = "width = device-width,initial-scale = 1.0,userscalable = yes"> <link href = "https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel = "stylesheet" type = "text/css" /> <link rel = "stylesheet" href = "/questions/css/home.css?v = 3" /> <script src = "/questions/js/jquery.min.js"></script> <script src = "/questions/js/fontawesome.js"></script> <script src = "https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"></script> </head> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . <script> window.dataLayer = window.dataLayer || []; function gtag() {dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-232293-17'); </script> </body> 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 2017, "s": 1827, "text": "Processing the HTTP responses using the response handlers is recommended. In this chapter, we are going to discuss how to create response handlers and how to use them to process a response." }, { "code": null, "e": 2108, "s": 2017, "text": "If you use the response handler, all the HTTP connections will be released automatically.\n" }, { "code": null, "e": 2319, "s": 2108, "text": "The HttpClient API provides an interface known as ResponseHandler in the package org.apache.http.client. In order to create a response handler, implement this interface\nand override its handleResponse() method." }, { "code": null, "e": 2573, "s": 2319, "text": "Every response has a status code and if the status code is in between 200 and 300, that means the action was successfully received, understood, and accepted. Therefore, in our example, we will handle the entities of the responses with such status codes." }, { "code": null, "e": 2651, "s": 2573, "text": "Follow the steps given below to execute the request using a response handler." }, { "code": null, "e": 2863, "s": 2651, "text": "The createDefault() method of the HttpClients class returns an object of the class CloseableHttpClient, which is the base implementation of the HttpClient interface. Using this method create an HttpClient object" }, { "code": null, "e": 2926, "s": 2863, "text": "CloseableHttpClient httpclient = HttpClients.createDefault();\n" }, { "code": null, "e": 3015, "s": 2926, "text": "Instantiate the response handler object created above using the following line of code −" }, { "code": null, "e": 3084, "s": 3015, "text": "ResponseHandler<String> responseHandler = new MyResponseHandler(); \n" }, { "code": null, "e": 3199, "s": 3084, "text": "The HttpGet class represents the HTTP GET request which retrieves the information of the given server using a URI." }, { "code": null, "e": 3340, "s": 3199, "text": "Create an HttpGet request by instantiating the HttpGet class and by passing a string representing the URI as a parameter to its constructor." }, { "code": null, "e": 3409, "s": 3340, "text": "ResponseHandler<String> responseHandler = new MyResponseHandler(); \n" }, { "code": null, "e": 3566, "s": 3409, "text": "The CloseableHttpClient class has a variant of execute() method which accepts two objects ResponseHandler and HttpUriRequest, and returns a response object." }, { "code": null, "e": 3635, "s": 3566, "text": "String httpResponse = httpclient.execute(httpget, responseHandler);\n" }, { "code": null, "e": 3698, "s": 3635, "text": "Following example demonstrates the usage of response handlers." }, { "code": null, "e": 5207, "s": 3698, "text": "import java.io.IOException;\nimport org.apache.http.HttpEntity;\nimport org.apache.http.HttpResponse;\nimport org.apache.http.client.ResponseHandler;\nimport org.apache.http.client.methods.HttpGet;\nimport org.apache.http.impl.client.CloseableHttpClient;\nimport org.apache.http.impl.client.HttpClients;\nimport org.apache.http.util.EntityUtils;\n\nclass MyResponseHandler implements ResponseHandler<String>{\n \n public String handleResponse(final HttpResponse response) throws IOException{\n\n //Get the status of the response\n int status = response.getStatusLine().getStatusCode();\n if (status >= 200 && status < 300) {\n HttpEntity entity = response.getEntity();\n if(entity == null) {\n return \"\";\n } else {\n return EntityUtils.toString(entity);\n }\n\n } else {\n return \"\"+status;\n }\n }\n}\n\npublic class ResponseHandlerExample {\n \n public static void main(String args[]) throws Exception{\n \n //Create an HttpClient object\n CloseableHttpClient httpclient = HttpClients.createDefault();\n\n //instantiate the response handler\n ResponseHandler<String> responseHandler = new MyResponseHandler();\n\n //Create an HttpGet object\n HttpGet httpget = new HttpGet(\"http://www.tutorialspoint.com/\");\n\n //Execute the Get request by passing the response handler object and HttpGet object\n String httpresponse = httpclient.execute(httpget, responseHandler);\n\n System.out.println(httpresponse);\n }\n}" }, { "code": null, "e": 5258, "s": 5207, "text": "The above programs generate the following output −" }, { "code": null, "e": 6383, "s": 5258, "text": "<!DOCTYPE html>\n<!--[if IE 8]><html class = \"ie ie8\"> <![endif]-->\n<!--[if IE 9]><html class = \"ie ie9\"> <![endif]-->\n<!--[if gt IE 9]><!-->\n<html lang = \"en-US\"> <!--<![endif]-->\n<head>\n<!-- Basic -->\n<meta charset = \"utf-8\">\n<meta http-equiv = \"X-UA-Compatible\" content = \"IE = edge\">\n<meta name = \"viewport\" content = \"width = device-width,initial-scale = 1.0,userscalable = yes\">\n<link href = \"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\"\nrel = \"stylesheet\" type = \"text/css\" />\n<link rel = \"stylesheet\" href = \"/questions/css/home.css?v = 3\" />\n<script src = \"/questions/js/jquery.min.js\"></script>\n<script src = \"/questions/js/fontawesome.js\"></script>\n<script src = \"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"></script>\n</head>\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n. . . . . . . . . . . . . . . . . . . . . . . . .\n<script>\nwindow.dataLayer = window.dataLayer || [];\nfunction gtag() {dataLayer.push(arguments);}\ngtag('js', new Date());\ngtag('config', 'UA-232293-17');\n</script>\n</body>\n" }, { "code": null, "e": 6418, "s": 6383, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6437, "s": 6418, "text": " Arnab Chakraborty" }, { "code": null, "e": 6472, "s": 6437, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6493, "s": 6472, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 6526, "s": 6493, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 6539, "s": 6526, "text": " Nilay Mehta" }, { "code": null, "e": 6574, "s": 6539, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6592, "s": 6574, "text": " Bigdata Engineer" }, { "code": null, "e": 6625, "s": 6592, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6643, "s": 6625, "text": " Bigdata Engineer" }, { "code": null, "e": 6676, "s": 6643, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 6694, "s": 6676, "text": " Bigdata Engineer" }, { "code": null, "e": 6701, "s": 6694, "text": " Print" }, { "code": null, "e": 6712, "s": 6701, "text": " Add Notes" } ]
How to Setup View Engine in Node.js ? - GeeksforGeeks
27 Apr, 2020 View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with plain javascript. Installation of ejs module: You can visit the link Install ejs module. You can install this package by using the following command.npm install ejsAfter installing multer you can check your ejs version in command prompt using the command.npm version ejsAfter that, you can just create a folder and add a file for example app.js, To run this file you need to run the following command.node app.jsTo setup view engine, you need the write this middleware in your index.js as follow:app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'ejs')where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.Now create a EJS file like Demo.ejs and put this file in views folder. You can visit the link Install ejs module. You can install this package by using the following command.npm install ejs npm install ejs After installing multer you can check your ejs version in command prompt using the command.npm version ejs npm version ejs After that, you can just create a folder and add a file for example app.js, To run this file you need to run the following command.node app.js node app.js To setup view engine, you need the write this middleware in your index.js as follow:app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'ejs')where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept. app.set('views', path.join(__dirname, 'views')) app.set('view engine', 'ejs') where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept. Now create a EJS file like Demo.ejs and put this file in views folder. Filename: Demo.ejs <!DOCTYPE html><html><head> <title>View Engine Demo</title></head><body> <!- For printing variable these tags are used: <%= %> --> <h1> <%= title %> </h1> <!- For business logic these tags are used: <% %> --> <% if(true){ %> <h4>Greetings from geeksforgeeks</h4> <% } %></body></html> Filename: app.js const express = require('express')const path = require('path')const app = express() // View Engine Setupapp.set('views', path.join(__dirname, 'views'))app.set('view engine', 'ejs') app.get('/', function(req, res){ // Rendering our web page i.e. Demo.ejs // and passing title variable through it res.render('Demo', { title: 'View Engine Demo' })}) app.listen(8080, function(error){ if(error) throw error console.log("Server created Successfully")}) Steps to run the program: The project structure will look like this:Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejs npm install expressRun app.js file using below command:node app.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Demo.ejs page as shown below: The project structure will look like this: Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejs npm install express npm install ejs npm install express Run app.js file using below command:node app.js node app.js Open browser and type this URL:http://localhost:8080/ http://localhost:8080/ Then you will see the Demo.ejs page as shown below: So this is how you can setup a view engine in node js. There are many other engines exist like Handlebars, Mustache, etc. Node.js-Misc Node.js Web Technologies Web technologies Questions Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Top 10 Front End Developer Skills That You Need in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 24133, "s": 24105, "text": "\n27 Apr, 2020" }, { "code": null, "e": 24452, "s": 24133, "text": "View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with plain javascript." }, { "code": null, "e": 24480, "s": 24452, "text": "Installation of ejs module:" }, { "code": null, "e": 25214, "s": 24480, "text": "You can visit the link Install ejs module. You can install this package by using the following command.npm install ejsAfter installing multer you can check your ejs version in command prompt using the command.npm version ejsAfter that, you can just create a folder and add a file for example app.js, To run this file you need to run the following command.node app.jsTo setup view engine, you need the write this middleware in your index.js as follow:app.set('views', path.join(__dirname, 'views'))\napp.set('view engine', 'ejs')where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept.Now create a EJS file like Demo.ejs and put this file in views folder." }, { "code": null, "e": 25333, "s": 25214, "text": "You can visit the link Install ejs module. You can install this package by using the following command.npm install ejs" }, { "code": null, "e": 25349, "s": 25333, "text": "npm install ejs" }, { "code": null, "e": 25456, "s": 25349, "text": "After installing multer you can check your ejs version in command prompt using the command.npm version ejs" }, { "code": null, "e": 25472, "s": 25456, "text": "npm version ejs" }, { "code": null, "e": 25615, "s": 25472, "text": "After that, you can just create a folder and add a file for example app.js, To run this file you need to run the following command.node app.js" }, { "code": null, "e": 25627, "s": 25615, "text": "node app.js" }, { "code": null, "e": 25925, "s": 25627, "text": "To setup view engine, you need the write this middleware in your index.js as follow:app.set('views', path.join(__dirname, 'views'))\napp.set('view engine', 'ejs')where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept." }, { "code": null, "e": 26003, "s": 25925, "text": "app.set('views', path.join(__dirname, 'views'))\napp.set('view engine', 'ejs')" }, { "code": null, "e": 26140, "s": 26003, "text": "where path is the global object and __dirname holds current directory address. Views is the folder where our all web pages will be kept." }, { "code": null, "e": 26211, "s": 26140, "text": "Now create a EJS file like Demo.ejs and put this file in views folder." }, { "code": null, "e": 26230, "s": 26211, "text": "Filename: Demo.ejs" }, { "code": "<!DOCTYPE html><html><head> <title>View Engine Demo</title></head><body> <!- For printing variable these tags are used: <%= %> --> <h1> <%= title %> </h1> <!- For business logic these tags are used: <% %> --> <% if(true){ %> <h4>Greetings from geeksforgeeks</h4> <% } %></body></html>", "e": 26547, "s": 26230, "text": null }, { "code": null, "e": 26564, "s": 26547, "text": "Filename: app.js" }, { "code": "const express = require('express')const path = require('path')const app = express() // View Engine Setupapp.set('views', path.join(__dirname, 'views'))app.set('view engine', 'ejs') app.get('/', function(req, res){ // Rendering our web page i.e. Demo.ejs // and passing title variable through it res.render('Demo', { title: 'View Engine Demo' })}) app.listen(8080, function(error){ if(error) throw error console.log(\"Server created Successfully\")})", "e": 27042, "s": 26564, "text": null }, { "code": null, "e": 27068, "s": 27042, "text": "Steps to run the program:" }, { "code": null, "e": 27407, "s": 27068, "text": "The project structure will look like this:Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejs\nnpm install expressRun app.js file using below command:node app.jsOpen browser and type this URL:http://localhost:8080/Then you will see the Demo.ejs page as shown below:" }, { "code": null, "e": 27450, "s": 27407, "text": "The project structure will look like this:" }, { "code": null, "e": 27596, "s": 27450, "text": "Make sure you have ‘view engine’ like I have used “ejs” and also install express using the following commands:npm install ejs\nnpm install express" }, { "code": null, "e": 27632, "s": 27596, "text": "npm install ejs\nnpm install express" }, { "code": null, "e": 27680, "s": 27632, "text": "Run app.js file using below command:node app.js" }, { "code": null, "e": 27692, "s": 27680, "text": "node app.js" }, { "code": null, "e": 27746, "s": 27692, "text": "Open browser and type this URL:http://localhost:8080/" }, { "code": null, "e": 27769, "s": 27746, "text": "http://localhost:8080/" }, { "code": null, "e": 27821, "s": 27769, "text": "Then you will see the Demo.ejs page as shown below:" }, { "code": null, "e": 27943, "s": 27821, "text": "So this is how you can setup a view engine in node js. There are many other engines exist like Handlebars, Mustache, etc." }, { "code": null, "e": 27956, "s": 27943, "text": "Node.js-Misc" }, { "code": null, "e": 27964, "s": 27956, "text": "Node.js" }, { "code": null, "e": 27981, "s": 27964, "text": "Web Technologies" }, { "code": null, "e": 28008, "s": 27981, "text": "Web technologies Questions" }, { "code": null, "e": 28024, "s": 28008, "text": "Write From Home" }, { "code": null, "e": 28122, "s": 28024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28131, "s": 28122, "text": "Comments" }, { "code": null, "e": 28144, "s": 28131, "text": "Old Comments" }, { "code": null, "e": 28173, "s": 28144, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 28203, "s": 28173, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 28260, "s": 28203, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28314, "s": 28260, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28351, "s": 28314, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28407, "s": 28351, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28469, "s": 28407, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28512, "s": 28469, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28562, "s": 28512, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
VB.Net - MenuStrip Control
The MenuStrip control represents the container for the menu structure. The MenuStrip control works as the top-level container for the menu structure. The ToolStripMenuItem class and the ToolStripDropDownMenu class provide the functionalities to create menu items, sub menus and drop-down menus. The following diagram shows adding a MenuStrip control on the form − The following are some of the commonly used properties of the MenuStrip control − CanOverflow Gets or sets a value indicating whether the MenuStrip supports overflow functionality. GripStyle Gets or sets the visibility of the grip used to reposition the control. MdiWindowListItem Gets or sets the ToolStripMenuItem that is used to display a list of Multiple-document interface (MDI) child forms. ShowItemToolTips Gets or sets a value indicating whether ToolTips are shown for the MenuStrip. Stretch Gets or sets a value indicating whether the MenuStrip stretches from end to end in its container. The following are some of the commonly used events of the MenuStrip control − MenuActivate Occurs when the user accesses the menu with the keyboard or mouse. MenuDeactivate Occurs when the MenuStrip is deactivated. In this example, let us add menu and sub-menu items. Take the following steps − Drag and drop or double click on a MenuStrip control, to add it to the form. Drag and drop or double click on a MenuStrip control, to add it to the form. Click the Type Here text to open a text box and enter the names of the menu items or sub-menu items you want. When you add a sub-menu, another text box with 'Type Here' text opens below it. Click the Type Here text to open a text box and enter the names of the menu items or sub-menu items you want. When you add a sub-menu, another text box with 'Type Here' text opens below it. Complete the menu structure shown in the diagram above. Complete the menu structure shown in the diagram above. Add a sub menu Exit under the File menu. Add a sub menu Exit under the File menu. Double-Click the Exit menu created and add the following code to the Click event of ExitToolStripMenuItem − Double-Click the Exit menu created and add the following code to the Click event of ExitToolStripMenuItem − Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) _ Handles ExitToolStripMenuItem.Click End End Sub When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window: Click on the File -> Exit to exit from 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": 2371, "s": 2300, "text": "The MenuStrip control represents the container for the menu structure." }, { "code": null, "e": 2595, "s": 2371, "text": "The MenuStrip control works as the top-level container for the menu structure. The ToolStripMenuItem class and the ToolStripDropDownMenu class provide the functionalities to create menu items, sub menus and drop-down menus." }, { "code": null, "e": 2664, "s": 2595, "text": "The following diagram shows adding a MenuStrip control on the form −" }, { "code": null, "e": 2746, "s": 2664, "text": "The following are some of the commonly used properties of the MenuStrip control −" }, { "code": null, "e": 2758, "s": 2746, "text": "CanOverflow" }, { "code": null, "e": 2845, "s": 2758, "text": "Gets or sets a value indicating whether the MenuStrip supports overflow functionality." }, { "code": null, "e": 2855, "s": 2845, "text": "GripStyle" }, { "code": null, "e": 2927, "s": 2855, "text": "Gets or sets the visibility of the grip used to reposition the control." }, { "code": null, "e": 2945, "s": 2927, "text": "MdiWindowListItem" }, { "code": null, "e": 3061, "s": 2945, "text": "Gets or sets the ToolStripMenuItem that is used to display a list of Multiple-document interface (MDI) child forms." }, { "code": null, "e": 3078, "s": 3061, "text": "ShowItemToolTips" }, { "code": null, "e": 3156, "s": 3078, "text": "Gets or sets a value indicating whether ToolTips are shown for the MenuStrip." }, { "code": null, "e": 3164, "s": 3156, "text": "Stretch" }, { "code": null, "e": 3262, "s": 3164, "text": "Gets or sets a value indicating whether the MenuStrip stretches from end to end in its container." }, { "code": null, "e": 3340, "s": 3262, "text": "The following are some of the commonly used events of the MenuStrip control −" }, { "code": null, "e": 3353, "s": 3340, "text": "MenuActivate" }, { "code": null, "e": 3420, "s": 3353, "text": "Occurs when the user accesses the menu with the keyboard or mouse." }, { "code": null, "e": 3435, "s": 3420, "text": "MenuDeactivate" }, { "code": null, "e": 3477, "s": 3435, "text": "Occurs when the MenuStrip is deactivated." }, { "code": null, "e": 3530, "s": 3477, "text": "In this example, let us add menu and sub-menu items." }, { "code": null, "e": 3557, "s": 3530, "text": "Take the following steps −" }, { "code": null, "e": 3634, "s": 3557, "text": "Drag and drop or double click on a MenuStrip control, to add it to the form." }, { "code": null, "e": 3711, "s": 3634, "text": "Drag and drop or double click on a MenuStrip control, to add it to the form." }, { "code": null, "e": 3901, "s": 3711, "text": "Click the Type Here text to open a text box and enter the names of the menu items or sub-menu items you want. When you add a sub-menu, another text box with 'Type Here' text opens below it." }, { "code": null, "e": 4091, "s": 3901, "text": "Click the Type Here text to open a text box and enter the names of the menu items or sub-menu items you want. When you add a sub-menu, another text box with 'Type Here' text opens below it." }, { "code": null, "e": 4147, "s": 4091, "text": "Complete the menu structure shown in the diagram above." }, { "code": null, "e": 4203, "s": 4147, "text": "Complete the menu structure shown in the diagram above." }, { "code": null, "e": 4244, "s": 4203, "text": "Add a sub menu Exit under the File menu." }, { "code": null, "e": 4285, "s": 4244, "text": "Add a sub menu Exit under the File menu." }, { "code": null, "e": 4394, "s": 4285, "text": "\nDouble-Click the Exit menu created and add the following code to the Click event of ExitToolStripMenuItem −" }, { "code": null, "e": 4502, "s": 4394, "text": "Double-Click the Exit menu created and add the following code to the Click event of ExitToolStripMenuItem −" }, { "code": null, "e": 4632, "s": 4502, "text": "Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) _\n Handles ExitToolStripMenuItem.Click\n End\nEnd Sub" }, { "code": null, "e": 4777, "s": 4632, "text": "When the above code is executed and run using Start button available at the Microsoft Visual Studio tool bar, it will show the following window:" }, { "code": null, "e": 4834, "s": 4777, "text": "Click on the File -> Exit to exit from the application −" }, { "code": null, "e": 4867, "s": 4834, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 4884, "s": 4867, "text": " Frahaan Hussain" }, { "code": null, "e": 4919, "s": 4884, "text": "\n 103 Lectures \n 12 hours \n" }, { "code": null, "e": 4934, "s": 4919, "text": " Arnold Higuit" }, { "code": null, "e": 4969, "s": 4934, "text": "\n 60 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4984, "s": 4969, "text": " Arnold Higuit" }, { "code": null, "e": 5017, "s": 4984, "text": "\n 97 Lectures \n 9 hours \n" }, { "code": null, "e": 5032, "s": 5017, "text": " Arnold Higuit" }, { "code": null, "e": 5039, "s": 5032, "text": " Print" }, { "code": null, "e": 5050, "s": 5039, "text": " Add Notes" } ]
C# BitConverter.ToSingle() Method
The BitConverter.ToSingle() method in C# is used to return a single-precision floating point number converted from four bytes at a specified position in a byte array. The syntax is as follows − public static float ToSingle (byte[] value, int begnIndex); Above, val is the byte array, whereas begnIndex is the beginning position within val. Let us now see an example − Live Demo using System; public class Demo { public static void Main() { byte[] arr = {0, 1, 2, 3, 5, 7, 10}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 0; i < arr.Length - 4; i = i + 4) { float res = BitConverter.ToSingle(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+res); } } } This will produce the following output − Byte Array = 00-01-02-03-05-07-0A Value = 0 Result = 3.820471E-37 Let us now see another example − Live Demo using System; public class Demo { public static void Main() { byte[] arr = {0, 10, 2, 5, 32, 45, 0, 0, 9, 20, 30, 50, 76, 88}; Console.WriteLine("Byte Array = {0} ", BitConverter.ToString(arr)); for (int i = 0; i < arr.Length - 4; i = i + 4) { float res = BitConverter.ToSingle(arr, i); Console.WriteLine("\nValue = "+arr[i]); Console.WriteLine("Result = "+res); } } } This will produce the following output − Byte Array = 00-0A-02-05-20-2D-00-00-09-14-1E-32-4C-58 Value = 0 Result = 6.114407E-36 Value = 32 Result = 1.61878E-41 Value = 9 Result = 9.201366E-09
[ { "code": null, "e": 1229, "s": 1062, "text": "The BitConverter.ToSingle() method in C# is used to return a single-precision floating point number converted from four bytes at a specified position in a byte array." }, { "code": null, "e": 1256, "s": 1229, "text": "The syntax is as follows −" }, { "code": null, "e": 1316, "s": 1256, "text": "public static float ToSingle (byte[] value, int begnIndex);" }, { "code": null, "e": 1402, "s": 1316, "text": "Above, val is the byte array, whereas begnIndex is the beginning position within val." }, { "code": null, "e": 1430, "s": 1402, "text": "Let us now see an example −" }, { "code": null, "e": 1441, "s": 1430, "text": " Live Demo" }, { "code": null, "e": 1845, "s": 1441, "text": "using System;\npublic class Demo {\n public static void Main() {\n byte[] arr = {0, 1, 2, 3, 5, 7, 10};\n Console.WriteLine(\"Byte Array = {0} \",\n BitConverter.ToString(arr));\n for (int i = 0; i < arr.Length - 4; i = i + 4) {\n float res = BitConverter.ToSingle(arr, i);\n Console.WriteLine(\"\\nValue = \"+arr[i]);\n Console.WriteLine(\"Result = \"+res);\n }\n }\n}" }, { "code": null, "e": 1886, "s": 1845, "text": "This will produce the following output −" }, { "code": null, "e": 1952, "s": 1886, "text": "Byte Array = 00-01-02-03-05-07-0A\nValue = 0\nResult = 3.820471E-37" }, { "code": null, "e": 1985, "s": 1952, "text": "Let us now see another example −" }, { "code": null, "e": 1996, "s": 1985, "text": " Live Demo" }, { "code": null, "e": 2422, "s": 1996, "text": "using System;\npublic class Demo {\n public static void Main() {\n byte[] arr = {0, 10, 2, 5, 32, 45, 0, 0, 9, 20, 30, 50, 76, 88};\n Console.WriteLine(\"Byte Array = {0} \", BitConverter.ToString(arr));\n for (int i = 0; i < arr.Length - 4; i = i + 4) {\n float res = BitConverter.ToSingle(arr, i);\n Console.WriteLine(\"\\nValue = \"+arr[i]);\n Console.WriteLine(\"Result = \"+res);\n }\n }\n}" }, { "code": null, "e": 2463, "s": 2422, "text": "This will produce the following output −" }, { "code": null, "e": 2614, "s": 2463, "text": "Byte Array = 00-0A-02-05-20-2D-00-00-09-14-1E-32-4C-58\nValue = 0\nResult = 6.114407E-36\nValue = 32\nResult = 1.61878E-41\nValue = 9\nResult = 9.201366E-09" } ]
Teradata - MultiLoad
MultiLoad can load multiple tables at a time and it can also perform different types of tasks such as INSERT, DELETE, UPDATE and UPSERT. It can load up to 5 tables at a time and perform up to 20 DML operations in a script. The target table is not required for MultiLoad. MultiLoad supports two modes − IMPORT DELETE MultiLoad requires a work table, a log table and two error tables in addition to the target table. Log Table − Used to maintain the checkpoints taken during load which will be used for restart. Log Table − Used to maintain the checkpoints taken during load which will be used for restart. Error Tables − These tables are inserted during load when an error occurs. First error table stores conversion errors whereas second error table stores duplicate records. Error Tables − These tables are inserted during load when an error occurs. First error table stores conversion errors whereas second error table stores duplicate records. Log Table − Maintains the results from each phase of MultiLoad for restart purpose. Log Table − Maintains the results from each phase of MultiLoad for restart purpose. Work table − MultiLoad script creates one work table per target table. Work table is used to keep DML tasks and the input data. Work table − MultiLoad script creates one work table per target table. Work table is used to keep DML tasks and the input data. MultiLoad has some limitations. Unique Secondary Index not supported on target table. Referential integrity not supported. Triggers not supported. MultiLoad import has five phases − Phase 1 − Preliminary Phase – Performs basic setup activities. Phase 1 − Preliminary Phase – Performs basic setup activities. Phase 2 − DML Transaction Phase – Verifies the syntax of DML statements and brings them to Teradata system. Phase 2 − DML Transaction Phase – Verifies the syntax of DML statements and brings them to Teradata system. Phase 3 − Acquisition Phase – Brings the input data into work tables and locks the table. Phase 3 − Acquisition Phase – Brings the input data into work tables and locks the table. Phase 4 − Application Phase – Applies all DML operations. Phase 4 − Application Phase – Applies all DML operations. Phase 5 − Cleanup Phase – Releases the table lock. Phase 5 − Cleanup Phase – Releases the table lock. The steps involved in a MultiLoad script are − Step 1 − Set up the log table. Step 1 − Set up the log table. Step 2 − Log on to Teradata. Step 2 − Log on to Teradata. Step 3 − Specify the Target, Work and Error tables. Step 3 − Specify the Target, Work and Error tables. Step 4 − Define INPUT file layout. Step 4 − Define INPUT file layout. Step 5 − Define the DML queries. Step 5 − Define the DML queries. Step 6 − Name the IMPORT file. Step 6 − Name the IMPORT file. Step 7 − Specify the LAYOUT to be used. Step 7 − Specify the LAYOUT to be used. Step 8 − Initiate the Load. Step 8 − Initiate the Load. Step 9 − Finish the load and terminate the sessions. Step 9 − Finish the load and terminate the sessions. Create a text file with the following records and name the file as employee.txt. 101,Mike,James,1980-01-05,2010-03-01,1 102,Robert,Williams,1983-03-05,2010-09-01,1 103,Peter,Paul,1983-04-01,2009-02-12,2 104,Alex,Stuart,1984-11-06,2014-01-01,2 105,Robert,James,1984-12-01,2015-03-09,3 The following example is a MultiLoad script that reads records from employee table and loads into Employee_Stg table. .LOGTABLE tduser.Employee_log; .LOGON 192.168.1.102/dbc,dbc; .BEGIN MLOAD TABLES Employee_Stg; .LAYOUT Employee; .FIELD in_EmployeeNo * VARCHAR(10); .FIELD in_FirstName * VARCHAR(30); .FIELD in_LastName * VARCHAR(30); .FIELD in_BirthDate * VARCHAR(10); .FIELD in_JoinedDate * VARCHAR(10); .FIELD in_DepartmentNo * VARCHAR(02); .DML LABEL EmpLabel; INSERT INTO Employee_Stg ( EmployeeNo, FirstName, LastName, BirthDate, JoinedDate, DepartmentNo ) VALUES ( :in_EmployeeNo, :in_FirstName, :in_Lastname, :in_BirthDate, :in_JoinedDate, :in_DepartmentNo ); .IMPORT INFILE employee.txt FORMAT VARTEXT ',' LAYOUT Employee APPLY EmpLabel; .END MLOAD; LOGOFF; Once the input file employee.txt is created and the multiload script is named as EmployeeLoad.ml, then you can run the Multiload script using the following command in UNIX and Windows. Multiload < EmployeeLoad.ml; Print Add Notes Bookmark this page
[ { "code": null, "e": 2901, "s": 2630, "text": "MultiLoad can load multiple tables at a time and it can also perform different types of tasks such as INSERT, DELETE, UPDATE and UPSERT. It can load up to 5 tables at a time and perform up to 20 DML operations in a script. The target table is not required for MultiLoad." }, { "code": null, "e": 2932, "s": 2901, "text": "MultiLoad supports two modes −" }, { "code": null, "e": 2939, "s": 2932, "text": "IMPORT" }, { "code": null, "e": 2946, "s": 2939, "text": "DELETE" }, { "code": null, "e": 3045, "s": 2946, "text": "MultiLoad requires a work table, a log table and two error tables in addition to the target table." }, { "code": null, "e": 3140, "s": 3045, "text": "Log Table − Used to maintain the checkpoints taken during load which will be used for restart." }, { "code": null, "e": 3235, "s": 3140, "text": "Log Table − Used to maintain the checkpoints taken during load which will be used for restart." }, { "code": null, "e": 3406, "s": 3235, "text": "Error Tables − These tables are inserted during load when an error occurs. First error table stores conversion errors whereas second error table stores duplicate records." }, { "code": null, "e": 3577, "s": 3406, "text": "Error Tables − These tables are inserted during load when an error occurs. First error table stores conversion errors whereas second error table stores duplicate records." }, { "code": null, "e": 3661, "s": 3577, "text": "Log Table − Maintains the results from each phase of MultiLoad for restart purpose." }, { "code": null, "e": 3745, "s": 3661, "text": "Log Table − Maintains the results from each phase of MultiLoad for restart purpose." }, { "code": null, "e": 3873, "s": 3745, "text": "Work table − MultiLoad script creates one work table per target table. Work table is used to keep DML tasks and the input data." }, { "code": null, "e": 4001, "s": 3873, "text": "Work table − MultiLoad script creates one work table per target table. Work table is used to keep DML tasks and the input data." }, { "code": null, "e": 4033, "s": 4001, "text": "MultiLoad has some limitations." }, { "code": null, "e": 4087, "s": 4033, "text": "Unique Secondary Index not supported on target table." }, { "code": null, "e": 4124, "s": 4087, "text": "Referential integrity not supported." }, { "code": null, "e": 4148, "s": 4124, "text": "Triggers not supported." }, { "code": null, "e": 4183, "s": 4148, "text": "MultiLoad import has five phases −" }, { "code": null, "e": 4246, "s": 4183, "text": "Phase 1 − Preliminary Phase – Performs basic setup activities." }, { "code": null, "e": 4309, "s": 4246, "text": "Phase 1 − Preliminary Phase – Performs basic setup activities." }, { "code": null, "e": 4417, "s": 4309, "text": "Phase 2 − DML Transaction Phase – Verifies the syntax of DML statements and brings them to Teradata system." }, { "code": null, "e": 4525, "s": 4417, "text": "Phase 2 − DML Transaction Phase – Verifies the syntax of DML statements and brings them to Teradata system." }, { "code": null, "e": 4615, "s": 4525, "text": "Phase 3 − Acquisition Phase – Brings the input data into work tables and locks the table." }, { "code": null, "e": 4705, "s": 4615, "text": "Phase 3 − Acquisition Phase – Brings the input data into work tables and locks the table." }, { "code": null, "e": 4763, "s": 4705, "text": "Phase 4 − Application Phase – Applies all DML operations." }, { "code": null, "e": 4821, "s": 4763, "text": "Phase 4 − Application Phase – Applies all DML operations." }, { "code": null, "e": 4872, "s": 4821, "text": "Phase 5 − Cleanup Phase – Releases the table lock." }, { "code": null, "e": 4923, "s": 4872, "text": "Phase 5 − Cleanup Phase – Releases the table lock." }, { "code": null, "e": 4970, "s": 4923, "text": "The steps involved in a MultiLoad script are −" }, { "code": null, "e": 5001, "s": 4970, "text": "Step 1 − Set up the log table." }, { "code": null, "e": 5032, "s": 5001, "text": "Step 1 − Set up the log table." }, { "code": null, "e": 5061, "s": 5032, "text": "Step 2 − Log on to Teradata." }, { "code": null, "e": 5090, "s": 5061, "text": "Step 2 − Log on to Teradata." }, { "code": null, "e": 5142, "s": 5090, "text": "Step 3 − Specify the Target, Work and Error tables." }, { "code": null, "e": 5194, "s": 5142, "text": "Step 3 − Specify the Target, Work and Error tables." }, { "code": null, "e": 5229, "s": 5194, "text": "Step 4 − Define INPUT file layout." }, { "code": null, "e": 5264, "s": 5229, "text": "Step 4 − Define INPUT file layout." }, { "code": null, "e": 5297, "s": 5264, "text": "Step 5 − Define the DML queries." }, { "code": null, "e": 5330, "s": 5297, "text": "Step 5 − Define the DML queries." }, { "code": null, "e": 5361, "s": 5330, "text": "Step 6 − Name the IMPORT file." }, { "code": null, "e": 5392, "s": 5361, "text": "Step 6 − Name the IMPORT file." }, { "code": null, "e": 5432, "s": 5392, "text": "Step 7 − Specify the LAYOUT to be used." }, { "code": null, "e": 5472, "s": 5432, "text": "Step 7 − Specify the LAYOUT to be used." }, { "code": null, "e": 5500, "s": 5472, "text": "Step 8 − Initiate the Load." }, { "code": null, "e": 5528, "s": 5500, "text": "Step 8 − Initiate the Load." }, { "code": null, "e": 5581, "s": 5528, "text": "Step 9 − Finish the load and terminate the sessions." }, { "code": null, "e": 5634, "s": 5581, "text": "Step 9 − Finish the load and terminate the sessions." }, { "code": null, "e": 5715, "s": 5634, "text": "Create a text file with the following records and name the file as employee.txt." }, { "code": null, "e": 5924, "s": 5715, "text": "101,Mike,James,1980-01-05,2010-03-01,1 \n102,Robert,Williams,1983-03-05,2010-09-01,1 \n103,Peter,Paul,1983-04-01,2009-02-12,2 \n104,Alex,Stuart,1984-11-06,2014-01-01,2 \n105,Robert,James,1984-12-01,2015-03-09,3 " }, { "code": null, "e": 6042, "s": 5924, "text": "The following example is a MultiLoad script that reads records from employee table and loads into Employee_Stg table." }, { "code": null, "e": 6927, "s": 6042, "text": ".LOGTABLE tduser.Employee_log; \n.LOGON 192.168.1.102/dbc,dbc; \n .BEGIN MLOAD TABLES Employee_Stg; \n .LAYOUT Employee; \n .FIELD in_EmployeeNo * VARCHAR(10); \n .FIELD in_FirstName * VARCHAR(30); \n .FIELD in_LastName * VARCHAR(30); \n .FIELD in_BirthDate * VARCHAR(10); \n .FIELD in_JoinedDate * VARCHAR(10); \n .FIELD in_DepartmentNo * VARCHAR(02);\n\n .DML LABEL EmpLabel; \n INSERT INTO Employee_Stg (\n EmployeeNo,\n FirstName,\n LastName,\n BirthDate,\n JoinedDate,\n DepartmentNo\n ) \n VALUES (\n :in_EmployeeNo,\n :in_FirstName,\n :in_Lastname,\n :in_BirthDate,\n :in_JoinedDate,\n :in_DepartmentNo\n );\n .IMPORT INFILE employee.txt \n FORMAT VARTEXT ','\n LAYOUT Employee\n APPLY EmpLabel; \n .END MLOAD; \nLOGOFF;" }, { "code": null, "e": 7112, "s": 6927, "text": "Once the input file employee.txt is created and the multiload script is named as EmployeeLoad.ml, then you can run the Multiload script using the following command in UNIX and Windows." }, { "code": null, "e": 7142, "s": 7112, "text": "Multiload < EmployeeLoad.ml;\n" }, { "code": null, "e": 7149, "s": 7142, "text": " Print" }, { "code": null, "e": 7160, "s": 7149, "text": " Add Notes" } ]
Sort a Rotated Sorted Array - GeeksforGeeks
07 Jul, 2021 You are given a rotated sorted array and your aim is to restore its original sort in place.Expected to use O(1) extra space and O(n) time complexity. Examples: Input : [3, 4, 1, 2] Output : [1, 2, 3, 4] Input : [2, 3, 4, 1] Output : [1, 2, 3, 4] We find the point of rotation. Then we rotate array using reversal algorithm. 1. First, find the split point where the sorting breaks. 2. Then call the reverse function in three steps. - From zero index to split index. - From split index to end index. - From zero index to end index. C++ Java Python3 C# Javascript // C++ implementation for restoring original// sort in rotated sorted array#include <bits/stdc++.h>using namespace std; // Function to restore the Original Sortvoid restoreSortedArray(int arr[], int n){ for (int i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr, arr+i+1); reverse(arr + i + 1, arr + n); reverse(arr, arr + n); } }} // Function to print the Arrayvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " ";} // Driver functionint main(){ int arr[] = { 3, 4, 5, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); restoreSortedArray(arr, n); printArray(arr, n); return 0;} // Java implementation for restoring original// sort in rotated sorted arrayclass GFG{ // Function to restore the Original Sortstatic void restoreSortedArray(int arr[], int n){ for (int i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr,0,i); reverse(arr , i + 1, n); reverse(arr,0, n); } }} static void reverse(int[] arr, int i, int j){ int temp; while(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; }} // Function to print the Arraystatic void printArray(int arr[], int size){ for (int i = 0; i < size; i++) System.out.print(arr[i] + " ");} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 4, 5, 1, 2 }; int n = arr.length; restoreSortedArray(arr, n - 1); printArray(arr, n);}} // This code has been contributed by 29AjayKumar # Python3 implementation for restoring original# sort in rotated sorted array # Function to restore the Original Sortdef restoreSortedArray(arr, n): for i in range(n): if (arr[i] > arr[i + 1]): # In reverse(), the first parameter # is iterator to beginning element # and second parameter is iterator # to last element plus one. reverse(arr, 0, i); reverse(arr, i + 1, n); reverse(arr, 0, n); def reverse(arr, i, j): while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i += 1; j -= 1; # Function to print the Arraydef printArray(arr, size): for i in range(size): print(arr[i], end=""); # Driver codeif __name__ == '__main__': arr = [3, 4, 5, 1, 2]; n = len(arr); restoreSortedArray(arr, n - 1); printArray(arr, n); # This code is contributed by 29AjayKumar // C# implementation for restoring original// sort in rotated sorted arrayusing System; class GFG{ // Function to restore the Original Sortstatic void restoreSortedArray(int []arr, int n){ for (int i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr,0,i); reverse(arr , i + 1, n); reverse(arr,0, n); } }} static void reverse(int[] arr, int i, int j){ int temp; while(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; }} // Function to print the Arraystatic void printArray(int []arr, int size){ for (int i = 0; i < size; i++) Console.Write(arr[i] + " ");} // Driver codepublic static void Main(String[] args){ int[] arr = { 3, 4, 5, 1, 2 }; int n = arr.Length; restoreSortedArray(arr, n - 1); printArray(arr, n);}} // This code contributed by Rajput-Ji <script>// JavaScript implementation for restoring original// sort in rotated sorted array // Function to restore the Original Sortfunction restoreSortedArray(arr, n){ for (let i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr,0,i); reverse(arr , i + 1, n); reverse(arr,0, n); } }} function reverse(arr, i, j){ let temp; while(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; }} // Function to print the Arrayfunction printArray(arr, size){ for (let i = 0; i < size; i++) document.write(arr[i] + " ");} // Driver Code let arr = [ 3, 4, 5, 1, 2 ]; let n = arr.length; restoreSortedArray(arr, n - 1); printArray(arr, n) </script> Output: 1 2 3 4 5 We can binary search to find the rotation point as discussed here .Efficient code approach using binary search: First find the index of minimum element (split index) in the array using binary searchThen call the reverse function in three steps.From zero index to split index.From split index to end index.From zero index to end index. First find the index of minimum element (split index) in the array using binary search Then call the reverse function in three steps.From zero index to split index.From split index to end index.From zero index to end index. From zero index to split index. From split index to end index. From zero index to end index. C++ Java Python3 C# Javascript // C++ implementation for restoring original// sort in rotated sorted array using binary search#include <bits/stdc++.h> using namespace std; // Function to find start index of arrayint findStartIndexOfArray(int arr[], int low,int high){ if (low>high) { return -1; } if (low == high) { return low; } int mid = low + (high-low)/2; if(arr[mid] > arr[mid+1]) return mid+1; if(arr[mid-1] > arr[mid]) return mid; if(arr[low] > arr[mid]) return findStartIndexOfArray(arr, low, mid-1); else return findStartIndexOfArray(arr, mid+1, high);} // Function to restore the Original Sortvoid restoreSortedArray(int arr[], int n){ // array is already sorted if (arr[0] < arr[n-1]) return; int start = findStartIndexOfArray(arr, 0, n-1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr, arr + start); reverse(arr + start, arr + n); reverse(arr, arr + n); } // Function to print the Arrayvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << " ";} // Driver functionint main(){ int arr[] = { 1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); restoreSortedArray(arr, n); printArray(arr, n); return 0;} // Java implementation for restoring original// sort in rotated sorted array using binary searchimport java.util.*; class GFG{ // Function to find start index of array static int findStartIndexOfArray(int arr[], int low, int high) { if (low > high) { return -1; } if (low == high) { return low; } int mid = low + (high - low) / 2; if (arr[mid] > arr[mid + 1]) { return mid + 1; } if (arr[mid - 1] > arr[mid]) { return mid; } if (arr[low] > arr[mid]) { return findStartIndexOfArray(arr, low, mid - 1); } else { return findStartIndexOfArray(arr, mid + 1, high); } } // Function to restore the Original Sort static void restoreSortedArray(int arr[], int n) { // array is already sorted if (arr[0] < arr[n - 1]) { return; } int start = findStartIndexOfArray(arr, 0, n - 1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. Arrays.sort(arr, 0, start); Arrays.sort(arr, start, n); Arrays.sort(arr); } // Function to print the Array static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { System.out.print(arr[i] + " "); } } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5}; int n = arr.length; restoreSortedArray(arr, n); printArray(arr, n); }} // This code contributed by Rajput-Ji # Python3 implementation for restoring original# sort in rotated sorted array using binary search # Function to find start index of arraydef findStartIndexOfArray(arr, low, high): if (low > high): return -1; if (low == high): return low; mid = low + (high - low) / 2; if (arr[mid] > arr[mid + 1]): return mid + 1; if (arr[mid - 1] > arr[mid]): return mid; if (arr[low] > arr[mid]): return findStartIndexOfArray(arr, low, mid - 1); else: return findStartIndexOfArray(arr, mid + 1, high); # Function to restore the Original Sortdef restoreSortedArray(arr, n): # array is already sorted if (arr[0] < arr[n - 1]): return; start = findStartIndexOfArray(arr, 0, n - 1); # In reverse(), the first parameter # is iterator to beginning element # and second parameter is iterator # to last element plus one. reverse(arr, 0, start); reverse(arr, start, n); reverse(arr); # Function to print the Arraydef printArray(arr, size): for i in range(size): print(arr[i], end=""); def reverse(arr, i, j): while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i += 1; j -= 1; # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5 ]; n = len(arr); restoreSortedArray(arr, n); printArray(arr, n); # This code is contributed by PrinciRaj1992 // C# implementation for restoring original// sort in rotated sorted array using binary searchusing System; class GFG{ // Function to find start index of array static int findStartIndexOfArray(int []arr, int low, int high) { if (low > high) { return -1; } if (low == high) { return low; } int mid = low + (high - low) / 2; if (arr[mid] > arr[mid + 1]) { return mid + 1; } if (arr[mid - 1] > arr[mid]) { return mid; } if (arr[low] > arr[mid]) { return findStartIndexOfArray(arr, low, mid - 1); } else { return findStartIndexOfArray(arr, mid + 1, high); } } // Function to restore the Original Sort static void restoreSortedArray(int []arr, int n) { // array is already sorted if (arr[0] < arr[n - 1]) { return; } int start = findStartIndexOfArray(arr, 0, n - 1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. Array.Sort(arr, 0, start); Array.Sort(arr, start, n); Array.Sort(arr); } // Function to print the Array static void printArray(int []arr, int size) { for (int i = 0; i < size; i++) { Console.Write(arr[i] + " "); } } // Driver code public static void Main() { int []arr = {1, 2, 3, 4, 5}; int n = arr.Length; restoreSortedArray(arr, n); printArray(arr, n); }} /* This code contributed by PrinciRaj1992 */ <script> // Javascript implementation for restoring original// sort in rotated sorted array using binary search // Function to find start index of arrayfunction findStartIndexOfArray(arr, low, high){ if (low > high) { return -1; } if (low == high) { return low; } let mid = low + parseInt((high - low) / 2, 10); if (arr[mid] > arr[mid + 1]) { return mid + 1; } if (arr[mid - 1] > arr[mid]) { return mid; } if (arr[low] > arr[mid]) { return findStartIndexOfArray(arr, low, mid - 1); } else { return findStartIndexOfArray(arr, mid + 1, high); }} // Function to restore the Original Sortfunction restoreSortedArray(arr, n){ // Array is already sorted if (arr[0] < arr[n - 1]) { return; } let start = findStartIndexOfArray(arr, 0, n - 1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. arr.sort(); } // Function to print the Arrayfunction printArray(arr, size){ for(let i = 0; i < size; i++) { document.write(arr[i] + " "); }} // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let n = arr.length; restoreSortedArray(arr, n);printArray(arr, n); // This code is contributed by decode2207 </script> Output: 1 2 3 4 5 This article is contributed by Kshitiz Gupta.If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Neha Jain Rajput-Ji princiraj1992 29AjayKumar Code_Mech code_hunt decode2207 sweetyty rotation Searching Sorting Searching Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to find largest element in an array k largest(or smallest) elements in an array Given an array of size n and a number k, find all elements that appear more than n/k times Median of two sorted arrays of different sizes Most frequent element in an array
[ { "code": null, "e": 25261, "s": 25233, "text": "\n07 Jul, 2021" }, { "code": null, "e": 25412, "s": 25261, "text": "You are given a rotated sorted array and your aim is to restore its original sort in place.Expected to use O(1) extra space and O(n) time complexity. " }, { "code": null, "e": 25423, "s": 25412, "text": "Examples: " }, { "code": null, "e": 25511, "s": 25423, "text": "Input : [3, 4, 1, 2] \nOutput : [1, 2, 3, 4]\n\nInput : [2, 3, 4, 1]\nOutput : [1, 2, 3, 4]" }, { "code": null, "e": 25590, "s": 25511, "text": "We find the point of rotation. Then we rotate array using reversal algorithm. " }, { "code": null, "e": 25813, "s": 25590, "text": " 1. First, find the split point where the sorting breaks.\n 2. Then call the reverse function in three steps.\n - From zero index to split index.\n - From split index to end index.\n - From zero index to end index." }, { "code": null, "e": 25817, "s": 25813, "text": "C++" }, { "code": null, "e": 25822, "s": 25817, "text": "Java" }, { "code": null, "e": 25830, "s": 25822, "text": "Python3" }, { "code": null, "e": 25833, "s": 25830, "text": "C#" }, { "code": null, "e": 25844, "s": 25833, "text": "Javascript" }, { "code": "// C++ implementation for restoring original// sort in rotated sorted array#include <bits/stdc++.h>using namespace std; // Function to restore the Original Sortvoid restoreSortedArray(int arr[], int n){ for (int i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr, arr+i+1); reverse(arr + i + 1, arr + n); reverse(arr, arr + n); } }} // Function to print the Arrayvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \";} // Driver functionint main(){ int arr[] = { 3, 4, 5, 1, 2 }; int n = sizeof(arr) / sizeof(arr[0]); restoreSortedArray(arr, n); printArray(arr, n); return 0;}", "e": 26730, "s": 25844, "text": null }, { "code": "// Java implementation for restoring original// sort in rotated sorted arrayclass GFG{ // Function to restore the Original Sortstatic void restoreSortedArray(int arr[], int n){ for (int i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr,0,i); reverse(arr , i + 1, n); reverse(arr,0, n); } }} static void reverse(int[] arr, int i, int j){ int temp; while(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; }} // Function to print the Arraystatic void printArray(int arr[], int size){ for (int i = 0; i < size; i++) System.out.print(arr[i] + \" \");} // Driver codepublic static void main(String[] args){ int arr[] = { 3, 4, 5, 1, 2 }; int n = arr.length; restoreSortedArray(arr, n - 1); printArray(arr, n);}} // This code has been contributed by 29AjayKumar", "e": 27824, "s": 26730, "text": null }, { "code": "# Python3 implementation for restoring original# sort in rotated sorted array # Function to restore the Original Sortdef restoreSortedArray(arr, n): for i in range(n): if (arr[i] > arr[i + 1]): # In reverse(), the first parameter # is iterator to beginning element # and second parameter is iterator # to last element plus one. reverse(arr, 0, i); reverse(arr, i + 1, n); reverse(arr, 0, n); def reverse(arr, i, j): while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i += 1; j -= 1; # Function to print the Arraydef printArray(arr, size): for i in range(size): print(arr[i], end=\"\"); # Driver codeif __name__ == '__main__': arr = [3, 4, 5, 1, 2]; n = len(arr); restoreSortedArray(arr, n - 1); printArray(arr, n); # This code is contributed by 29AjayKumar", "e": 28737, "s": 27824, "text": null }, { "code": "// C# implementation for restoring original// sort in rotated sorted arrayusing System; class GFG{ // Function to restore the Original Sortstatic void restoreSortedArray(int []arr, int n){ for (int i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr,0,i); reverse(arr , i + 1, n); reverse(arr,0, n); } }} static void reverse(int[] arr, int i, int j){ int temp; while(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; }} // Function to print the Arraystatic void printArray(int []arr, int size){ for (int i = 0; i < size; i++) Console.Write(arr[i] + \" \");} // Driver codepublic static void Main(String[] args){ int[] arr = { 3, 4, 5, 1, 2 }; int n = arr.Length; restoreSortedArray(arr, n - 1); printArray(arr, n);}} // This code contributed by Rajput-Ji", "e": 29833, "s": 28737, "text": null }, { "code": "<script>// JavaScript implementation for restoring original// sort in rotated sorted array // Function to restore the Original Sortfunction restoreSortedArray(arr, n){ for (let i = 0; i < n; i++) { if (arr[i] > arr[i + 1]) { // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr,0,i); reverse(arr , i + 1, n); reverse(arr,0, n); } }} function reverse(arr, i, j){ let temp; while(i < j) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; }} // Function to print the Arrayfunction printArray(arr, size){ for (let i = 0; i < size; i++) document.write(arr[i] + \" \");} // Driver Code let arr = [ 3, 4, 5, 1, 2 ]; let n = arr.length; restoreSortedArray(arr, n - 1); printArray(arr, n) </script>", "e": 30827, "s": 29833, "text": null }, { "code": null, "e": 30836, "s": 30827, "text": "Output: " }, { "code": null, "e": 30846, "s": 30836, "text": "1 2 3 4 5" }, { "code": null, "e": 30959, "s": 30846, "text": "We can binary search to find the rotation point as discussed here .Efficient code approach using binary search: " }, { "code": null, "e": 31182, "s": 30959, "text": "First find the index of minimum element (split index) in the array using binary searchThen call the reverse function in three steps.From zero index to split index.From split index to end index.From zero index to end index." }, { "code": null, "e": 31269, "s": 31182, "text": "First find the index of minimum element (split index) in the array using binary search" }, { "code": null, "e": 31406, "s": 31269, "text": "Then call the reverse function in three steps.From zero index to split index.From split index to end index.From zero index to end index." }, { "code": null, "e": 31438, "s": 31406, "text": "From zero index to split index." }, { "code": null, "e": 31469, "s": 31438, "text": "From split index to end index." }, { "code": null, "e": 31499, "s": 31469, "text": "From zero index to end index." }, { "code": null, "e": 31503, "s": 31499, "text": "C++" }, { "code": null, "e": 31508, "s": 31503, "text": "Java" }, { "code": null, "e": 31516, "s": 31508, "text": "Python3" }, { "code": null, "e": 31519, "s": 31516, "text": "C#" }, { "code": null, "e": 31530, "s": 31519, "text": "Javascript" }, { "code": "// C++ implementation for restoring original// sort in rotated sorted array using binary search#include <bits/stdc++.h> using namespace std; // Function to find start index of arrayint findStartIndexOfArray(int arr[], int low,int high){ if (low>high) { return -1; } if (low == high) { return low; } int mid = low + (high-low)/2; if(arr[mid] > arr[mid+1]) return mid+1; if(arr[mid-1] > arr[mid]) return mid; if(arr[low] > arr[mid]) return findStartIndexOfArray(arr, low, mid-1); else return findStartIndexOfArray(arr, mid+1, high);} // Function to restore the Original Sortvoid restoreSortedArray(int arr[], int n){ // array is already sorted if (arr[0] < arr[n-1]) return; int start = findStartIndexOfArray(arr, 0, n-1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. reverse(arr, arr + start); reverse(arr + start, arr + n); reverse(arr, arr + n); } // Function to print the Arrayvoid printArray(int arr[], int size){ for (int i = 0; i < size; i++) cout << arr[i] << \" \";} // Driver functionint main(){ int arr[] = { 1, 2, 3, 4, 5}; int n = sizeof(arr) / sizeof(arr[0]); restoreSortedArray(arr, n); printArray(arr, n); return 0;}", "e": 32902, "s": 31530, "text": null }, { "code": "// Java implementation for restoring original// sort in rotated sorted array using binary searchimport java.util.*; class GFG{ // Function to find start index of array static int findStartIndexOfArray(int arr[], int low, int high) { if (low > high) { return -1; } if (low == high) { return low; } int mid = low + (high - low) / 2; if (arr[mid] > arr[mid + 1]) { return mid + 1; } if (arr[mid - 1] > arr[mid]) { return mid; } if (arr[low] > arr[mid]) { return findStartIndexOfArray(arr, low, mid - 1); } else { return findStartIndexOfArray(arr, mid + 1, high); } } // Function to restore the Original Sort static void restoreSortedArray(int arr[], int n) { // array is already sorted if (arr[0] < arr[n - 1]) { return; } int start = findStartIndexOfArray(arr, 0, n - 1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. Arrays.sort(arr, 0, start); Arrays.sort(arr, start, n); Arrays.sort(arr); } // Function to print the Array static void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { System.out.print(arr[i] + \" \"); } } // Driver code public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5}; int n = arr.length; restoreSortedArray(arr, n); printArray(arr, n); }} // This code contributed by Rajput-Ji", "e": 34678, "s": 32902, "text": null }, { "code": "# Python3 implementation for restoring original# sort in rotated sorted array using binary search # Function to find start index of arraydef findStartIndexOfArray(arr, low, high): if (low > high): return -1; if (low == high): return low; mid = low + (high - low) / 2; if (arr[mid] > arr[mid + 1]): return mid + 1; if (arr[mid - 1] > arr[mid]): return mid; if (arr[low] > arr[mid]): return findStartIndexOfArray(arr, low, mid - 1); else: return findStartIndexOfArray(arr, mid + 1, high); # Function to restore the Original Sortdef restoreSortedArray(arr, n): # array is already sorted if (arr[0] < arr[n - 1]): return; start = findStartIndexOfArray(arr, 0, n - 1); # In reverse(), the first parameter # is iterator to beginning element # and second parameter is iterator # to last element plus one. reverse(arr, 0, start); reverse(arr, start, n); reverse(arr); # Function to print the Arraydef printArray(arr, size): for i in range(size): print(arr[i], end=\"\"); def reverse(arr, i, j): while (i < j): temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i += 1; j -= 1; # Driver codeif __name__ == '__main__': arr = [ 1, 2, 3, 4, 5 ]; n = len(arr); restoreSortedArray(arr, n); printArray(arr, n); # This code is contributed by PrinciRaj1992", "e": 36103, "s": 34678, "text": null }, { "code": "// C# implementation for restoring original// sort in rotated sorted array using binary searchusing System; class GFG{ // Function to find start index of array static int findStartIndexOfArray(int []arr, int low, int high) { if (low > high) { return -1; } if (low == high) { return low; } int mid = low + (high - low) / 2; if (arr[mid] > arr[mid + 1]) { return mid + 1; } if (arr[mid - 1] > arr[mid]) { return mid; } if (arr[low] > arr[mid]) { return findStartIndexOfArray(arr, low, mid - 1); } else { return findStartIndexOfArray(arr, mid + 1, high); } } // Function to restore the Original Sort static void restoreSortedArray(int []arr, int n) { // array is already sorted if (arr[0] < arr[n - 1]) { return; } int start = findStartIndexOfArray(arr, 0, n - 1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. Array.Sort(arr, 0, start); Array.Sort(arr, start, n); Array.Sort(arr); } // Function to print the Array static void printArray(int []arr, int size) { for (int i = 0; i < size; i++) { Console.Write(arr[i] + \" \"); } } // Driver code public static void Main() { int []arr = {1, 2, 3, 4, 5}; int n = arr.Length; restoreSortedArray(arr, n); printArray(arr, n); }} /* This code contributed by PrinciRaj1992 */", "e": 37859, "s": 36103, "text": null }, { "code": "<script> // Javascript implementation for restoring original// sort in rotated sorted array using binary search // Function to find start index of arrayfunction findStartIndexOfArray(arr, low, high){ if (low > high) { return -1; } if (low == high) { return low; } let mid = low + parseInt((high - low) / 2, 10); if (arr[mid] > arr[mid + 1]) { return mid + 1; } if (arr[mid - 1] > arr[mid]) { return mid; } if (arr[low] > arr[mid]) { return findStartIndexOfArray(arr, low, mid - 1); } else { return findStartIndexOfArray(arr, mid + 1, high); }} // Function to restore the Original Sortfunction restoreSortedArray(arr, n){ // Array is already sorted if (arr[0] < arr[n - 1]) { return; } let start = findStartIndexOfArray(arr, 0, n - 1); // In reverse(), the first parameter // is iterator to beginning element // and second parameter is iterator // to last element plus one. arr.sort(); } // Function to print the Arrayfunction printArray(arr, size){ for(let i = 0; i < size; i++) { document.write(arr[i] + \" \"); }} // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let n = arr.length; restoreSortedArray(arr, n);printArray(arr, n); // This code is contributed by decode2207 </script>", "e": 39276, "s": 37859, "text": null }, { "code": null, "e": 39285, "s": 39276, "text": "Output: " }, { "code": null, "e": 39295, "s": 39285, "text": "1 2 3 4 5" }, { "code": null, "e": 39716, "s": 39295, "text": "This article is contributed by Kshitiz Gupta.If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 39726, "s": 39716, "text": "Neha Jain" }, { "code": null, "e": 39736, "s": 39726, "text": "Rajput-Ji" }, { "code": null, "e": 39750, "s": 39736, "text": "princiraj1992" }, { "code": null, "e": 39762, "s": 39750, "text": "29AjayKumar" }, { "code": null, "e": 39772, "s": 39762, "text": "Code_Mech" }, { "code": null, "e": 39782, "s": 39772, "text": "code_hunt" }, { "code": null, "e": 39793, "s": 39782, "text": "decode2207" }, { "code": null, "e": 39802, "s": 39793, "text": "sweetyty" }, { "code": null, "e": 39811, "s": 39802, "text": "rotation" }, { "code": null, "e": 39821, "s": 39811, "text": "Searching" }, { "code": null, "e": 39829, "s": 39821, "text": "Sorting" }, { "code": null, "e": 39839, "s": 39829, "text": "Searching" }, { "code": null, "e": 39847, "s": 39839, "text": "Sorting" }, { "code": null, "e": 39945, "s": 39847, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39954, "s": 39945, "text": "Comments" }, { "code": null, "e": 39967, "s": 39954, "text": "Old Comments" }, { "code": null, "e": 40011, "s": 39967, "text": "Program to find largest element in an array" }, { "code": null, "e": 40055, "s": 40011, "text": "k largest(or smallest) elements in an array" }, { "code": null, "e": 40146, "s": 40055, "text": "Given an array of size n and a number k, find all elements that appear more than n/k times" }, { "code": null, "e": 40193, "s": 40146, "text": "Median of two sorted arrays of different sizes" } ]
How to compute the histogram of a tensor in PyTorch?
The histogram of a tensor is computed using torch.histc(). It returns a histogram represented as a tensor. It takes four parameters: input, bins, min and max. It sorts the elements into equal width bins between min and max. It ignores the elements smaller than the min and greater than the max. Import the required library. In all the following Python examples, the required Python libraries are torch and Matplotlib. Make sure you have already installed them. Import the required library. In all the following Python examples, the required Python libraries are torch and Matplotlib. Make sure you have already installed them. Create a tensor and print it. Create a tensor and print it. Compute torch.histc(input, bins=100, min=0, max=100). It returns a tensor of histogram values. Set bins, min, and max to appropriate values according to your need. Compute torch.histc(input, bins=100, min=0, max=100). It returns a tensor of histogram values. Set bins, min, and max to appropriate values according to your need. Print the above calculated histogram. Print the above calculated histogram. Visualize the histogram as a bar diagram. Visualize the histogram as a bar diagram. # Python program to calculate histogram of a tensor # import necessary libraries import torch import matplotlib.pyplot as plt # Create a tensor T = torch.Tensor([2,3,1,2,3,4,3,2,3,4,3,4]) print("Original Tensor T:\n",T) # Calculate the histogram of the above created tensor hist = torch.histc(T, bins = 5, min = 0, max = 4) print("Histogram of T:\n", hist) Original Tensor T: tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.]) Histogram of T: tensor([0., 1., 3., 5., 3.]) # Python program to calculate histogram of a tensor # import necessary libraries import torch import matplotlib.pyplot as plt # Create a tensor T = torch.Tensor([2,3,1,2,3,4,3,2,3,4,3,4]) print("Original Tensor T:\n",T) # Calculate the histogram of the above created tensor hist = torch.histc(T, bins = 5, min = 0, max = 4) # Visualize above calculated histogram as bar diagram bins = 5 x = range(bins) plt.bar(x, hist, align='center') plt.xlabel('Bins') plt.ylabel('Frequency') plt.show() Original Tensor T: tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.])
[ { "code": null, "e": 1357, "s": 1062, "text": "The histogram of a tensor is computed using torch.histc(). It returns a histogram represented as a tensor. It takes four parameters: input, bins, min and max. It sorts the elements into equal width bins between min and max. It ignores the elements smaller than the min and greater than the max." }, { "code": null, "e": 1523, "s": 1357, "text": "Import the required library. In all the following Python examples, the required Python libraries are torch and Matplotlib. Make sure you have already installed them." }, { "code": null, "e": 1689, "s": 1523, "text": "Import the required library. In all the following Python examples, the required Python libraries are torch and Matplotlib. Make sure you have already installed them." }, { "code": null, "e": 1719, "s": 1689, "text": "Create a tensor and print it." }, { "code": null, "e": 1749, "s": 1719, "text": "Create a tensor and print it." }, { "code": null, "e": 1913, "s": 1749, "text": "Compute torch.histc(input, bins=100, min=0, max=100). It\nreturns a tensor of histogram values. Set bins, min, and max to\nappropriate values according to your need." }, { "code": null, "e": 2077, "s": 1913, "text": "Compute torch.histc(input, bins=100, min=0, max=100). It\nreturns a tensor of histogram values. Set bins, min, and max to\nappropriate values according to your need." }, { "code": null, "e": 2115, "s": 2077, "text": "Print the above calculated histogram." }, { "code": null, "e": 2153, "s": 2115, "text": "Print the above calculated histogram." }, { "code": null, "e": 2195, "s": 2153, "text": "Visualize the histogram as a bar diagram." }, { "code": null, "e": 2237, "s": 2195, "text": "Visualize the histogram as a bar diagram." }, { "code": null, "e": 2596, "s": 2237, "text": "# Python program to calculate histogram of a tensor\n# import necessary libraries\nimport torch\nimport matplotlib.pyplot as plt\n\n# Create a tensor\nT = torch.Tensor([2,3,1,2,3,4,3,2,3,4,3,4])\nprint(\"Original Tensor T:\\n\",T)\n\n# Calculate the histogram of the above created tensor\nhist = torch.histc(T, bins = 5, min = 0, max = 4)\nprint(\"Histogram of T:\\n\", hist)" }, { "code": null, "e": 2723, "s": 2596, "text": "Original Tensor T:\n tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.])\nHistogram of T:\n tensor([0., 1., 3., 5., 3.])" }, { "code": null, "e": 3216, "s": 2723, "text": "# Python program to calculate histogram of a tensor\n# import necessary libraries\nimport torch\nimport matplotlib.pyplot as plt\n\n# Create a tensor\nT = torch.Tensor([2,3,1,2,3,4,3,2,3,4,3,4])\nprint(\"Original Tensor T:\\n\",T)\n\n# Calculate the histogram of the above created tensor\nhist = torch.histc(T, bins = 5, min = 0, max = 4)\n\n# Visualize above calculated histogram as bar diagram\nbins = 5\nx = range(bins)\nplt.bar(x, hist, align='center')\nplt.xlabel('Bins')\nplt.ylabel('Frequency')\nplt.show()" }, { "code": null, "e": 3295, "s": 3216, "text": "Original Tensor T:\n tensor([2., 3., 1., 2., 3., 4., 3., 2., 3., 4., 3., 4.])" } ]
PostgreSQL - ALIAS Syntax
You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular PostgreSQL statement. Renaming is a temporary change and the actual table name does not change in the database. The column aliases are used to rename a table's columns for the purpose of a particular PostgreSQL query. The basic syntax of table alias is as follows − SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition]; The basic syntax of column alias is as follows − SELECT column_name AS alias_name FROM table_name WHERE [condition]; Consider the following two tables, (a) COMPANY table is as follows − testdb=# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows) (b) Another table is DEPARTMENT as follows − id | dept | emp_id ----+--------------+-------- 1 | IT Billing | 1 2 | Engineering | 2 3 | Finance | 7 4 | Engineering | 3 5 | Finance | 4 6 | Engineering | 5 7 | Finance | 6 (7 rows) Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables, respectively − testdb=# SELECT C.ID, C.NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID; The above given PostgreSQL statement will produce the following result − id | name | age | dept ----+-------+-----+------------ 1 | Paul | 32 | IT Billing 2 | Allen | 25 | Engineering 7 | James | 24 | Finance 3 | Teddy | 23 | Engineering 4 | Mark | 25 | Finance 5 | David | 27 | Engineering 6 | Kim | 22 | Finance (7 rows) Let us see an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column − testdb=# SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT FROM COMPANY AS C, DEPARTMENT AS D WHERE C.ID = D.EMP_ID; The above given PostgreSQL statement will produce the following result − company_id | company_name | age | dept ------------+--------------+-----+------------ 1 | Paul | 32 | IT Billing 2 | Allen | 25 | Engineering 7 | James | 24 | Finance 3 | Teddy | 23 | Engineering 4 | Mark | 25 | Finance 5 | David | 27 | Engineering 6 | Kim | 22 | Finance (7 rows) 23 Lectures 1.5 hours John Elder 49 Lectures 3.5 hours Niyazi Erdogan 126 Lectures 10.5 hours Abhishek And Pukhraj 35 Lectures 5 hours Karthikeya T 5 Lectures 51 mins Vinay Kumar 5 Lectures 52 mins Vinay Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 3098, "s": 2825, "text": "You can rename a table or a column temporarily by giving another name, which is known as ALIAS. The use of table aliases means to rename a table in a particular PostgreSQL statement. Renaming is a temporary change and the actual table name does not change in the database." }, { "code": null, "e": 3204, "s": 3098, "text": "The column aliases are used to rename a table's columns for the purpose of a particular PostgreSQL query." }, { "code": null, "e": 3252, "s": 3204, "text": "The basic syntax of table alias is as follows −" }, { "code": null, "e": 3330, "s": 3252, "text": "SELECT column1, column2....\nFROM table_name AS alias_name\nWHERE [condition];\n" }, { "code": null, "e": 3379, "s": 3330, "text": "The basic syntax of column alias is as follows −" }, { "code": null, "e": 3448, "s": 3379, "text": "SELECT column_name AS alias_name\nFROM table_name\nWHERE [condition];\n" }, { "code": null, "e": 3517, "s": 3448, "text": "Consider the following two tables, (a) COMPANY table is as follows −" }, { "code": null, "e": 3910, "s": 3517, "text": "testdb=# select * from COMPANY;\n id | name | age | address | salary\n----+-------+-----+-----------+--------\n 1 | Paul | 32 | California| 20000\n 2 | Allen | 25 | Texas | 15000\n 3 | Teddy | 23 | Norway | 20000\n 4 | Mark | 25 | Rich-Mond | 65000\n 5 | David | 27 | Texas | 85000\n 6 | Kim | 22 | South-Hall| 45000\n 7 | James | 24 | Houston | 10000\n(7 rows)" }, { "code": null, "e": 3955, "s": 3910, "text": "(b) Another table is DEPARTMENT as follows −" }, { "code": null, "e": 4217, "s": 3955, "text": " id | dept | emp_id\n----+--------------+--------\n 1 | IT Billing | 1\n 2 | Engineering | 2\n 3 | Finance | 7\n 4 | Engineering | 3\n 5 | Finance | 4\n 6 | Engineering | 5\n 7 | Finance | 6\n(7 rows)" }, { "code": null, "e": 4342, "s": 4217, "text": "Now, following is the usage of TABLE ALIAS where we use C and D as aliases for COMPANY and DEPARTMENT tables, respectively −" }, { "code": null, "e": 4451, "s": 4342, "text": "testdb=# SELECT C.ID, C.NAME, C.AGE, D.DEPT\n FROM COMPANY AS C, DEPARTMENT AS D\n WHERE C.ID = D.EMP_ID;" }, { "code": null, "e": 4524, "s": 4451, "text": "The above given PostgreSQL statement will produce the following result −" }, { "code": null, "e": 4803, "s": 4524, "text": " id | name | age | dept\n----+-------+-----+------------\n 1 | Paul | 32 | IT Billing\n 2 | Allen | 25 | Engineering\n 7 | James | 24 | Finance\n 3 | Teddy | 23 | Engineering\n 4 | Mark | 25 | Finance\n 5 | David | 27 | Engineering\n 6 | Kim | 22 | Finance\n(7 rows)\n" }, { "code": null, "e": 4943, "s": 4803, "text": "Let us see an example for the usage of COLUMN ALIAS where COMPANY_ID is an alias of ID column and COMPANY_NAME is an alias of name column −" }, { "code": null, "e": 5082, "s": 4943, "text": "testdb=# SELECT C.ID AS COMPANY_ID, C.NAME AS COMPANY_NAME, C.AGE, D.DEPT\n FROM COMPANY AS C, DEPARTMENT AS D\n WHERE C.ID = D.EMP_ID;" }, { "code": null, "e": 5155, "s": 5082, "text": "The above given PostgreSQL statement will produce the following result −" }, { "code": null, "e": 5568, "s": 5155, "text": " company_id | company_name | age | dept\n------------+--------------+-----+------------\n 1 | Paul | 32 | IT Billing\n 2 | Allen | 25 | Engineering\n 7 | James | 24 | Finance\n 3 | Teddy | 23 | Engineering\n 4 | Mark | 25 | Finance\n 5 | David | 27 | Engineering\n 6 | Kim | 22 | Finance\n(7 rows)\n" }, { "code": null, "e": 5603, "s": 5568, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5615, "s": 5603, "text": " John Elder" }, { "code": null, "e": 5650, "s": 5615, "text": "\n 49 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5666, "s": 5650, "text": " Niyazi Erdogan" }, { "code": null, "e": 5703, "s": 5666, "text": "\n 126 Lectures \n 10.5 hours \n" }, { "code": null, "e": 5725, "s": 5703, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 5758, "s": 5725, "text": "\n 35 Lectures \n 5 hours \n" }, { "code": null, "e": 5772, "s": 5758, "text": " Karthikeya T" }, { "code": null, "e": 5803, "s": 5772, "text": "\n 5 Lectures \n 51 mins\n" }, { "code": null, "e": 5816, "s": 5803, "text": " Vinay Kumar" }, { "code": null, "e": 5847, "s": 5816, "text": "\n 5 Lectures \n 52 mins\n" }, { "code": null, "e": 5860, "s": 5847, "text": " Vinay Kumar" }, { "code": null, "e": 5867, "s": 5860, "text": " Print" }, { "code": null, "e": 5878, "s": 5867, "text": " Add Notes" } ]
Cordova - Media
Cordova media plugin is used for recording and playing audio sounds in Cordova apps. Media plugin can be installed by running the following code in command prompt window. C:\Users\username\Desktop\CordovaProject>cordova plugin add cordova-plugin-media In this tutorial, we will create simple audio player. Let's create buttons that we need in index.html. <button id = "playAudio">PLAY</button> <button id = "pauseAudio">PAUSE</button> <button id = "stopAudio">STOP</button> <button id = "volumeUp">VOLUME UP</button> <button id = "volumeDown">VOLUME DOWN</button> Now we need to add event listeners for our buttons inside onDeviceReady function inside index.js. document.getElementById("playAudio").addEventListener("click", playAudio); document.getElementById("pauseAudio").addEventListener("click", pauseAudio); document.getElementById("stopAudio").addEventListener("click", stopAudio); document.getElementById("volumeUp").addEventListener("click", volumeUp); document.getElementById("volumeDown").addEventListener("click", volumeDown); The first function that we are going to add is playAudio. We are defining myMedia outside of the function because we want to use it in functions that are going to be added later (pause, stop, volumeUp and volumeDown). This code is placed in index.js file. var myMedia = null; function playAudio() { var src = "/android_asset/www/audio/piano.mp3"; if(myMedia === null) { myMedia = new Media(src, onSuccess, onError); function onSuccess() { console.log("playAudio Success"); } function onError(error) { console.log("playAudio Error: " + error.code); } } myMedia.play(); } We can click PLAY button to start the piano music from the src path. The next functions that we need is pauseAudio and stopAudio. function pauseAudio() { if(myMedia) { myMedia.pause(); } } function stopAudio() { if(myMedia) { myMedia.stop(); } myMedia = null; } Now we can pause or stop the piano sound by clicking PAUSE or STOP buttons. To set the volume, we can use setVolume method. This method takes parameter with values from 0 to 1. We will set starting value to 0.5. var volumeValue = 0.5; function volumeUp() { if(myMedia && volumeValue < 1) { myMedia.setVolume(volumeValue += 0.1); } } function volumeDown() { if(myMedia && volumeValue > 0) { myMedia.setVolume(volumeValue -= 0.1); } } Once we press VOLUME UP or VOLUME DOWN we can change the volume value by 0.1. The following table shows other methods that this plugin provides. getCurrentPosition Returns current position of an audio. getDuration Returns duration of an audio. play Used for starting or resuming audio. pause Used for pausing audio. release Releases the underlying operating system's audio resources. seekTo Used for changing position of an audio. setVolume Used for setting volume for audio. startRecord Start recording an audio file. stopRecord Stop recording an audio file. stop Stop playing an audio file. 45 Lectures 2 hours Skillbakerystudios 16 Lectures 1 hours Nilay Mehta Print Add Notes Bookmark this page
[ { "code": null, "e": 2265, "s": 2180, "text": "Cordova media plugin is used for recording and playing audio sounds in Cordova apps." }, { "code": null, "e": 2351, "s": 2265, "text": "Media plugin can be installed by running the following code in command prompt window." }, { "code": null, "e": 2433, "s": 2351, "text": "C:\\Users\\username\\Desktop\\CordovaProject>cordova plugin add cordova-plugin-media\n" }, { "code": null, "e": 2536, "s": 2433, "text": "In this tutorial, we will create simple audio player. Let's create buttons that we need in index.html." }, { "code": null, "e": 2745, "s": 2536, "text": "<button id = \"playAudio\">PLAY</button>\n<button id = \"pauseAudio\">PAUSE</button>\n<button id = \"stopAudio\">STOP</button>\n<button id = \"volumeUp\">VOLUME UP</button>\n<button id = \"volumeDown\">VOLUME DOWN</button>" }, { "code": null, "e": 2843, "s": 2745, "text": "Now we need to add event listeners for our buttons inside onDeviceReady function inside index.js." }, { "code": null, "e": 3220, "s": 2843, "text": "document.getElementById(\"playAudio\").addEventListener(\"click\", playAudio);\ndocument.getElementById(\"pauseAudio\").addEventListener(\"click\", pauseAudio);\ndocument.getElementById(\"stopAudio\").addEventListener(\"click\", stopAudio);\ndocument.getElementById(\"volumeUp\").addEventListener(\"click\", volumeUp);\ndocument.getElementById(\"volumeDown\").addEventListener(\"click\", volumeDown);" }, { "code": null, "e": 3476, "s": 3220, "text": "The first function that we are going to add is playAudio. We are defining myMedia outside of the function because we want to use it in functions that are going to be added later (pause, stop, volumeUp and volumeDown). This code is placed in index.js file." }, { "code": null, "e": 3853, "s": 3476, "text": "var myMedia = null;\nfunction playAudio() {\n var src = \"/android_asset/www/audio/piano.mp3\";\n\n if(myMedia === null) {\n myMedia = new Media(src, onSuccess, onError);\n\n function onSuccess() {\n console.log(\"playAudio Success\");\n }\n\n function onError(error) {\n console.log(\"playAudio Error: \" + error.code);\n }\n }\n myMedia.play();\n}" }, { "code": null, "e": 3922, "s": 3853, "text": "We can click PLAY button to start the piano music from the src path." }, { "code": null, "e": 3983, "s": 3922, "text": "The next functions that we need is pauseAudio and stopAudio." }, { "code": null, "e": 4144, "s": 3983, "text": "function pauseAudio() {\n if(myMedia) {\n myMedia.pause();\n }\n}\n\nfunction stopAudio() {\n if(myMedia) {\n myMedia.stop(); \n }\n myMedia = null;\n}" }, { "code": null, "e": 4220, "s": 4144, "text": "Now we can pause or stop the piano sound by clicking PAUSE or STOP buttons." }, { "code": null, "e": 4356, "s": 4220, "text": "To set the volume, we can use setVolume method. This method takes parameter with values from 0 to 1. We will set starting value to 0.5." }, { "code": null, "e": 4602, "s": 4356, "text": "var volumeValue = 0.5;\nfunction volumeUp() {\n if(myMedia && volumeValue < 1) {\n myMedia.setVolume(volumeValue += 0.1);\n }\n}\n\nfunction volumeDown() {\n if(myMedia && volumeValue > 0) {\n myMedia.setVolume(volumeValue -= 0.1);\n }\n}" }, { "code": null, "e": 4680, "s": 4602, "text": "Once we press VOLUME UP or VOLUME DOWN we can change the volume value by 0.1." }, { "code": null, "e": 4747, "s": 4680, "text": "The following table shows other methods that this plugin provides." }, { "code": null, "e": 4766, "s": 4747, "text": "getCurrentPosition" }, { "code": null, "e": 4804, "s": 4766, "text": "Returns current position of an audio." }, { "code": null, "e": 4816, "s": 4804, "text": "getDuration" }, { "code": null, "e": 4846, "s": 4816, "text": "Returns duration of an audio." }, { "code": null, "e": 4851, "s": 4846, "text": "play" }, { "code": null, "e": 4888, "s": 4851, "text": "Used for starting or resuming audio." }, { "code": null, "e": 4894, "s": 4888, "text": "pause" }, { "code": null, "e": 4918, "s": 4894, "text": "Used for pausing audio." }, { "code": null, "e": 4926, "s": 4918, "text": "release" }, { "code": null, "e": 4986, "s": 4926, "text": "Releases the underlying operating system's audio resources." }, { "code": null, "e": 4993, "s": 4986, "text": "seekTo" }, { "code": null, "e": 5033, "s": 4993, "text": "Used for changing position of an audio." }, { "code": null, "e": 5043, "s": 5033, "text": "setVolume" }, { "code": null, "e": 5078, "s": 5043, "text": "Used for setting volume for audio." }, { "code": null, "e": 5090, "s": 5078, "text": "startRecord" }, { "code": null, "e": 5121, "s": 5090, "text": "Start recording an audio file." }, { "code": null, "e": 5132, "s": 5121, "text": "stopRecord" }, { "code": null, "e": 5162, "s": 5132, "text": "Stop recording an audio file." }, { "code": null, "e": 5167, "s": 5162, "text": "stop" }, { "code": null, "e": 5195, "s": 5167, "text": "Stop playing an audio file." }, { "code": null, "e": 5228, "s": 5195, "text": "\n 45 Lectures \n 2 hours \n" }, { "code": null, "e": 5248, "s": 5228, "text": " Skillbakerystudios" }, { "code": null, "e": 5281, "s": 5248, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 5294, "s": 5281, "text": " Nilay Mehta" }, { "code": null, "e": 5301, "s": 5294, "text": " Print" }, { "code": null, "e": 5312, "s": 5301, "text": " Add Notes" } ]
Coloring Plotly Box-Plots. Applying a custom color scale to Plotly... | by Shah Newaz Khan | Towards Data Science
I was recently asked by my boss to apply a color scale to a series of Plotly Box plots I was working on for a Dash application. The notion was to plot multiple box plots on the same graph and have each box plot be darker or lighter based on its distance from the overall median in the dataset. The issue here is that Plotly only supports color scales for heatmaps, scatter plots & contour plots. I will demonstrate the default behavior by plotting some generated data for Canucks players +/- per game all time as follows: Note: Complete code at the end of the post The dashed green line represents the NHL league average +/- per game at +2.0, what my boss wanted was to color each box plot darker or lighter based on how far away each players median +/- value was from the league average . Given that I was already in a Python environment, I chose to use the colormap & colormap normalizer features from the Matplotlib Python module. First step was to import Matplotlib: import matplotlib.pyplot as pltimport matplotlibimport pandas as pd Then determine the minand maxvalues in the dataset: x_data = ['Henrik Sedin', 'Daniel Sedin', 'Brock Boeser', 'Elias Pettersen', 'Bo Horvat', 'Pavel Bure',]# Generate random datay0 = np.random.randn(50)+4y1 = np.random.randn(50)+4y2 = np.random.randn(50)+2y3 = np.random.randn(50)+2y4 = np.random.randn(50)+1y5 = np.random.randn(50)+3y_data = [y0,y1,y2,y3,y4,y5]df = pd.DataFrame(y_data)vmin, vmax = df.min().min(), df.max().max() Initialize the Matplotlib cmap & normalizer: norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)cmap = matplotlib.cm.get_cmap('GnBu') # green to blue color way Find the median of each y_data and use the normalizer to map it to an appropriate color based on the median value: for xd, yd in zip(x_data, y_data): median = np.median(yd) # find the median color = 'rgb' + str(cmap(norm(median))[0:3]) # normalize traces.append(go.Box( y=yd, name=xd, boxpoints='all', jitter=0.5, whiskerwidth=0.2, fillcolor=color, # add the box plot color marker=dict( size=2, ), line=dict(width=1) )) The resulting plot will render a darker fillcolorthe further positive the players median +/- is from the league average and vice versa. Here is the complete code to get the result above: from plotly import __version__from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotinit_notebook_mode(connected=True)import plotly.graph_objs as goimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlibx_data = ['Henrik Sedin', 'Daniel Sedin', 'Brock Boeser', 'Elias Pettersen', 'Bo Horvat', 'Pavel Bure',]y0 = np.random.randn(50)+4y1 = np.random.randn(50)+4y2 = np.random.randn(50)+2y3 = np.random.randn(50)+2y4 = np.random.randn(50)+1y5 = np.random.randn(50)+3y_data = [y0,y1,y2,y3,y4,y5]traces = []df = pd.DataFrame(y_data)vmin, vmax = df.min().min(), df.max().max()norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)cmap = matplotlib.cm.get_cmap('GnBu')for xd, yd in zip(x_data, y_data): median = np.median(yd) color = 'rgb' + str(cmap(norm(median))[0:3]) traces.append(go.Box( y=yd, name=xd, boxpoints='all', jitter=0.5, whiskerwidth=0.2, fillcolor=color, marker=dict( size=2, color='rgb(0, 0, 0)' ), line=dict(width=1), ))layout = go.Layout( title='Canucks all time +/- per game', yaxis=dict( autorange=True, showgrid=True, zeroline=True, dtick=5, gridcolor='rgb(255, 255, 255)', gridwidth=1, zerolinecolor='rgb(255, 255, 255)', zerolinewidth=2, ), margin=dict( l=40, r=30, b=80, t=100, ), paper_bgcolor='rgb(243, 243, 243)', plot_bgcolor='rgb(243, 243, 243)', showlegend=False, shapes= [{ 'type': 'line', 'x0': -1, 'y0': 2, 'x1': 6, 'y1': 2, 'line': { 'color': 'rgb(50, 171, 96)', 'width': 4, 'dash': 'dashdot' } }])fig = go.Figure(data=traces, layout=layout)iplot(fig)
[ { "code": null, "e": 466, "s": 172, "text": "I was recently asked by my boss to apply a color scale to a series of Plotly Box plots I was working on for a Dash application. The notion was to plot multiple box plots on the same graph and have each box plot be darker or lighter based on its distance from the overall median in the dataset." }, { "code": null, "e": 568, "s": 466, "text": "The issue here is that Plotly only supports color scales for heatmaps, scatter plots & contour plots." }, { "code": null, "e": 694, "s": 568, "text": "I will demonstrate the default behavior by plotting some generated data for Canucks players +/- per game all time as follows:" }, { "code": null, "e": 737, "s": 694, "text": "Note: Complete code at the end of the post" }, { "code": null, "e": 962, "s": 737, "text": "The dashed green line represents the NHL league average +/- per game at +2.0, what my boss wanted was to color each box plot darker or lighter based on how far away each players median +/- value was from the league average ." }, { "code": null, "e": 1106, "s": 962, "text": "Given that I was already in a Python environment, I chose to use the colormap & colormap normalizer features from the Matplotlib Python module." }, { "code": null, "e": 1143, "s": 1106, "text": "First step was to import Matplotlib:" }, { "code": null, "e": 1211, "s": 1143, "text": "import matplotlib.pyplot as pltimport matplotlibimport pandas as pd" }, { "code": null, "e": 1263, "s": 1211, "text": "Then determine the minand maxvalues in the dataset:" }, { "code": null, "e": 1660, "s": 1263, "text": "x_data = ['Henrik Sedin', 'Daniel Sedin', 'Brock Boeser', 'Elias Pettersen', 'Bo Horvat', 'Pavel Bure',]# Generate random datay0 = np.random.randn(50)+4y1 = np.random.randn(50)+4y2 = np.random.randn(50)+2y3 = np.random.randn(50)+2y4 = np.random.randn(50)+1y5 = np.random.randn(50)+3y_data = [y0,y1,y2,y3,y4,y5]df = pd.DataFrame(y_data)vmin, vmax = df.min().min(), df.max().max()" }, { "code": null, "e": 1705, "s": 1660, "text": "Initialize the Matplotlib cmap & normalizer:" }, { "code": null, "e": 1825, "s": 1705, "text": "norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax)cmap = matplotlib.cm.get_cmap('GnBu') # green to blue color way" }, { "code": null, "e": 1940, "s": 1825, "text": "Find the median of each y_data and use the normalizer to map it to an appropriate color based on the median value:" }, { "code": null, "e": 2408, "s": 1940, "text": "for xd, yd in zip(x_data, y_data): median = np.median(yd) # find the median color = 'rgb' + str(cmap(norm(median))[0:3]) # normalize traces.append(go.Box( y=yd, name=xd, boxpoints='all', jitter=0.5, whiskerwidth=0.2, fillcolor=color, # add the box plot color marker=dict( size=2, ), line=dict(width=1) ))" }, { "code": null, "e": 2544, "s": 2408, "text": "The resulting plot will render a darker fillcolorthe further positive the players median +/- is from the league average and vice versa." }, { "code": null, "e": 2595, "s": 2544, "text": "Here is the complete code to get the result above:" } ]
C++ Regex Library - regex_match
It returns whether the target sequence matches the regular expression rgx. The target sequence is either s or the character sequence between first and last, depending on the version used. Following is the declaration for std::regex_match. template <class charT, class traits> bool regex_match (const charT* s, const basic_regex<charT,traits>& rgx, regex_constants::match_flag_type flags = regex_constants::match_default); template <class charT, class traits> bool regex_match (const charT* s, const basic_regex<charT,traits>& rgx, regex_constants::match_flag_type flags = regex_constants::match_default); template <class charT, class traits> bool regex_match (const charT* s, const basic_regex<charT,traits>& rgx, regex_constants::match_flag_type flags = regex_constants::match_default); s − It is a string with the target sequence. s − It is a string with the target sequence. rgx − It is a basic_regex object to match. rgx − It is a basic_regex object to match. flags − It is used to control how rgx is matched. flags − It is used to control how rgx is matched. m − It is an object of a match_results type. m − It is an object of a match_results type. It returns true if rgx is matched against the target sequence. false otherwise. No-noexcept − this member function never throws exceptions. In below example for std::regex_match. #include <iostream> #include <string> #include <regex> int main () { if (std::regex_match ("subject", std::regex("(sub)(.*)") )) std::cout << "string literal matched\n"; const char cstr[] = "subject"; std::string s ("subject"); std::regex e ("(sub)(.*)"); if (std::regex_match (s,e)) std::cout << "string object matched\n"; if ( std::regex_match ( s.begin(), s.end(), e ) ) std::cout << "range matched\n"; std::cmatch cm; std::regex_match (cstr,cm,e); std::cout << "string literal with " << cm.size() << " matches\n"; std::smatch sm; std::regex_match (s,sm,e); std::cout << "string object with " << sm.size() << " matches\n"; std::regex_match ( s.cbegin(), s.cend(), sm, e); std::cout << "range with " << sm.size() << " matches\n"; std::regex_match ( cstr, cm, e, std::regex_constants::match_default ); std::cout << "the matches were: "; for (unsigned i=0; i<sm.size(); ++i) { std::cout << "[" << sm[i] << "] "; } std::cout << std::endl; return 0; } The output should be like this − string literal matched string object matched range matched string literal with 3 matches string object with 3 matches range with 3 matches the matches were: [subject] [sub] [ject] Print Add Notes Bookmark this page
[ { "code": null, "e": 2791, "s": 2603, "text": "It returns whether the target sequence matches the regular expression rgx. The target sequence is either s or the character sequence between first and last, depending on the version used." }, { "code": null, "e": 2842, "s": 2791, "text": "Following is the declaration for std::regex_match." }, { "code": null, "e": 3031, "s": 2842, "text": "template <class charT, class traits>\n bool regex_match (const charT* s, const basic_regex<charT,traits>& rgx,\n regex_constants::match_flag_type flags = regex_constants::match_default);" }, { "code": null, "e": 3220, "s": 3031, "text": "template <class charT, class traits>\n bool regex_match (const charT* s, const basic_regex<charT,traits>& rgx,\n regex_constants::match_flag_type flags = regex_constants::match_default);" }, { "code": null, "e": 3409, "s": 3220, "text": "template <class charT, class traits>\n bool regex_match (const charT* s, const basic_regex<charT,traits>& rgx,\n regex_constants::match_flag_type flags = regex_constants::match_default);" }, { "code": null, "e": 3454, "s": 3409, "text": "s − It is a string with the target sequence." }, { "code": null, "e": 3499, "s": 3454, "text": "s − It is a string with the target sequence." }, { "code": null, "e": 3542, "s": 3499, "text": "rgx − It is a basic_regex object to match." }, { "code": null, "e": 3585, "s": 3542, "text": "rgx − It is a basic_regex object to match." }, { "code": null, "e": 3635, "s": 3585, "text": "flags − It is used to control how rgx is matched." }, { "code": null, "e": 3685, "s": 3635, "text": "flags − It is used to control how rgx is matched." }, { "code": null, "e": 3730, "s": 3685, "text": "m − It is an object of a match_results type." }, { "code": null, "e": 3775, "s": 3730, "text": "m − It is an object of a match_results type." }, { "code": null, "e": 3855, "s": 3775, "text": "It returns true if rgx is matched against the target sequence. false otherwise." }, { "code": null, "e": 3915, "s": 3855, "text": "No-noexcept − this member function never throws exceptions." }, { "code": null, "e": 3954, "s": 3915, "text": "In below example for std::regex_match." }, { "code": null, "e": 5003, "s": 3954, "text": "#include <iostream>\n#include <string>\n#include <regex>\n\nint main () {\n\n if (std::regex_match (\"subject\", std::regex(\"(sub)(.*)\") ))\n std::cout << \"string literal matched\\n\";\n\n const char cstr[] = \"subject\";\n std::string s (\"subject\");\n std::regex e (\"(sub)(.*)\");\n\n if (std::regex_match (s,e))\n std::cout << \"string object matched\\n\";\n\n if ( std::regex_match ( s.begin(), s.end(), e ) )\n std::cout << \"range matched\\n\";\n\n std::cmatch cm;\n std::regex_match (cstr,cm,e);\n std::cout << \"string literal with \" << cm.size() << \" matches\\n\";\n\n std::smatch sm;\n std::regex_match (s,sm,e);\n std::cout << \"string object with \" << sm.size() << \" matches\\n\";\n\n std::regex_match ( s.cbegin(), s.cend(), sm, e);\n std::cout << \"range with \" << sm.size() << \" matches\\n\";\n\n \n std::regex_match ( cstr, cm, e, std::regex_constants::match_default );\n\n std::cout << \"the matches were: \";\n for (unsigned i=0; i<sm.size(); ++i) {\n std::cout << \"[\" << sm[i] << \"] \";\n }\n\n std::cout << std::endl;\n\n return 0;\n}" }, { "code": null, "e": 5036, "s": 5003, "text": "The output should be like this −" }, { "code": null, "e": 5218, "s": 5036, "text": "string literal matched\nstring object matched\nrange matched\nstring literal with 3 matches\nstring object with 3 matches\nrange with 3 matches\nthe matches were: [subject] [sub] [ject] \n" }, { "code": null, "e": 5225, "s": 5218, "text": " Print" }, { "code": null, "e": 5236, "s": 5225, "text": " Add Notes" } ]
Demystifying Customer behavior with Market Basket analysis | by Shubham Goyal | Towards Data Science
In this blog, we are going to see how we can Anticipate customer behavior with Market Basket analysis By using Association rules. Market Basket Analysis is one of the key techniques used by large retailers to uncover associations between items. It works by looking for combinations of items that occur together frequently in transactions. To put it another way, it allows retailers to identify relationships between the items that people buy. The approach is based on the theory that customers who buy a certain item are more likely to buy another specific item ). For example, People who buy Bread usually buy Butter too. The Marketing teams at retail stores should target customers who buy bread and butter and provide an offer to them so that they buy the third item, like eggs. So if customers buy bread and butter and see a discount or an offer on eggs, they will be encouraged to spend more and buy the eggs. This is what market basket analysis is all about. This is just a small example. So, if you take 10000 or 20000 items data of your Supermart to a Data Scientist, Just imagine the number of insights you can get. And that is why Association Rule mining is so important. Market basket analysis can also be used to cross-sell products. Amazon famously uses an algorithm to suggest items that you might be interested in, based on your browsing history or what other people have purchased. A well known urban legend is that a supermarket, in the wake of running a business sector bushel examination, found that men were probably going to purchase brew and diapers together. Deals expanded deals by putting lager alongside the diapers. It sounds straightforward (and much of the time, it is). Be that as it may, entanglements to know about: For huge inventories (for example more than 10,000), the mix of things may detonate into the billions, making the math practically outlandish. Information is regularly mined from enormous exchange chronicles. A lot of information is normally taken care of by particular measurable programming Association Rule Mining basically used when we have to find an association between objects in a given set or to find some hidden pattern in any piece of Information. Market Basket Analysis or Basket Data Analysis in retailing or clustering are some applications of Association Rule Mining. The most widely Used way to deal with these examples is Market Basket Analysis. This is a key system utilized by many big companies in the retail sector like Amazon, Flipkart, and so forth to break down users of purchasing behavior by identifying the relationship between the various things that users place in their “shopping containers”. The revelation of these affiliations can assist retailers with creating advertising procedures by picking up knowledge into which things are as often as possible acquired together by clients. The methodologies may include: Changing the store layout according to trends Cross marketing on online stores What are the trending items customers buy Customized emails with add-on sales Customer behavior analysis Catalog design Note: There is a lot of confusion in everyone’s mind regarding the similarity between Market Basket Analysis and Recommendation Systems As already discussed, the Association rules do not work on an individual’s preference. It always finds the relation between some sets of elements of every transaction. This makes them totally different than recommendation system method called Collaborating filtering. If you want to learn about the recommendation system, you can go through my previous blog Recommendation Engines. To understand it better take a look at below snapshot from amazon.com. You notice 2 headings “Frequently Bought Together” and the “Customers who bought this item also bought” on each product’s info page. Frequently Bought Together → Association Customers who bought this item also bought → Recommendation So this was the difference between association rules and recommendations. Now, let’s talk about one of the main association Machine learning algorithms. ie. Apriori Algorithm Let assume that we have a transaction containing a set {Banana, Pineapple, mango} also contain another set {Banana, Mango}. So, according to the principle of Apriori, if {Banana, Pineapple, Mango} is frequent, then {Banana, Mango} must also be frequent. We have a dataset which is consist of some transactions. 0 -> absence of an item 1-> Presence of an item In order to find out interesting rules out of multiple possible rules from this small business scenario, we will be using the following matrices: Support: Support is the popularity(frequency of occurrence) of an item. It can be calculated by a number of transactions containing the item to the total number of transactions. So, if we want to calculate the support for the banana, here it is: Support(Banana) = (Transactions involving Grapes)/(Total transaction) Support(Banana) = 0.666 Confidence: Likelihood of occurrence of item B if item A occurs(Conditional Probability). Confidence(A => B) = (Transactions involving both A and B)/(Transactions involving only A) Confidence({Banana, Pineapple} => {Mango}) = Support(Banana, Pineapple, Mango)/Support(banana, Pineapple) = 2/6 / 3/6 = 0.667 Lift: Increase in the ratio of occurence of item B if item A occurs. Lift(A => B) = Confidence(A, B) / Support(B) Lift ({Banana, Pineapple} => {Mango}) = 1 So, likelihood of a customer buying both A and B together is ‘lift-value’ times more than the chance if purchasing alone. Lift (A=> B) = 1 means that there is no correlation within the item set. Lift (A => B) > 1 means that there is a positive correlation within the itemset, i.e., products in the itemset, A, and B, are more likely to be bought together. Lift (A => B) < 1 means that there is a negative correlation within the itemset, i.e., products in itemset, A, and B, are unlikely to be bought together. You can get the data from here. This dataset containing transaction data of a store with various products. Install apyori package before importing the library conda install --yes apyoriORpip3 install --yes apyori import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom apyori import apriori we have imported all the necessary libraries: NumPy and pandas for basic operations Matplotlib for data visualization apyori for our data modeling store_data = pd.read_csv("store_data.csv",header = None) we have read the dataset using pandas into a data frame with the name “store_data”. Now let’s see the data store_data.head() So, this is our data looks like, it contains all the transaction history of various products. store_data.shape 7501 indicates the total number of transactions with different items bought together. 20 indicates the number of columns to display items Since the Apriori library requires our dataset to be in the form of a list of lists. So the whole dataset is a big list and each transaction in the dataset is an inner list within the outer big list. [ [transaction1], [transaction2], . . [transaction7501] ] Let’s Convert our pandas’ data frame into a list of lists as follows: records = []for i in range(0,7501): records.append([str(store_data.values[i,j]) for j in range(0,20)]) Let’s see these transaction sets: for sets in records: print(sets) Parameters of apriori: records: list of lists min_support: probability value to select the items with support values greater than the value specified by the parameter min_confidence: probability value to filter rules with greater confidence than the specified threshold min_lift: minimum lift value to shortlist the list of rules min_length: minimum number of items you want in your rules association_rules = apriori(records, min_support = 0.0055, min_confidence = .3, min_lift = 3, min_length = 2) Convert above rules into a list of rules: association_results = list(association_rules) Now let’s see how many rules had been generated by our algorithm: print(len(association_results)) So, In total, we have 18 rules and those have support, confidence and lift higher than what we expect. Let’s see some of the rules print(association_results[5]) we can see that rule 5 contains (spaghetti, ground beef, frozen vegetables) which have a good association between them. for item in association_results: pair = item[0] items = [x for x in pair] print("Rule :"+ str(items[0]) + "->" + str(items[1])) print("Support : {}".format(item[1])) print("Confidence : {}".format(item[2][0][2])) print("List : {}".format(item[2][0][3])) print("\n-------------------------------------------------\n") So, this was all about how to implement the apriori algorithm to find associativity in our set of transactions. Stay Tunes, happy learning 🙂 Originally posted on Knoldus Blogs: https://blog.knoldus.com/machinex-demystifying-market-basket-analysis/ Follow MachineX Intelligence for more: LinkedIn Twitter Overview of Traditional Machine Learning Techniques edureka apriori Algorithm
[ { "code": null, "e": 301, "s": 171, "text": "In this blog, we are going to see how we can Anticipate customer behavior with Market Basket analysis By using Association rules." }, { "code": null, "e": 614, "s": 301, "text": "Market Basket Analysis is one of the key techniques used by large retailers to uncover associations between items. It works by looking for combinations of items that occur together frequently in transactions. To put it another way, it allows retailers to identify relationships between the items that people buy." }, { "code": null, "e": 736, "s": 614, "text": "The approach is based on the theory that customers who buy a certain item are more likely to buy another specific item )." }, { "code": null, "e": 953, "s": 736, "text": "For example, People who buy Bread usually buy Butter too. The Marketing teams at retail stores should target customers who buy bread and butter and provide an offer to them so that they buy the third item, like eggs." }, { "code": null, "e": 1136, "s": 953, "text": "So if customers buy bread and butter and see a discount or an offer on eggs, they will be encouraged to spend more and buy the eggs. This is what market basket analysis is all about." }, { "code": null, "e": 1353, "s": 1136, "text": "This is just a small example. So, if you take 10000 or 20000 items data of your Supermart to a Data Scientist, Just imagine the number of insights you can get. And that is why Association Rule mining is so important." }, { "code": null, "e": 1569, "s": 1353, "text": "Market basket analysis can also be used to cross-sell products. Amazon famously uses an algorithm to suggest items that you might be interested in, based on your browsing history or what other people have purchased." }, { "code": null, "e": 1814, "s": 1569, "text": "A well known urban legend is that a supermarket, in the wake of running a business sector bushel examination, found that men were probably going to purchase brew and diapers together. Deals expanded deals by putting lager alongside the diapers." }, { "code": null, "e": 1919, "s": 1814, "text": "It sounds straightforward (and much of the time, it is). Be that as it may, entanglements to know about:" }, { "code": null, "e": 2062, "s": 1919, "text": "For huge inventories (for example more than 10,000), the mix of things may detonate into the billions, making the math practically outlandish." }, { "code": null, "e": 2212, "s": 2062, "text": "Information is regularly mined from enormous exchange chronicles. A lot of information is normally taken care of by particular measurable programming" }, { "code": null, "e": 2378, "s": 2212, "text": "Association Rule Mining basically used when we have to find an association between objects in a given set or to find some hidden pattern in any piece of Information." }, { "code": null, "e": 2502, "s": 2378, "text": "Market Basket Analysis or Basket Data Analysis in retailing or clustering are some applications of Association Rule Mining." }, { "code": null, "e": 3065, "s": 2502, "text": "The most widely Used way to deal with these examples is Market Basket Analysis. This is a key system utilized by many big companies in the retail sector like Amazon, Flipkart, and so forth to break down users of purchasing behavior by identifying the relationship between the various things that users place in their “shopping containers”. The revelation of these affiliations can assist retailers with creating advertising procedures by picking up knowledge into which things are as often as possible acquired together by clients. The methodologies may include:" }, { "code": null, "e": 3111, "s": 3065, "text": "Changing the store layout according to trends" }, { "code": null, "e": 3144, "s": 3111, "text": "Cross marketing on online stores" }, { "code": null, "e": 3186, "s": 3144, "text": "What are the trending items customers buy" }, { "code": null, "e": 3222, "s": 3186, "text": "Customized emails with add-on sales" }, { "code": null, "e": 3249, "s": 3222, "text": "Customer behavior analysis" }, { "code": null, "e": 3264, "s": 3249, "text": "Catalog design" }, { "code": null, "e": 3400, "s": 3264, "text": "Note: There is a lot of confusion in everyone’s mind regarding the similarity between Market Basket Analysis and Recommendation Systems" }, { "code": null, "e": 3668, "s": 3400, "text": "As already discussed, the Association rules do not work on an individual’s preference. It always finds the relation between some sets of elements of every transaction. This makes them totally different than recommendation system method called Collaborating filtering." }, { "code": null, "e": 3782, "s": 3668, "text": "If you want to learn about the recommendation system, you can go through my previous blog Recommendation Engines." }, { "code": null, "e": 3986, "s": 3782, "text": "To understand it better take a look at below snapshot from amazon.com. You notice 2 headings “Frequently Bought Together” and the “Customers who bought this item also bought” on each product’s info page." }, { "code": null, "e": 4087, "s": 3986, "text": "Frequently Bought Together → Association Customers who bought this item also bought → Recommendation" }, { "code": null, "e": 4161, "s": 4087, "text": "So this was the difference between association rules and recommendations." }, { "code": null, "e": 4262, "s": 4161, "text": "Now, let’s talk about one of the main association Machine learning algorithms. ie. Apriori Algorithm" }, { "code": null, "e": 4516, "s": 4262, "text": "Let assume that we have a transaction containing a set {Banana, Pineapple, mango} also contain another set {Banana, Mango}. So, according to the principle of Apriori, if {Banana, Pineapple, Mango} is frequent, then {Banana, Mango} must also be frequent." }, { "code": null, "e": 4573, "s": 4516, "text": "We have a dataset which is consist of some transactions." }, { "code": null, "e": 4597, "s": 4573, "text": "0 -> absence of an item" }, { "code": null, "e": 4621, "s": 4597, "text": "1-> Presence of an item" }, { "code": null, "e": 4767, "s": 4621, "text": "In order to find out interesting rules out of multiple possible rules from this small business scenario, we will be using the following matrices:" }, { "code": null, "e": 5013, "s": 4767, "text": "Support: Support is the popularity(frequency of occurrence) of an item. It can be calculated by a number of transactions containing the item to the total number of transactions. So, if we want to calculate the support for the banana, here it is:" }, { "code": null, "e": 5083, "s": 5013, "text": "Support(Banana) = (Transactions involving Grapes)/(Total transaction)" }, { "code": null, "e": 5107, "s": 5083, "text": "Support(Banana) = 0.666" }, { "code": null, "e": 5197, "s": 5107, "text": "Confidence: Likelihood of occurrence of item B if item A occurs(Conditional Probability)." }, { "code": null, "e": 5288, "s": 5197, "text": "Confidence(A => B) = (Transactions involving both A and B)/(Transactions involving only A)" }, { "code": null, "e": 5394, "s": 5288, "text": "Confidence({Banana, Pineapple} => {Mango}) = Support(Banana, Pineapple, Mango)/Support(banana, Pineapple)" }, { "code": null, "e": 5406, "s": 5394, "text": "= 2/6 / 3/6" }, { "code": null, "e": 5414, "s": 5406, "text": "= 0.667" }, { "code": null, "e": 5483, "s": 5414, "text": "Lift: Increase in the ratio of occurence of item B if item A occurs." }, { "code": null, "e": 5528, "s": 5483, "text": "Lift(A => B) = Confidence(A, B) / Support(B)" }, { "code": null, "e": 5570, "s": 5528, "text": "Lift ({Banana, Pineapple} => {Mango}) = 1" }, { "code": null, "e": 5692, "s": 5570, "text": "So, likelihood of a customer buying both A and B together is ‘lift-value’ times more than the chance if purchasing alone." }, { "code": null, "e": 5765, "s": 5692, "text": "Lift (A=> B) = 1 means that there is no correlation within the item set." }, { "code": null, "e": 5926, "s": 5765, "text": "Lift (A => B) > 1 means that there is a positive correlation within the itemset, i.e., products in the itemset, A, and B, are more likely to be bought together." }, { "code": null, "e": 6080, "s": 5926, "text": "Lift (A => B) < 1 means that there is a negative correlation within the itemset, i.e., products in itemset, A, and B, are unlikely to be bought together." }, { "code": null, "e": 6112, "s": 6080, "text": "You can get the data from here." }, { "code": null, "e": 6187, "s": 6112, "text": "This dataset containing transaction data of a store with various products." }, { "code": null, "e": 6239, "s": 6187, "text": "Install apyori package before importing the library" }, { "code": null, "e": 6293, "s": 6239, "text": "conda install --yes apyoriORpip3 install --yes apyori" }, { "code": null, "e": 6388, "s": 6293, "text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltfrom apyori import apriori" }, { "code": null, "e": 6434, "s": 6388, "text": "we have imported all the necessary libraries:" }, { "code": null, "e": 6472, "s": 6434, "text": "NumPy and pandas for basic operations" }, { "code": null, "e": 6506, "s": 6472, "text": "Matplotlib for data visualization" }, { "code": null, "e": 6535, "s": 6506, "text": "apyori for our data modeling" }, { "code": null, "e": 6592, "s": 6535, "text": "store_data = pd.read_csv(\"store_data.csv\",header = None)" }, { "code": null, "e": 6699, "s": 6592, "text": "we have read the dataset using pandas into a data frame with the name “store_data”. Now let’s see the data" }, { "code": null, "e": 6717, "s": 6699, "text": "store_data.head()" }, { "code": null, "e": 6811, "s": 6717, "text": "So, this is our data looks like, it contains all the transaction history of various products." }, { "code": null, "e": 6828, "s": 6811, "text": "store_data.shape" }, { "code": null, "e": 6966, "s": 6828, "text": "7501 indicates the total number of transactions with different items bought together. 20 indicates the number of columns to display items" }, { "code": null, "e": 7224, "s": 6966, "text": "Since the Apriori library requires our dataset to be in the form of a list of lists. So the whole dataset is a big list and each transaction in the dataset is an inner list within the outer big list. [ [transaction1], [transaction2], . . [transaction7501] ]" }, { "code": null, "e": 7294, "s": 7224, "text": "Let’s Convert our pandas’ data frame into a list of lists as follows:" }, { "code": null, "e": 7400, "s": 7294, "text": "records = []for i in range(0,7501): records.append([str(store_data.values[i,j]) for j in range(0,20)])" }, { "code": null, "e": 7434, "s": 7400, "text": "Let’s see these transaction sets:" }, { "code": null, "e": 7470, "s": 7434, "text": "for sets in records: print(sets)" }, { "code": null, "e": 7493, "s": 7470, "text": "Parameters of apriori:" }, { "code": null, "e": 7516, "s": 7493, "text": "records: list of lists" }, { "code": null, "e": 7637, "s": 7516, "text": "min_support: probability value to select the items with support values greater than the value specified by the parameter" }, { "code": null, "e": 7740, "s": 7637, "text": "min_confidence: probability value to filter rules with greater confidence than the specified threshold" }, { "code": null, "e": 7800, "s": 7740, "text": "min_lift: minimum lift value to shortlist the list of rules" }, { "code": null, "e": 7859, "s": 7800, "text": "min_length: minimum number of items you want in your rules" }, { "code": null, "e": 7969, "s": 7859, "text": "association_rules = apriori(records, min_support = 0.0055, min_confidence = .3, min_lift = 3, min_length = 2)" }, { "code": null, "e": 8011, "s": 7969, "text": "Convert above rules into a list of rules:" }, { "code": null, "e": 8057, "s": 8011, "text": "association_results = list(association_rules)" }, { "code": null, "e": 8123, "s": 8057, "text": "Now let’s see how many rules had been generated by our algorithm:" }, { "code": null, "e": 8155, "s": 8123, "text": "print(len(association_results))" }, { "code": null, "e": 8286, "s": 8155, "text": "So, In total, we have 18 rules and those have support, confidence and lift higher than what we expect. Let’s see some of the rules" }, { "code": null, "e": 8316, "s": 8286, "text": "print(association_results[5])" }, { "code": null, "e": 8436, "s": 8316, "text": "we can see that rule 5 contains (spaghetti, ground beef, frozen vegetables) which have a good association between them." }, { "code": null, "e": 8774, "s": 8436, "text": "for item in association_results: pair = item[0] items = [x for x in pair] print(\"Rule :\"+ str(items[0]) + \"->\" + str(items[1])) print(\"Support : {}\".format(item[1])) print(\"Confidence : {}\".format(item[2][0][2])) print(\"List : {}\".format(item[2][0][3])) print(\"\\n-------------------------------------------------\\n\")" }, { "code": null, "e": 8886, "s": 8774, "text": "So, this was all about how to implement the apriori algorithm to find associativity in our set of transactions." }, { "code": null, "e": 8915, "s": 8886, "text": "Stay Tunes, happy learning 🙂" }, { "code": null, "e": 9022, "s": 8915, "text": "Originally posted on Knoldus Blogs: https://blog.knoldus.com/machinex-demystifying-market-basket-analysis/" }, { "code": null, "e": 9061, "s": 9022, "text": "Follow MachineX Intelligence for more:" }, { "code": null, "e": 9070, "s": 9061, "text": "LinkedIn" }, { "code": null, "e": 9078, "s": 9070, "text": "Twitter" }, { "code": null, "e": 9130, "s": 9078, "text": "Overview of Traditional Machine Learning Techniques" } ]
Framework7 - Start App With Login Screen
You can create the login screen on applicaton's first screen by using the modal-in class. The following example demonstrates the use of start app with login screen in the Framework7 − <!DOCTYPE html> <html> <head> <meta name = "viewport" content = "width = device-width, initial-scale = 1, maximum-scale = 1, minimum-scale = 1, user-scalable = no, minimal-ui" /> <meta name = "apple-mobile-web-app-capable" content = "yes" /> <meta name = "apple-mobile-web-app-status-bar-style" content = "black" /> <title>Start App With Login Screen</title> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.min.css" /> <link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.colors.min.css" /> </head> <body> <div class = "views"> <div class = "view view-main"> <div class = "navbar"> <div class = "navbar-inner"> <div class = "center sliding">Start App With Login Screen</div> </div> </div> <div class = "pages"> <div data-page = "index" class = "page navbar-fixed"> <div class = "page-content"> <div class = "content-block"> <p><a href = "#" class = "open-login-screen">Click here to open Login Screen</a></p> </div> </div> </div> </div> </div> </div> <div class = "login-screen modal-in"> <div class = "view"> <div class = "page"> <div class = "page-content login-screen-content"> <div class = "login-screen-title">Login Here</div> <form> <div class = "list-block"> <ul> <li class = "item-content"> <div class = "item-inner"> <div class = "item-title label">Username</div> <div class = "item-input"> <input type = "text" name = "username" placeholder = "Enter the username"> </div> </div> </li> <li class = "item-content"> <div class = "item-inner"> <div class = "item-title label">Password</div> <div class = "item-input"> <input type = "password" name = "password" placeholder = "Enter the password"> </div> </div> </li> </ul> </div> <div class = "list-block"> <ul> <li><a href = "#" class = "item-link list-button">Log In</a></li> </ul> <div class = "list-block-label"> <p><a href = "#" class = "close-login-screen">Click here to close Login Screen</a></p> </div> </div> </form> </div> </div> </div> </div> <script type = "text/javascript" src = "https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/js/framework7.min.js"></script> <script> // Here you can initialize the app var myApp = new Framework7(); // If your using custom DOM library, then save it to $$ variable var $$ = Dom7; // Add the view var mainView = myApp.addView('.view-main', { // enable the dynamic navbar for this view: dynamicNavbar: true }); $$('.login-screen .list-button').on('click', function () { var uname = $$('.login-screen input[name = "username"]').val(); var pwd = $$('.login-screen input[name = "password"]').val(); myApp.alert('Username: ' + uname + ', Password: ' + pwd, function () { myApp.closeModal('.login-screen'); }); }); </script> </body> </html> Let us carry out the following steps to see how the above given code works − Save the above given HTML code as login_screen_start_app.html file in your server root folder. Save the above given HTML code as login_screen_start_app.html file in your server root folder. Open this HTML file as http://localhost/login_screen_start_app.html and the output is displayed as shown below. Open this HTML file as http://localhost/login_screen_start_app.html and the output is displayed as shown below. When you enter username, password and click on the “Log in” link, the login wizard is displayed with the entered username and password. When you enter username, password and click on the “Log in” link, the login wizard is displayed with the entered username and password. You can close the login screen by clicking on the Close login link. You can close the login screen by clicking on the Close login link. Click here to open Login Screen Username Password Log In Click here to close Login Screen 7 Lectures 1 hours Anadi Sharma 22 Lectures 6 hours Malhar Lathkar 102 Lectures 8 hours Karthikeya T 19 Lectures 5 hours Trevoir Williams 20 Lectures 1 hours John Elder 13 Lectures 3 hours Darwish Print Add Notes Bookmark this page
[ { "code": null, "e": 2741, "s": 2651, "text": "You can create the login screen on applicaton's first screen by using the modal-in class." }, { "code": null, "e": 2835, "s": 2741, "text": "The following example demonstrates the use of start app with login screen in the Framework7 −" }, { "code": null, "e": 7257, "s": 2835, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1, \n maximum-scale = 1, minimum-scale = 1, user-scalable = no, minimal-ui\" />\n <meta name = \"apple-mobile-web-app-capable\" content = \"yes\" />\n <meta name = \"apple-mobile-web-app-status-bar-style\" content = \"black\" />\n <title>Start App With Login Screen</title>\n <link rel = \"stylesheet\" \n href = \"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.min.css\" />\n <link rel = \"stylesheet\" \n href = \"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/css/framework7.ios.colors.min.css\" />\n </head>\n\n <body>\n <div class = \"views\">\n <div class = \"view view-main\">\n \n <div class = \"navbar\">\n <div class = \"navbar-inner\">\n <div class = \"center sliding\">Start App With Login Screen</div>\n </div>\n </div>\n \n <div class = \"pages\">\n <div data-page = \"index\" class = \"page navbar-fixed\">\n <div class = \"page-content\">\n <div class = \"content-block\">\n <p><a href = \"#\" class = \"open-login-screen\">Click here to open Login Screen</a></p>\n </div>\n </div>\n </div>\n </div>\n \n </div>\n </div>\n \n <div class = \"login-screen modal-in\">\n <div class = \"view\">\n <div class = \"page\">\n <div class = \"page-content login-screen-content\">\n <div class = \"login-screen-title\">Login Here</div>\n \n <form>\n <div class = \"list-block\">\n <ul>\n <li class = \"item-content\">\n <div class = \"item-inner\">\n <div class = \"item-title label\">Username</div>\n <div class = \"item-input\">\n <input type = \"text\" name = \"username\" placeholder = \"Enter the username\">\n </div>\n </div>\n </li>\n \n <li class = \"item-content\">\n <div class = \"item-inner\">\n <div class = \"item-title label\">Password</div>\n <div class = \"item-input\">\n <input type = \"password\" name = \"password\" placeholder = \"Enter the password\">\n </div>\n </div>\n </li>\n </ul>\n </div>\n \n <div class = \"list-block\">\n <ul>\n <li><a href = \"#\" class = \"item-link list-button\">Log In</a></li>\n </ul>\n \n <div class = \"list-block-label\">\n <p><a href = \"#\" class = \"close-login-screen\">Click here to close Login Screen</a></p>\n </div>\n </div>\n </form>\n \n </div>\n </div>\n </div>\n </div>\n \n <script type = \"text/javascript\" \n src = \"https://cdnjs.cloudflare.com/ajax/libs/framework7/1.4.2/js/framework7.min.js\"></script>\n \n <script>\n // Here you can initialize the app\n var myApp = new Framework7();\n\n // If your using custom DOM library, then save it to $$ variable\n var $$ = Dom7;\n\n // Add the view\n var mainView = myApp.addView('.view-main', {\n \n // enable the dynamic navbar for this view:\n dynamicNavbar: true\n });\n \n $$('.login-screen .list-button').on('click', function () {\n var uname = $$('.login-screen input[name = \"username\"]').val();\n var pwd = $$('.login-screen input[name = \"password\"]').val();\n \n myApp.alert('Username: ' + uname + ', Password: ' + pwd, function () {\n myApp.closeModal('.login-screen');\n });\n });\n </script>\n </body>\n\n</html>" }, { "code": null, "e": 7334, "s": 7257, "text": "Let us carry out the following steps to see how the above given code works −" }, { "code": null, "e": 7429, "s": 7334, "text": "Save the above given HTML code as login_screen_start_app.html file in your server root folder." }, { "code": null, "e": 7524, "s": 7429, "text": "Save the above given HTML code as login_screen_start_app.html file in your server root folder." }, { "code": null, "e": 7636, "s": 7524, "text": "Open this HTML file as http://localhost/login_screen_start_app.html and the output is displayed as shown below." }, { "code": null, "e": 7748, "s": 7636, "text": "Open this HTML file as http://localhost/login_screen_start_app.html and the output is displayed as shown below." }, { "code": null, "e": 7884, "s": 7748, "text": "When you enter username, password and click on the “Log in” link, the login wizard is displayed with the entered username and password." }, { "code": null, "e": 8020, "s": 7884, "text": "When you enter username, password and click on the “Log in” link, the login wizard is displayed with the entered username and password." }, { "code": null, "e": 8088, "s": 8020, "text": "You can close the login screen by clicking on the Close login link." }, { "code": null, "e": 8156, "s": 8088, "text": "You can close the login screen by clicking on the Close login link." }, { "code": null, "e": 8188, "s": 8156, "text": "Click here to open Login Screen" }, { "code": null, "e": 8204, "s": 8188, "text": "\n\nUsername\n\n\n\n\n" }, { "code": null, "e": 8220, "s": 8204, "text": "\n\nPassword\n\n\n\n\n" }, { "code": null, "e": 8227, "s": 8220, "text": "Log In" }, { "code": null, "e": 8260, "s": 8227, "text": "Click here to close Login Screen" }, { "code": null, "e": 8292, "s": 8260, "text": "\n 7 Lectures \n 1 hours \n" }, { "code": null, "e": 8306, "s": 8292, "text": " Anadi Sharma" }, { "code": null, "e": 8339, "s": 8306, "text": "\n 22 Lectures \n 6 hours \n" }, { "code": null, "e": 8355, "s": 8339, "text": " Malhar Lathkar" }, { "code": null, "e": 8389, "s": 8355, "text": "\n 102 Lectures \n 8 hours \n" }, { "code": null, "e": 8403, "s": 8389, "text": " Karthikeya T" }, { "code": null, "e": 8436, "s": 8403, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 8454, "s": 8436, "text": " Trevoir Williams" }, { "code": null, "e": 8487, "s": 8454, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 8499, "s": 8487, "text": " John Elder" }, { "code": null, "e": 8532, "s": 8499, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 8541, "s": 8532, "text": " Darwish" }, { "code": null, "e": 8548, "s": 8541, "text": " Print" }, { "code": null, "e": 8559, "s": 8548, "text": " Add Notes" } ]
Initialize HashMap in Java
The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets. Following is the list of constructors supported by the HashMap class. Following is an example displaying how to initialize and work with HashMap in Java − Live Demo import java.util.*; public class Demo { public static void main(String args[]) { HashMap<Integer, String> hashMap = new HashMap<Integer, String>(7); hashMap.put(1, "Laptop"); hashMap.put(2, "LCD"); hashMap.put(3, "LED"); hashMap.put(4, "Desktop"); hashMap.put(5, "Laptop"); hashMap.put(6, "Notebook"); hashMap.put(7, "Mobile"); System.out.println("HashMap = " + hashMap); } } HashMap = {1=Laptop, 2=LCD, 3=LED, 4=Desktop, 5=Laptop, 6=Notebook, 7=Mobile} Let us see another example − Live Demo import java.util.*; public class Main { public static void main(String args[]) { HashMap hashMap = new HashMap(); hashMap.put("John", new Integer(10000)); hashMap.put("Tim", new Integer(25000)); hashMap.put("Adam", new Integer(15000)); hashMap.put("Katie", new Integer(30000)); hashMap.put("Jacob", new Integer(45000)); hashMap.put("Steve", new Integer(23000)); hashMap.put("Nathan", new Integer(25000)); hashMap.put("Amy", new Integer(27000)); Set set = hashMap.entrySet(); Iterator iterator = set.iterator(); while(iterator.hasNext()) { Map.Entry map = (Map.Entry)iterator.next(); System.out.print(map.getKey() + ": "); System.out.println(map.getValue()); } System.out.println(); System.out.println("Size of IdentintyHashMap: "+hashMap.size()); int bonus = ((Integer)hashMap.get("Amy")).intValue(); hashMap.put("Amy", new Integer(bonus + 5000)); System.out.println("Amy's salary after bonus = " + hashMap.get("Amy")); int deductions = ((Integer)hashMap.get("Steve")).intValue(); hashMap.put("Steve", new Integer(deductions - 3000)); System.out.println("Steve's salary after deductions = " + hashMap.get("Steve")); } } Adam: 15000 Nathan: 25000 Katie: 30000 Steve: 23000 John: 10000 Tim: 25000 Amy: 27000 Jacob: 45000 Size of IdentintyHashMap: 8 Amy's salary after bonus = 32000 Steve's salary after deductions = 20000
[ { "code": null, "e": 1248, "s": 1062, "text": "The HashMap class uses a hashtable to implement the Map interface. This allows the execution time of basic operations, such as get( ) and put( ), to remain constant even for large sets." }, { "code": null, "e": 1318, "s": 1248, "text": "Following is the list of constructors supported by the HashMap class." }, { "code": null, "e": 1403, "s": 1318, "text": "Following is an example displaying how to initialize and work with HashMap in Java −" }, { "code": null, "e": 1414, "s": 1403, "text": " Live Demo" }, { "code": null, "e": 1850, "s": 1414, "text": "import java.util.*;\npublic class Demo {\n public static void main(String args[]) {\n HashMap<Integer, String> hashMap = new HashMap<Integer, String>(7);\n hashMap.put(1, \"Laptop\");\n hashMap.put(2, \"LCD\");\n hashMap.put(3, \"LED\");\n hashMap.put(4, \"Desktop\");\n hashMap.put(5, \"Laptop\");\n hashMap.put(6, \"Notebook\");\n hashMap.put(7, \"Mobile\");\n System.out.println(\"HashMap = \" + hashMap);\n }\n}" }, { "code": null, "e": 1928, "s": 1850, "text": "HashMap = {1=Laptop, 2=LCD, 3=LED, 4=Desktop, 5=Laptop, 6=Notebook, 7=Mobile}" }, { "code": null, "e": 1957, "s": 1928, "text": "Let us see another example −" }, { "code": null, "e": 1968, "s": 1957, "text": " Live Demo" }, { "code": null, "e": 3247, "s": 1968, "text": "import java.util.*;\npublic class Main {\n public static void main(String args[]) {\n HashMap hashMap = new HashMap();\n hashMap.put(\"John\", new Integer(10000));\n hashMap.put(\"Tim\", new Integer(25000));\n hashMap.put(\"Adam\", new Integer(15000));\n hashMap.put(\"Katie\", new Integer(30000));\n hashMap.put(\"Jacob\", new Integer(45000));\n hashMap.put(\"Steve\", new Integer(23000));\n hashMap.put(\"Nathan\", new Integer(25000));\n hashMap.put(\"Amy\", new Integer(27000));\n Set set = hashMap.entrySet();\n Iterator iterator = set.iterator();\n while(iterator.hasNext()) {\n Map.Entry map = (Map.Entry)iterator.next();\n System.out.print(map.getKey() + \": \");\n System.out.println(map.getValue());\n }\n System.out.println();\n System.out.println(\"Size of IdentintyHashMap: \"+hashMap.size());\n int bonus = ((Integer)hashMap.get(\"Amy\")).intValue();\n hashMap.put(\"Amy\", new Integer(bonus + 5000));\n System.out.println(\"Amy's salary after bonus = \" + hashMap.get(\"Amy\"));\n int deductions = ((Integer)hashMap.get(\"Steve\")).intValue();\n hashMap.put(\"Steve\", new Integer(deductions - 3000));\n System.out.println(\"Steve's salary after deductions = \" + hashMap.get(\"Steve\"));\n }\n}" }, { "code": null, "e": 3447, "s": 3247, "text": "Adam: 15000\nNathan: 25000\nKatie: 30000\nSteve: 23000\nJohn: 10000\nTim: 25000\nAmy: 27000\nJacob: 45000\nSize of IdentintyHashMap: 8\nAmy's salary after bonus = 32000\nSteve's salary after deductions = 20000" } ]
Unix / Linux Shell - The if...elif...fi statement
The if...elif...fi statement is the one level advance form of control statement that allows Shell to make correct decision out of several conditions. if [ expression 1 ] then Statement(s) to be executed if expression 1 is true elif [ expression 2 ] then Statement(s) to be executed if expression 2 is true elif [ expression 3 ] then Statement(s) to be executed if expression 3 is true else Statement(s) to be executed if no expression is true fi This code is just a series of if statements, where each if is part of the else clause of the previous statement. Here statement(s) are executed based on the true condition, if none of the condition is true then else block is executed. #!/bin/sh a=10 b=20 if [ $a == $b ] then echo "a is equal to b" elif [ $a -gt $b ] then echo "a is greater than b" elif [ $a -lt $b ] then echo "a is less than b" else echo "None of the condition met" fi Upon execution, you will receive the following result − a is less than b 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2897, "s": 2747, "text": "The if...elif...fi statement is the one level advance form of control statement that allows Shell to make correct decision out of several conditions." }, { "code": null, "e": 3206, "s": 2897, "text": "if [ expression 1 ]\nthen\n Statement(s) to be executed if expression 1 is true\nelif [ expression 2 ]\nthen\n Statement(s) to be executed if expression 2 is true\nelif [ expression 3 ]\nthen\n Statement(s) to be executed if expression 3 is true\nelse\n Statement(s) to be executed if no expression is true\nfi\n" }, { "code": null, "e": 3441, "s": 3206, "text": "This code is just a series of if statements, where each if is part of the else clause of the previous statement. Here statement(s) are executed based on the true condition, if none of the condition is true then else block is executed." }, { "code": null, "e": 3659, "s": 3441, "text": "#!/bin/sh\n\na=10\nb=20\n\nif [ $a == $b ]\nthen\n echo \"a is equal to b\"\nelif [ $a -gt $b ]\nthen\n echo \"a is greater than b\"\nelif [ $a -lt $b ]\nthen\n echo \"a is less than b\"\nelse\n echo \"None of the condition met\"\nfi" }, { "code": null, "e": 3715, "s": 3659, "text": "Upon execution, you will receive the following result −" }, { "code": null, "e": 3733, "s": 3715, "text": "a is less than b\n" }, { "code": null, "e": 3768, "s": 3733, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 3796, "s": 3768, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3830, "s": 3796, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3847, "s": 3830, "text": " Frahaan Hussain" }, { "code": null, "e": 3880, "s": 3847, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 3891, "s": 3880, "text": " Pradeep D" }, { "code": null, "e": 3926, "s": 3891, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3942, "s": 3926, "text": " Musab Zayadneh" }, { "code": null, "e": 3975, "s": 3942, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 3987, "s": 3975, "text": " GUHARAJANM" }, { "code": null, "e": 4019, "s": 3987, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 4027, "s": 4019, "text": " Uplatz" }, { "code": null, "e": 4034, "s": 4027, "text": " Print" }, { "code": null, "e": 4045, "s": 4034, "text": " Add Notes" } ]
Alternate positive and negative numbers | Practice | GeeksforGeeks
Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of alternate positive and negative numbers without changing the relative order of positive and negative numbers. Note: Array should start with positive number. Example 1: Input: N = 9 Arr[] = {9, 4, -2, -1, 5, 0, -5, -3, 2} Output: 9 -2 4 -1 5 -5 0 -3 2 Example 2: Input: N = 10 Arr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8} Output: 5 -5 2 -2 4 -8 7 1 8 0 Your Task: You don't need to read input or print anything. Your task is to complete the function rearrange() which takes the array of integers arr[] and n as parameters. You need to modify the array itself. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N ≤ 107 -106 ≤ Arr[i] ≤ 107 0 loveyvishnanics198 hours ago void rearrange(int arr[], int n) { // code here ArrayList<Integer> pos = new ArrayList<Integer>(); ArrayList<Integer> neg = new ArrayList<Integer>(); int i; for(i=0; i<n; i++){ if(arr[i]>=0){ pos.add(arr[i]); } } for( i=0; i<n; i++){ if(arr[i]<0){ neg.add(arr[i]); } } for(i=0; i<n; i++){ if(!pos.isEmpty() && i%2==0){ arr[i] = pos.get(0); pos.remove(0); } else if(!neg.isEmpty() && i%2!=0 ){ arr[i] = neg.get(0); neg.remove(0); } else if(pos.isEmpty() || neg.isEmpty()){ break; } } while(!pos.isEmpty()){ arr[i++] = pos.get(0); pos.remove(0); } while(!neg.isEmpty() ){ arr[i++] = neg.get(0); neg.remove(0); } } +2 sidvas582 days ago void rearrange(int a[], int n) { int j=0,k=0,b[n],c[n]; for(int i=0;i<n;i++) { if(a[i]>=0) b[j++]=a[i]; else c[k++]=a[i]; } int p=0,q=0,i=0; while(p<j&&q<k) { a[i++]=b[p++]; a[i++]=c[q++]; } if(p<j) { while(p<j) a[i++]=b[p++]; } if(q<k) { while(q<k) a[i++]=c[q++]; }} 0 rajat8213 days ago class Solution { void rearrange(int arr[], int n) { ArrayList<Integer> pos = new ArrayList<>(); ArrayList<Integer> neg = new ArrayList<>(); for(int i=0 ; i<n ; i++) { if(arr[i]<0) neg.add(arr[i]); else pos.add(arr[i]); } for(int i=0 ; i<n ; i++) { if(pos.isEmpty()){ arr[i]=neg.get(0); neg.remove(0); } else if(neg.isEmpty()){ arr[i] = pos.get(0); pos.remove(0); } else{ if(i%2==0) { arr[i] = pos.get(0); pos.remove(0); } else{ arr[i] = neg.get(0); neg.remove(0); } } } }} 0 ayckerayush3 days ago check this out vector<int>ans1,ans2; for(int i=0;i<n;i++){ if(arr[i]<0) ans1.push_back(arr[i]); else ans2.push_back(arr[i]); } int i=0; for(;i<2*min(ans1.size() , ans2.size());i++){ if(i%2 == 0){ arr[i]=ans2[i/2]; } else arr[i]=ans1[i/2]; } int j=i; i/=2; if(ans1.size() > ans2.size()){ for(;j<n;){ arr[j++]=ans1[i++]; } } else if(ans1.size() < ans2.size()){ for(;j<n;){ arr[j++]=ans2[i++]; } } 0 krishnan8radha5 days ago void rearrange(int arr[], int n) { ArrayList<Integer> positive = new ArrayList<>(); ArrayList<Integer> negative = new ArrayList<>(); for(int i=0;i<n;i++) { if(arr[i]>=0) { positive.add(arr[i]); } else { negative.add(arr[i]); } } for(int j=0,m=0;j<n;j=j+2,m++) { arr[j]=positive.get(m); } for(int k=1,l=0;k<n;k=k+2,l++) { arr[k]=negative.get(l); } } 0 niravramotiya0032 weeks ago class Solution: def rearrange(self,arr, n): t=0 p=[] n=[] for i in arr: if i>=0: p.append(i) else: n.append(i) arr.clear() if len(p)>len(n): while t<len(p): arr.append(p[t]) if t<len(n): arr.append(n[t]) t+=1 elif len(n)>len(p): while t<len(n): if t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 else: while t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 0 niravramotiya0032 weeks ago class Solution: def rearrange(self,arr, n): # code here t=0 p=[] n=[] for i in arr: if i>=0: p.append(i) else: n.append(i) arr.clear() if len(p)>len(n): while t<len(p): arr.append(p[t]) if t<len(n): arr.append(n[t]) t+=1 elif len(n)>len(p): while t<len(n): if t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 else: while t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 0 niravramotiya0032 weeks ago #Python solution #time 1.8 class Solution: def rearrange(self,arr, n): # code here t=0 p=[] n=[] for i in arr: if i>=0: p.append(i) else: n.append(i) arr.clear() if len(p)>len(n): while t<len(p): arr.append(p[t]) if t<len(n): arr.append(n[t]) t+=1 elif len(n)>len(p): while t<len(n): if t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 else: while t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 +1 sameerhakeentc20192 weeks ago class Solution{public: int next_positive(int arr[],int position,int n) { for(int i=position+1;i<n;i++) { if(arr[i]>=0) return i; } return n; } int next_negative(int arr[],int position,int n) { for(int i=position+1;i<n;i++) { if(arr[i]<0) return i; } return n; } void rearrange(int arr[], int n) { // code here int positive=0; int negative=0; bool flag1=true,flag2=false; for(int i=0;i<n;i++) { if(arr[i]>0) { positive=i; break; } } for(int i=0;i<n;i++) { if(arr[i]<0) { negative=i; break; } } while(positive<n and negative<n) { if(arr[positive] >= 0 and flag1) { cout<<arr[positive]<<" "; positive=next_positive(arr,positive,n); flag1=false; flag2=true; continue; } if( arr[negative]<0 and flag2 ) { cout<<arr[negative]<<" "; negative=next_negative(arr,negative,n); flag1=true; flag2=false; } } if(negative==n) { for(int i=positive;i<n;i++) { if(arr[i]>0) cout<<arr[i]<<" "; } } if(positive==n) { for(int i=negative;i<n;i++) { if(arr[i]>0) cout<<arr[i]<<" "; } }}}; +1 krushnaoza2 weeks ago Space Complexity: O(1) ; Time Complexity: O(n^2) public void rotateright(int[] A, int i, int j){ int tmp = A[j]; for(int k=j; k>i; k--){ A[k] = A[k-1]; } A[i]=tmp; } void rearrange(int A[], int n) { for(int i=0; i<n; i++){ if((i&1)==1 && A[i]>=0){ int j=i+1; while(j<n && A[j]>=0) j++; if(j==n) break; rotateright(A,i,j); } else if(i%2==0 && A[i]<0) { int j=i+1; while(j<n && A[j]<0) j++; if(j==n) break; rotateright(A,i,j); } } } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 496, "s": 238, "text": "Given an unsorted array Arr of N positive and negative numbers. Your task is to create an array of alternate positive and negative numbers without changing the relative order of positive and negative numbers.\nNote: Array should start with positive number.\n " }, { "code": null, "e": 507, "s": 496, "text": "Example 1:" }, { "code": null, "e": 592, "s": 507, "text": "Input: \nN = 9\nArr[] = {9, 4, -2, -1, 5, 0, -5, -3, 2}\nOutput:\n9 -2 4 -1 5 -5 0 -3 2\n" }, { "code": null, "e": 603, "s": 592, "text": "Example 2:" }, { "code": null, "e": 694, "s": 603, "text": "Input: \nN = 10\nArr[] = {-5, -2, 5, 2, 4, 7, 1, 8, 0, -8}\nOutput:\n5 -5 2 -2 4 -8 7 1 8 0 \n\n" }, { "code": null, "e": 969, "s": 694, "text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function rearrange() which takes the array of integers arr[] and n as parameters. You need to modify the array itself.\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)\n " }, { "code": null, "e": 1014, "s": 969, "text": "Constraints:\n1 ≤ N ≤ 107\n-106 ≤ Arr[i] ≤ 107" }, { "code": null, "e": 1016, "s": 1014, "text": "0" }, { "code": null, "e": 1045, "s": 1016, "text": "loveyvishnanics198 hours ago" }, { "code": null, "e": 2001, "s": 1045, "text": "void rearrange(int arr[], int n) { // code here ArrayList<Integer> pos = new ArrayList<Integer>(); ArrayList<Integer> neg = new ArrayList<Integer>(); int i; for(i=0; i<n; i++){ if(arr[i]>=0){ pos.add(arr[i]); } } for( i=0; i<n; i++){ if(arr[i]<0){ neg.add(arr[i]); } } for(i=0; i<n; i++){ if(!pos.isEmpty() && i%2==0){ arr[i] = pos.get(0); pos.remove(0); } else if(!neg.isEmpty() && i%2!=0 ){ arr[i] = neg.get(0); neg.remove(0); } else if(pos.isEmpty() || neg.isEmpty()){ break; } } while(!pos.isEmpty()){ arr[i++] = pos.get(0); pos.remove(0); } while(!neg.isEmpty() ){ arr[i++] = neg.get(0); neg.remove(0); } }" }, { "code": null, "e": 2004, "s": 2001, "text": "+2" }, { "code": null, "e": 2023, "s": 2004, "text": "sidvas582 days ago" }, { "code": null, "e": 2403, "s": 2023, "text": "void rearrange(int a[], int n) { int j=0,k=0,b[n],c[n]; for(int i=0;i<n;i++) { if(a[i]>=0) b[j++]=a[i]; else c[k++]=a[i]; } int p=0,q=0,i=0; while(p<j&&q<k) { a[i++]=b[p++]; a[i++]=c[q++]; } if(p<j) { while(p<j) a[i++]=b[p++]; } if(q<k) { while(q<k) a[i++]=c[q++]; }}" }, { "code": null, "e": 2405, "s": 2403, "text": "0" }, { "code": null, "e": 2424, "s": 2405, "text": "rajat8213 days ago" }, { "code": null, "e": 2478, "s": 2424, "text": "class Solution { void rearrange(int arr[], int n) {" }, { "code": null, "e": 3232, "s": 2478, "text": " ArrayList<Integer> pos = new ArrayList<>(); ArrayList<Integer> neg = new ArrayList<>(); for(int i=0 ; i<n ; i++) { if(arr[i]<0) neg.add(arr[i]); else pos.add(arr[i]); } for(int i=0 ; i<n ; i++) { if(pos.isEmpty()){ arr[i]=neg.get(0); neg.remove(0); } else if(neg.isEmpty()){ arr[i] = pos.get(0); pos.remove(0); } else{ if(i%2==0) { arr[i] = pos.get(0); pos.remove(0); } else{ arr[i] = neg.get(0); neg.remove(0); } } } }}" }, { "code": null, "e": 3234, "s": 3232, "text": "0" }, { "code": null, "e": 3256, "s": 3234, "text": "ayckerayush3 days ago" }, { "code": null, "e": 3271, "s": 3256, "text": "check this out" }, { "code": null, "e": 3854, "s": 3271, "text": " vector<int>ans1,ans2;\n\t for(int i=0;i<n;i++){\n\t if(arr[i]<0)\n\t ans1.push_back(arr[i]);\n\t else\n\t ans2.push_back(arr[i]);\n\t }\n\t int i=0;\n\t for(;i<2*min(ans1.size() , ans2.size());i++){\n\t if(i%2 == 0){\n\t arr[i]=ans2[i/2];\n\t }\n\t else\n\t arr[i]=ans1[i/2];\n\t }\n\t int j=i;\n\t i/=2;\n\t if(ans1.size() > ans2.size()){\n\t for(;j<n;){\n\t arr[j++]=ans1[i++];\n\t }\n\t }\n\t else if(ans1.size() < ans2.size()){\n\t for(;j<n;){\n\t arr[j++]=ans2[i++];\n\t }\n\t }" }, { "code": null, "e": 3856, "s": 3854, "text": "0" }, { "code": null, "e": 3881, "s": 3856, "text": "krishnan8radha5 days ago" }, { "code": null, "e": 4374, "s": 3881, "text": "void rearrange(int arr[], int n) {\n ArrayList<Integer> positive = new ArrayList<>();\n ArrayList<Integer> negative = new ArrayList<>();\n for(int i=0;i<n;i++) {\n \tif(arr[i]>=0) {\n \t\tpositive.add(arr[i]);\n \t}\n \telse {\n \t\tnegative.add(arr[i]);\n \t}\n }\n for(int j=0,m=0;j<n;j=j+2,m++) {\n \t\tarr[j]=positive.get(m);\n }\n for(int k=1,l=0;k<n;k=k+2,l++) {\n \t\tarr[k]=negative.get(l);\n }\n }" }, { "code": null, "e": 4376, "s": 4374, "text": "0" }, { "code": null, "e": 4404, "s": 4376, "text": "niravramotiya0032 weeks ago" }, { "code": null, "e": 5052, "s": 4404, "text": "class Solution: def rearrange(self,arr, n): t=0 p=[] n=[] for i in arr: if i>=0: p.append(i) else: n.append(i) arr.clear() if len(p)>len(n): while t<len(p): arr.append(p[t]) if t<len(n): arr.append(n[t]) t+=1 elif len(n)>len(p): while t<len(n): if t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 else: while t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1" }, { "code": null, "e": 5054, "s": 5052, "text": "0" }, { "code": null, "e": 5082, "s": 5054, "text": "niravramotiya0032 weeks ago" }, { "code": null, "e": 5748, "s": 5082, "text": "class Solution: def rearrange(self,arr, n): # code here t=0 p=[] n=[] for i in arr: if i>=0: p.append(i) else: n.append(i) arr.clear() if len(p)>len(n): while t<len(p): arr.append(p[t]) if t<len(n): arr.append(n[t]) t+=1 elif len(n)>len(p): while t<len(n): if t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 else: while t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1" }, { "code": null, "e": 5750, "s": 5748, "text": "0" }, { "code": null, "e": 5778, "s": 5750, "text": "niravramotiya0032 weeks ago" }, { "code": null, "e": 5796, "s": 5778, "text": "#Python solution " }, { "code": null, "e": 5806, "s": 5796, "text": "#time 1.8" }, { "code": null, "e": 6472, "s": 5806, "text": "class Solution: def rearrange(self,arr, n): # code here t=0 p=[] n=[] for i in arr: if i>=0: p.append(i) else: n.append(i) arr.clear() if len(p)>len(n): while t<len(p): arr.append(p[t]) if t<len(n): arr.append(n[t]) t+=1 elif len(n)>len(p): while t<len(n): if t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1 else: while t<len(p): arr.append(p[t]) arr.append(n[t]) t+=1" }, { "code": null, "e": 6475, "s": 6472, "text": "+1" }, { "code": null, "e": 6505, "s": 6475, "text": "sameerhakeentc20192 weeks ago" }, { "code": null, "e": 6528, "s": 6505, "text": "class Solution{public:" }, { "code": null, "e": 7974, "s": 6528, "text": "int next_positive(int arr[],int position,int n) { for(int i=position+1;i<n;i++) { if(arr[i]>=0) return i; } return n; } int next_negative(int arr[],int position,int n) { for(int i=position+1;i<n;i++) { if(arr[i]<0) return i; } return n; } void rearrange(int arr[], int n) { // code here int positive=0; int negative=0; bool flag1=true,flag2=false; for(int i=0;i<n;i++) { if(arr[i]>0) { positive=i; break; } } for(int i=0;i<n;i++) { if(arr[i]<0) { negative=i; break; } } while(positive<n and negative<n) { if(arr[positive] >= 0 and flag1) { cout<<arr[positive]<<\" \"; positive=next_positive(arr,positive,n); flag1=false; flag2=true; continue; } if( arr[negative]<0 and flag2 ) { cout<<arr[negative]<<\" \"; negative=next_negative(arr,negative,n); flag1=true; flag2=false; } } if(negative==n) { for(int i=positive;i<n;i++) { if(arr[i]>0) cout<<arr[i]<<\" \"; } } if(positive==n) { for(int i=negative;i<n;i++) { if(arr[i]>0) cout<<arr[i]<<\" \"; } }}}; " }, { "code": null, "e": 7977, "s": 7974, "text": "+1" }, { "code": null, "e": 7999, "s": 7977, "text": "krushnaoza2 weeks ago" }, { "code": null, "e": 8048, "s": 7999, "text": "Space Complexity: O(1) ; Time Complexity: O(n^2)" }, { "code": null, "e": 8703, "s": 8048, "text": "\n public void rotateright(int[] A, int i, int j){\n int tmp = A[j];\n for(int k=j; k>i; k--){\n A[k] = A[k-1];\n }\n A[i]=tmp;\n }\n void rearrange(int A[], int n) {\n for(int i=0; i<n; i++){\n if((i&1)==1 && A[i]>=0){\n int j=i+1;\n while(j<n && A[j]>=0) j++;\n\n if(j==n) break;\n\n rotateright(A,i,j);\n \n } else if(i%2==0 && A[i]<0) {\n int j=i+1;\n while(j<n && A[j]<0) j++;\n\n if(j==n) break;\n rotateright(A,i,j);\n \n }\n }\n }" }, { "code": null, "e": 8851, "s": 8705, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8887, "s": 8851, "text": " Login to access your submissions. " }, { "code": null, "e": 8897, "s": 8887, "text": "\nProblem\n" }, { "code": null, "e": 8907, "s": 8897, "text": "\nContest\n" }, { "code": null, "e": 8970, "s": 8907, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9118, "s": 8970, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 9326, "s": 9118, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 9432, "s": 9326, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
SAP Scripts - Print Program
In SAP Scripts, Print Program is used to print the actual form and get the data from database tables, choosing a form and print the text elements in a defined format. It retrieves the data from the database and combines it with the user input, formats the data and prints it. All print programs and forms are stored in table TNAPR. Different functional modules are used in Print Program. To start a print program, OPEN_FORM functional module is used, and to end the program CLOSE_FORM functional module is used. OPEN_FORM − In Print Program, this function should be called first before any printing can take place. You specify the name of the form and the print language. CALL FUNCTION 'OPEN_FORM' START_FORM − This function is called to use different forms with similar characteristics in a single request. CALL FUNCTION ’START_FORM’ WRITE_FORM − This function is used to write text in a window in the form using text elements. CALL FUNCTION ‘WRITE_FORM’ CONTROL_FORM − This function is used to insert SAP Script control commands in an ABAP program. CALL FUNCTION ‘CONTROL_FORM’ END_FORM − This function is called in the end and it has no exporting parameters. CALL FUNCTION ‘END_FORM’ CLOSE_FORM − To view the standard form and the standard Print program, run Transaction Code: NACE Enter Application Types and click the Output Type at the top. In the following screenshot, you can see the Application name for the selected service. Following is a sample print program that creates an invoice with company-related information such as customer data, date, flight booking, etc. TABLES: zcustom, zbook, zpfli. DATA: bookings like zbook... select * from... /In this section, you are reading the data from tables in database./ CALL FUNCTION 'OPEN_FORM' EXPORTING DEVICE = 'PRINTER' FORM = 'EXAMPLE1' DIALOG = 'X' OPTIONS = EXCEPTIONS CANCELLED = 1 DEVICE = 2 FORM = 3 OTHERS = 11 /In this section, you are calling OPEN_FORM function module to initialize print output./ In the above function module, the parameter − FORM shows the name of the form. FORM shows the name of the form. DEVICE can be PRINTER (print using spool), TELEFAX (fax output) or a SCREEN (output to screen) DEVICE can be PRINTER (print using spool), TELEFAX (fax output) or a SCREEN (output to screen) OPTIONS shows a structure of type ITCPO to control the various attributes - Print preview, number of copies. OPTIONS shows a structure of type ITCPO to control the various attributes - Print preview, number of copies. CALL FUNCTION 'WRITE_FORM' EXPORTING ELEMENT = 'textelement’ TYPE = 'TOP' WINDOW = 'MAIN' FUNCTION = 'SET' ... /In this section, you use WRITE_FORM function to output general text elements and column heading/ ELEMENT function module shows the ‘textelement’ to be printed and ‘WINDOW’ shows which window of the form to be printed. ELEMENT function module shows the ‘textelement’ to be printed and ‘WINDOW’ shows which window of the form to be printed. TYPE shows the output area of the window like- TOP, BOTTOM, or BODY. TYPE shows the output area of the window like- TOP, BOTTOM, or BODY. FUNCTION tells the text to be replaced, added or appended. FUNCTION tells the text to be replaced, added or appended. LOOP AT bookings WHERE CALL FUNCTION 'WRITE_FORM' EXPORTING ELEMENT = 'BOOKING' TYPE = 'BODY' WINDOW = 'MAIN' ... ENDLOOP /In this section, text element BOOKING is used to output the bookings of a customer from the loop from BOOKING table in database./ CALL FUNCTION 'CLOSE_FORM' IMPORTING * RESULT = EXCEPTIONS UNOPENED = 1 OTHERS = 5 /To end the Print Program/ You call this function module in the end and it has no exporting parameter. 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2799, "s": 2523, "text": "In SAP Scripts, Print Program is used to print the actual form and get the data from database tables, choosing a form and print the text elements in a defined format. It retrieves the data from the database and combines it with the user input, formats the data and prints it." }, { "code": null, "e": 2855, "s": 2799, "text": "All print programs and forms are stored in table TNAPR." }, { "code": null, "e": 3035, "s": 2855, "text": "Different functional modules are used in Print Program. To start a print program, OPEN_FORM functional module is used, and to end the program CLOSE_FORM functional module is used." }, { "code": null, "e": 3195, "s": 3035, "text": "OPEN_FORM − In Print Program, this function should be called first before any printing can take place. You specify the name of the form and the print language." }, { "code": null, "e": 3223, "s": 3195, "text": "CALL FUNCTION 'OPEN_FORM' \n" }, { "code": null, "e": 3333, "s": 3223, "text": "START_FORM − This function is called to use different forms with similar characteristics in a single request." }, { "code": null, "e": 3361, "s": 3333, "text": "CALL FUNCTION ’START_FORM’\n" }, { "code": null, "e": 3455, "s": 3361, "text": "WRITE_FORM − This function is used to write text in a window in the form using text elements." }, { "code": null, "e": 3483, "s": 3455, "text": "CALL FUNCTION ‘WRITE_FORM’\n" }, { "code": null, "e": 3578, "s": 3483, "text": "CONTROL_FORM − This function is used to insert SAP Script control commands in an ABAP program." }, { "code": null, "e": 3608, "s": 3578, "text": "CALL FUNCTION ‘CONTROL_FORM’\n" }, { "code": null, "e": 3690, "s": 3608, "text": "END_FORM − This function is called in the end and it has no exporting parameters." }, { "code": null, "e": 3717, "s": 3690, "text": "CALL FUNCTION ‘END_FORM’ \n" }, { "code": null, "e": 3815, "s": 3717, "text": "CLOSE_FORM − To view the standard form and the standard Print program, run Transaction Code: NACE" }, { "code": null, "e": 3877, "s": 3815, "text": "Enter Application Types and click the Output Type at the top." }, { "code": null, "e": 3965, "s": 3877, "text": "In the following screenshot, you can see the Application name for the selected service." }, { "code": null, "e": 4108, "s": 3965, "text": "Following is a sample print program that creates an invoice with company-related information such as customer data, date, flight booking, etc." }, { "code": null, "e": 4259, "s": 4108, "text": "TABLES: zcustom, zbook, zpfli. \nDATA: bookings like zbook... \nselect * from... \n/In this section, you are reading the data from tables in database./ " }, { "code": null, "e": 4550, "s": 4259, "text": "CALL FUNCTION 'OPEN_FORM' \nEXPORTING \nDEVICE = 'PRINTER' \nFORM = 'EXAMPLE1' \nDIALOG = 'X' \nOPTIONS = \nEXCEPTIONS \nCANCELLED = 1 \nDEVICE = 2 \nFORM = 3 \nOTHERS = 11 \n/In this section, you are calling OPEN_FORM function module to initialize print output./" }, { "code": null, "e": 4596, "s": 4550, "text": "In the above function module, the parameter −" }, { "code": null, "e": 4629, "s": 4596, "text": "FORM shows the name of the form." }, { "code": null, "e": 4662, "s": 4629, "text": "FORM shows the name of the form." }, { "code": null, "e": 4757, "s": 4662, "text": "DEVICE can be PRINTER (print using spool), TELEFAX (fax output) or a SCREEN (output to screen)" }, { "code": null, "e": 4852, "s": 4757, "text": "DEVICE can be PRINTER (print using spool), TELEFAX (fax output) or a SCREEN (output to screen)" }, { "code": null, "e": 4961, "s": 4852, "text": "OPTIONS shows a structure of type ITCPO to control the various attributes - Print preview, number of copies." }, { "code": null, "e": 5070, "s": 4961, "text": "OPTIONS shows a structure of type ITCPO to control the various attributes - Print preview, number of copies." }, { "code": null, "e": 5295, "s": 5070, "text": "CALL FUNCTION 'WRITE_FORM' \nEXPORTING \nELEMENT = 'textelement’ \nTYPE = 'TOP' \nWINDOW = 'MAIN' \nFUNCTION = 'SET' \n... \n/In this section, you use WRITE_FORM function to output general text elements and column \nheading/" }, { "code": null, "e": 5416, "s": 5295, "text": "ELEMENT function module shows the ‘textelement’ to be printed and ‘WINDOW’ shows which window of the form to be printed." }, { "code": null, "e": 5537, "s": 5416, "text": "ELEMENT function module shows the ‘textelement’ to be printed and ‘WINDOW’ shows which window of the form to be printed." }, { "code": null, "e": 5606, "s": 5537, "text": "TYPE shows the output area of the window like- TOP, BOTTOM, or BODY." }, { "code": null, "e": 5675, "s": 5606, "text": "TYPE shows the output area of the window like- TOP, BOTTOM, or BODY." }, { "code": null, "e": 5734, "s": 5675, "text": "FUNCTION tells the text to be replaced, added or appended." }, { "code": null, "e": 5793, "s": 5734, "text": "FUNCTION tells the text to be replaced, added or appended." }, { "code": null, "e": 6069, "s": 5793, "text": "LOOP AT bookings WHERE \nCALL FUNCTION 'WRITE_FORM' \nEXPORTING \nELEMENT = 'BOOKING' \nTYPE = 'BODY' \nWINDOW = 'MAIN' \n... \nENDLOOP \n/In this section, text element BOOKING is used to output the bookings of a customer from\nthe loop from BOOKING table in database./" }, { "code": null, "e": 6198, "s": 6069, "text": "CALL FUNCTION 'CLOSE_FORM' \nIMPORTING \n* RESULT = \nEXCEPTIONS \nUNOPENED = 1 \nOTHERS = 5 \n/To end the Print Program/ " }, { "code": null, "e": 6274, "s": 6198, "text": "You call this function module in the end and it has no exporting parameter." }, { "code": null, "e": 6307, "s": 6274, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 6321, "s": 6307, "text": " Sanjo Thomas" }, { "code": null, "e": 6354, "s": 6321, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 6366, "s": 6354, "text": " Neha Gupta" }, { "code": null, "e": 6401, "s": 6366, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6416, "s": 6401, "text": " Sumit Agarwal" }, { "code": null, "e": 6449, "s": 6416, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6464, "s": 6449, "text": " Sumit Agarwal" }, { "code": null, "e": 6499, "s": 6464, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6511, "s": 6499, "text": " Neha Malik" }, { "code": null, "e": 6546, "s": 6511, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6558, "s": 6546, "text": " Neha Malik" }, { "code": null, "e": 6565, "s": 6558, "text": " Print" }, { "code": null, "e": 6576, "s": 6565, "text": " Add Notes" } ]
JavaScript - Array length Property
JavaScript array length property returns an unsigned, 32-bit integer that specifies the number of elements in an array. Its syntax is as follows − array.length Returns the length of the array. Try the following example. <html> <head> <title>JavaScript Array length Property</title> </head> <body> <script type = "text/javascript"> var arr = new Array( 10, 20, 30 ); document.write("arr.length is : " + arr.length); </script> </body> </html> arr.length is : 3 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2586, "s": 2466, "text": "JavaScript array length property returns an unsigned, 32-bit integer that specifies the number of elements in an array." }, { "code": null, "e": 2613, "s": 2586, "text": "Its syntax is as follows −" }, { "code": null, "e": 2627, "s": 2613, "text": "array.length\n" }, { "code": null, "e": 2660, "s": 2627, "text": "Returns the length of the array." }, { "code": null, "e": 2687, "s": 2660, "text": "Try the following example." }, { "code": null, "e": 2970, "s": 2687, "text": "<html>\n <head>\n <title>JavaScript Array length Property</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var arr = new Array( 10, 20, 30 );\n document.write(\"arr.length is : \" + arr.length); \n </script> \n </body>\n</html>" }, { "code": null, "e": 2990, "s": 2970, "text": "arr.length is : 3 \n" }, { "code": null, "e": 3025, "s": 2990, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3039, "s": 3025, "text": " Anadi Sharma" }, { "code": null, "e": 3073, "s": 3039, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 3087, "s": 3073, "text": " Lets Kode It" }, { "code": null, "e": 3122, "s": 3087, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3139, "s": 3122, "text": " Frahaan Hussain" }, { "code": null, "e": 3174, "s": 3139, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3191, "s": 3174, "text": " Frahaan Hussain" }, { "code": null, "e": 3224, "s": 3191, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 3252, "s": 3224, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3286, "s": 3252, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 3314, "s": 3286, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3321, "s": 3314, "text": " Print" }, { "code": null, "e": 3332, "s": 3321, "text": " Add Notes" } ]
Program to print a inverse pyramid character pattern - GeeksforGeeks
09 Apr, 2021 Given a positive integer n, print the inverse pyramid pattern upto n rows as shown in the examples.Examples : Input : 4 Output : A B C D D C B A A B C C B A A B B A A A Input : 6 Output : A B C D E F F E D C B A A B C D E E D C B A A B C D D C B A A B C C B A A B B A A A Below is the implementation for the pattern: C++ Java Python3 C# PHP Javascript // C++ code to print inverse// pyramid pattern#include <bits/stdc++.h>using namespace std; // function to print the// inverse pyramid patternvoid pyramid(int n){ int i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { cout<<" "; cout<<" "; } // initializing value corresponding // to 'A' ASCII value num = 'A'; // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { cout << (char) num++ <<" "; } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { cout << (char) --num <<" "; } cout<<"\n"; }} // Driver functionint main(){ int n = 9; pyramid(n); return 0;} // Java code for Inverse Pyramidimport java.util.*; class GFG { // function for inverse pyramid print static void pyramid(int n) { int i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { System.out.print(" "); System.out.print(" "); } // initializing value corresponding // to ASCII value of 'A' num = 'A'; // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { System.out.print((char)num++ + " "); } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { System.out.print((char)--num + " "); } System.out.println(""); } } /* Driver program to test above function */ public static void main(String[] args) { int n = 9; pyramid(n); }} // This article is contributed by Gitanjali. # Python3 code to print inverse# pyramid pattern # function to print the following# inverse pyramid patterndef pyramid( n ): # outer loop to handle number # of rows n in this case for i in range(n, 0, -1): # inner loop to create right triangle # gaps on left side of pyramid for gap in range(n-1, i-1, -1): print(" ", end = '') print(" ", end = '') # initializing value corresponding # to 'A' ASCII value num = ord('A') # loop to print characters on # left side of pyramid for j in range(1, i+1): print(chr(num), end = ' ') num += 1 # loop to print characters on # right side of pyramid for j in range(i - 1, -1, -1): num -= 1 print(chr(num), end = ' ') print("\n", end = '') # Driver Coden = 9pyramid(n) # This code is contributed by "Sharad_Bhardwaj". //C# code for Inverse Pyramidusing System; class GFG { // function for inverse pyramid print static void pyramid(int n) { int i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { Console.Write(" "); Console.Write(" "); } // initializing value corresponding // to ASCII value of 'A' num = 'A'; // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { Console.Write((char)num++ + " "); } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { Console.Write((char)--num + " "); } Console.WriteLine(""); } } /* Driver program to test above function */ public static void Main() { int n = 9; pyramid(n); }} // This article is contributed by vt_m. <?php// PHP implementation to print// inverse pyramid pattern // function to print the// inverse pyramid patternfunction pyramid($n){ // outer loop to handle number // of rows n in this case for ($i = $n; $i >= 1; $i--) { // inner loop to create // right triangle gaps on // left side of pyramid for ($gap = $n - 1; $gap >= $i; $gap--) { echo" "; } // initializing value corresponding // to 'A' ASCII value is 65 $num = 65; // loop to print characters on // left side of pyramid for ($j = 1; $j <= $i; $j++) { echo chr($num++)." "; } // loop to print characters on // right side of pyramid for ($j = $i - 1; $j >= 0; $j--) { echo chr(--$num)." "; } echo"\n"; }} // Driver Code$n = 9;pyramid($n); // This code is contributed by mits?> <script> // JavaScript code to print inverse // pyramid pattern // function to print the // inverse pyramid pattern function pyramid(n) { var i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { document.write(" "); } // initializing value corresponding // to 'A' ASCII value num = "A".charCodeAt(0); // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { document.write(String.fromCharCode(num++) + " "); } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { document.write(String.fromCharCode(--num) + " "); } document.write("<br>"); } } // Driver function var n = 9; pyramid(n); </script> Output : A B C D E F G H I I H G F E D C B A A B C D E F G H H G F E D C B A A B C D E F G G F E D C B A A B C D E F F E D C B A A B C D E E D C B A A B C D D C B A A B C C B A A B B A A A Mithun Kumar rdtank pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Ternary Operator in Python Inline Functions in C++ Difference between Abstract Class and Interface in Java Destructors in C++ Pure Virtual Functions and Abstract Classes in C++ Python Exception Handling Exception Handling in C++ Taking input from console in Python
[ { "code": null, "e": 24232, "s": 24204, "text": "\n09 Apr, 2021" }, { "code": null, "e": 24344, "s": 24232, "text": "Given a positive integer n, print the inverse pyramid pattern upto n rows as shown in the examples.Examples : " }, { "code": null, "e": 24558, "s": 24344, "text": "Input : 4\nOutput :\n\nA B C D D C B A\n A B C C B A\n A B B A\n A A\n \nInput : 6\nOutput :\n\n A B C D E F F E D C B A\n A B C D E E D C B A\n A B C D D C B A\n A B C C B A\n A B B A\n A A" }, { "code": null, "e": 24607, "s": 24560, "text": "Below is the implementation for the pattern: " }, { "code": null, "e": 24611, "s": 24607, "text": "C++" }, { "code": null, "e": 24616, "s": 24611, "text": "Java" }, { "code": null, "e": 24624, "s": 24616, "text": "Python3" }, { "code": null, "e": 24627, "s": 24624, "text": "C#" }, { "code": null, "e": 24631, "s": 24627, "text": "PHP" }, { "code": null, "e": 24642, "s": 24631, "text": "Javascript" }, { "code": "// C++ code to print inverse// pyramid pattern#include <bits/stdc++.h>using namespace std; // function to print the// inverse pyramid patternvoid pyramid(int n){ int i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { cout<<\" \"; cout<<\" \"; } // initializing value corresponding // to 'A' ASCII value num = 'A'; // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { cout << (char) num++ <<\" \"; } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { cout << (char) --num <<\" \"; } cout<<\"\\n\"; }} // Driver functionint main(){ int n = 9; pyramid(n); return 0;}", "e": 25626, "s": 24642, "text": null }, { "code": "// Java code for Inverse Pyramidimport java.util.*; class GFG { // function for inverse pyramid print static void pyramid(int n) { int i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { System.out.print(\" \"); System.out.print(\" \"); } // initializing value corresponding // to ASCII value of 'A' num = 'A'; // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { System.out.print((char)num++ + \" \"); } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { System.out.print((char)--num + \" \"); } System.out.println(\"\"); } } /* Driver program to test above function */ public static void main(String[] args) { int n = 9; pyramid(n); }} // This article is contributed by Gitanjali.", "e": 26906, "s": 25626, "text": null }, { "code": "# Python3 code to print inverse# pyramid pattern # function to print the following# inverse pyramid patterndef pyramid( n ): # outer loop to handle number # of rows n in this case for i in range(n, 0, -1): # inner loop to create right triangle # gaps on left side of pyramid for gap in range(n-1, i-1, -1): print(\" \", end = '') print(\" \", end = '') # initializing value corresponding # to 'A' ASCII value num = ord('A') # loop to print characters on # left side of pyramid for j in range(1, i+1): print(chr(num), end = ' ') num += 1 # loop to print characters on # right side of pyramid for j in range(i - 1, -1, -1): num -= 1 print(chr(num), end = ' ') print(\"\\n\", end = '') # Driver Coden = 9pyramid(n) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 27880, "s": 26906, "text": null }, { "code": "//C# code for Inverse Pyramidusing System; class GFG { // function for inverse pyramid print static void pyramid(int n) { int i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { Console.Write(\" \"); Console.Write(\" \"); } // initializing value corresponding // to ASCII value of 'A' num = 'A'; // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { Console.Write((char)num++ + \" \"); } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { Console.Write((char)--num + \" \"); } Console.WriteLine(\"\"); } } /* Driver program to test above function */ public static void Main() { int n = 9; pyramid(n); }} // This article is contributed by vt_m.", "e": 29118, "s": 27880, "text": null }, { "code": "<?php// PHP implementation to print// inverse pyramid pattern // function to print the// inverse pyramid patternfunction pyramid($n){ // outer loop to handle number // of rows n in this case for ($i = $n; $i >= 1; $i--) { // inner loop to create // right triangle gaps on // left side of pyramid for ($gap = $n - 1; $gap >= $i; $gap--) { echo\" \"; } // initializing value corresponding // to 'A' ASCII value is 65 $num = 65; // loop to print characters on // left side of pyramid for ($j = 1; $j <= $i; $j++) { echo chr($num++).\" \"; } // loop to print characters on // right side of pyramid for ($j = $i - 1; $j >= 0; $j--) { echo chr(--$num).\" \"; } echo\"\\n\"; }} // Driver Code$n = 9;pyramid($n); // This code is contributed by mits?>", "e": 30096, "s": 29118, "text": null }, { "code": "<script> // JavaScript code to print inverse // pyramid pattern // function to print the // inverse pyramid pattern function pyramid(n) { var i, j, num, gap; // outer loop to handle number // of rows n in this case for (i = n; i >= 1; i--) { // inner loop to create right triangle // gaps on left side of pyramid for (gap = n - 1; gap >= i; gap--) { document.write(\" \"); } // initializing value corresponding // to 'A' ASCII value num = \"A\".charCodeAt(0); // loop to print characters on // left side of pyramid for (j = 1; j <= i; j++) { document.write(String.fromCharCode(num++) + \" \"); } // loop to print characters on // right side of pyramid for (j = i - 1; j >= 0; j--) { document.write(String.fromCharCode(--num) + \" \"); } document.write(\"<br>\"); } } // Driver function var n = 9; pyramid(n); </script>", "e": 31207, "s": 30096, "text": null }, { "code": null, "e": 31217, "s": 31207, "text": "Output : " }, { "code": null, "e": 31478, "s": 31217, "text": " A B C D E F G H I I H G F E D C B A\n A B C D E F G H H G F E D C B A\n A B C D E F G G F E D C B A\n A B C D E F F E D C B A\n A B C D E E D C B A\n A B C D D C B A\n A B C C B A\n A B B A\n A A" }, { "code": null, "e": 31493, "s": 31480, "text": "Mithun Kumar" }, { "code": null, "e": 31500, "s": 31493, "text": "rdtank" }, { "code": null, "e": 31517, "s": 31500, "text": "pattern-printing" }, { "code": null, "e": 31536, "s": 31517, "text": "School Programming" }, { "code": null, "e": 31553, "s": 31536, "text": "pattern-printing" }, { "code": null, "e": 31651, "s": 31553, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31672, "s": 31651, "text": "Constructors in Java" }, { "code": null, "e": 31691, "s": 31672, "text": "Exceptions in Java" }, { "code": null, "e": 31718, "s": 31691, "text": "Ternary Operator in Python" }, { "code": null, "e": 31742, "s": 31718, "text": "Inline Functions in C++" }, { "code": null, "e": 31798, "s": 31742, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 31817, "s": 31798, "text": "Destructors in C++" }, { "code": null, "e": 31868, "s": 31817, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 31894, "s": 31868, "text": "Python Exception Handling" }, { "code": null, "e": 31920, "s": 31894, "text": "Exception Handling in C++" } ]
Box Office Revenue Analysis and Visualization | by Durgesh Samariya | August 2020 | Towards Data Science
Welcome back to my 100 Days of Data Science Challenge Journey. On day 4 and 5, I work on TMDB Box Office Prediction Dataset available on Kaggle. I’ll start by importing some useful libraries that we need in this task. import pandas as pd# for visualizationsimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlineplt.style.use('dark_background') Once you downloaded data from the Kaggle, you will have 3 files. As this is a prediction competition, you have train, test, and sample_submission file. For this project, my motive is only to perform data analysis and visuals. I am going to ignore test.csv and sample_submission.csv files. Let’s load train.csv in data frame using pandas. %time train = pd.read_csv('./data/tmdb-box-office-prediction/train.csv')# outputCPU times: user 258 ms, sys: 132 ms, total: 389 msWall time: 403 ms id: Integer unique id of each moviebelongs_to_collection: Contains the TMDB Id, Name, Movie Poster, and Backdrop URL of a movie in JSON format.budget: Budget of a movie in dollars. Some row contains 0 values, which mean unknown.genres: Contains all the Genres Name & TMDB Id in JSON Format.homepage: Contains the official URL of a movie.imdb_id: IMDB id of a movie (string).original_language: Two-digit code of the original language, in which the movie was made.original_title: The original title of a movie in original_language.overview: Brief description of the movie.popularity: Popularity of the movie.poster_path: Poster path of a movie. You can see full poster image by adding URL after this link → https://image.tmdb.org/t/p/original/production_companies: All production company name and TMDB id in JSON format of a movie.production_countries: Two-digit code and the full name of the production company in JSON format.release_date: The release date of a movie in mm/dd/yy format.runtime: Total runtime of a movie in minutes (Integer).spoken_languages: Two-digit code and the full name of the spoken language.status: Is the movie released or rumored?tagline: Tagline of a movietitle: English title of a movieKeywords: TMDB Id and name of all the keywords in JSON format.cast: All cast TMDB id, name, character name, gender (1 = Female, 2 = Male) in JSON formatcrew: Name, TMDB id, profile path of various kind of crew members job like Director, Writer, Art, Sound, etc.revenue: Total revenue earned by a movie in dollars. Let’s have a look at the sample data. train.head() As we can see that some features have dictionaries, hence I am dropping all such columns for now. train = train.drop(['belongs_to_collection', 'genres', 'crew','cast', 'Keywords', 'spoken_languages', 'production_companies', 'production_countries', 'tagline','overview','homepage'], axis=1) Now it time to have a look at statistics of the data. print("Shape of data is ")train.shape# OutputShape of data is(3000, 12) Dataframe information. train.info()# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 3000 entries, 0 to 2999Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 3000 non-null int64 1 budget 3000 non-null int64 2 imdb_id 3000 non-null object 3 original_language 3000 non-null object 4 original_title 3000 non-null object 5 popularity 3000 non-null float64 6 poster_path 2999 non-null object 7 release_date 3000 non-null object 8 runtime 2998 non-null float64 9 status 3000 non-null object 10 title 3000 non-null object 11 revenue 3000 non-null int64 dtypes: float64(2), int64(3), object(7)memory usage: 281.4+ KB Describe dataframe. train.describe() Let’s create new columns for release weekday, date, month, and year. train['release_date'] = pd.to_datetime(train['release_date'], infer_datetime_format=True)train['release_day'] = train['release_date'].apply(lambda t: t.day)train['release_weekday'] = train['release_date'].apply(lambda t: t.weekday())train['release_month'] = train['release_date'].apply(lambda t: t.month)train['release_year'] = train['release_date'].apply(lambda t: t.year if t.year < 2018 else t.year -100) train[train['revenue'] == train['revenue'].max()] train[['id','title','budget','revenue']].sort_values(['revenue'], ascending=False).head(10).style.background_gradient(subset='revenue', cmap='BuGn')# Please note that output has a gradient style, but in a medium, it is not possible to show. The Avengers movie has made the highest revenue. train[train['budget'] == train['budget'].max()] train[['id','title','budget', 'revenue']].sort_values(['budget'], ascending=False).head(10).style.background_gradient(subset=['budget', 'revenue'], cmap='PuBu') Pirates of the Caribbean: On Stranger Tides is most expensive movie. train[train['runtime'] == train['runtime'].max()] plt.hist(train['runtime'].fillna(0) / 60, bins=40);plt.title('Distribution of length of film in hours', fontsize=16, color='white');plt.xlabel('Duration of Movie in Hours')plt.ylabel('Number of Movies') train[['id','title','runtime', 'budget', 'revenue']].sort_values(['runtime'],ascending=False).head(10).style.background_gradient(subset=['runtime','budget','revenue'], cmap='YlGn') Carlos is the longest movie, with 338 minutes (5 hours and 38 minutes) of runtime. plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.countplot(train['release_year'].sort_values(), palette = "Dark2", edgecolor=(0,0,0))plt.title("Movie Release count by Year",fontsize=20)plt.xlabel('Release Year')plt.ylabel('Number of Movies Release')plt.xticks(fontsize=12,rotation=90)plt.show() train['release_year'].value_counts().head()# Output2013 1412015 1282010 1262016 1252012 125Name: release_year, dtype: int64 In 2013 total 141 movies were released. Most popular Movie: train[train['popularity']==train['popularity'].max()][['original_title','popularity','release_date','revenue']] Least Popular Movie: train[train['popularity']==train['popularity'].min()][['original_title','popularity','release_date','revenue']] Lets create popularity distribution plot. plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.distplot(train['popularity'], kde=False)plt.title("Movie Popularity Count",fontsize=20)plt.xlabel('Popularity')plt.ylabel('Count')plt.xticks(fontsize=12,rotation=90)plt.show() Wonder Woman movie have highest popularity of 294.33 whereas Big Time movie have lowest popularity which is 0. plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.countplot(train['release_month'].sort_values(), palette = "Dark2", edgecolor=(0,0,0))plt.title("Movie Release count by Month",fontsize=20)plt.xlabel('Release Month')plt.ylabel('Number of Movies Release')plt.xticks(fontsize=12)plt.show() train['release_month'].value_counts()# Output9 36210 30712 2638 2564 2453 2386 2372 2265 22411 2211 2127 209Name: release_month, dtype: int64 In september month most movies are relesed which is around 362. plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.countplot(train['release_day'].sort_values(), palette = "Dark2", edgecolor=(0,0,0))plt.title("Movie Release count by Day of Month",fontsize=20)plt.xlabel('Release Day')plt.ylabel('Number of Movies Release')plt.xticks(fontsize=12)plt.show() train['release_day'].value_counts().head()#Output1 15215 12612 1227 1106 107Name: release_day, dtype: int64 plt.figure(figsize=(20,12))sns.countplot(train['release_weekday'].sort_values(), palette='Dark2')loc = np.array(range(len(train['release_weekday'].unique())))day_labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']plt.xlabel('Release Day of Week')plt.ylabel('Number of Movies Release')plt.xticks(loc, day_labels, fontsize=12)plt.show() train['release_weekday'].value_counts()# Output4 13343 6092 4491 1965 1580 1356 119Name: release_weekday, dtype: int64 I hope this article was helpful to you. I tried to answer a few questions using data science. There are many more questions to ask. Now, I will move towards another dataset tomorrow. All the codes of data analysis and visuals can be found at this GitHub repository or Kaggle kernel. Thanks for reading. I appreciate any feedback. towardsdatascience.com If you like my work and want to support me, I’d greatly appreciate it if you follow me on my social media channels: The best way to support me is by following me on Medium. Subscribe to my new YouTube channel. Sign up on my email list.
[ { "code": null, "e": 317, "s": 172, "text": "Welcome back to my 100 Days of Data Science Challenge Journey. On day 4 and 5, I work on TMDB Box Office Prediction Dataset available on Kaggle." }, { "code": null, "e": 390, "s": 317, "text": "I’ll start by importing some useful libraries that we need in this task." }, { "code": null, "e": 532, "s": 390, "text": "import pandas as pd# for visualizationsimport matplotlib.pyplot as pltimport seaborn as sns%matplotlib inlineplt.style.use('dark_background')" }, { "code": null, "e": 821, "s": 532, "text": "Once you downloaded data from the Kaggle, you will have 3 files. As this is a prediction competition, you have train, test, and sample_submission file. For this project, my motive is only to perform data analysis and visuals. I am going to ignore test.csv and sample_submission.csv files." }, { "code": null, "e": 870, "s": 821, "text": "Let’s load train.csv in data frame using pandas." }, { "code": null, "e": 1018, "s": 870, "text": "%time train = pd.read_csv('./data/tmdb-box-office-prediction/train.csv')# outputCPU times: user 258 ms, sys: 132 ms, total: 389 msWall time: 403 ms" }, { "code": null, "e": 2546, "s": 1018, "text": "id: Integer unique id of each moviebelongs_to_collection: Contains the TMDB Id, Name, Movie Poster, and Backdrop URL of a movie in JSON format.budget: Budget of a movie in dollars. Some row contains 0 values, which mean unknown.genres: Contains all the Genres Name & TMDB Id in JSON Format.homepage: Contains the official URL of a movie.imdb_id: IMDB id of a movie (string).original_language: Two-digit code of the original language, in which the movie was made.original_title: The original title of a movie in original_language.overview: Brief description of the movie.popularity: Popularity of the movie.poster_path: Poster path of a movie. You can see full poster image by adding URL after this link → https://image.tmdb.org/t/p/original/production_companies: All production company name and TMDB id in JSON format of a movie.production_countries: Two-digit code and the full name of the production company in JSON format.release_date: The release date of a movie in mm/dd/yy format.runtime: Total runtime of a movie in minutes (Integer).spoken_languages: Two-digit code and the full name of the spoken language.status: Is the movie released or rumored?tagline: Tagline of a movietitle: English title of a movieKeywords: TMDB Id and name of all the keywords in JSON format.cast: All cast TMDB id, name, character name, gender (1 = Female, 2 = Male) in JSON formatcrew: Name, TMDB id, profile path of various kind of crew members job like Director, Writer, Art, Sound, etc.revenue: Total revenue earned by a movie in dollars." }, { "code": null, "e": 2584, "s": 2546, "text": "Let’s have a look at the sample data." }, { "code": null, "e": 2597, "s": 2584, "text": "train.head()" }, { "code": null, "e": 2695, "s": 2597, "text": "As we can see that some features have dictionaries, hence I am dropping all such columns for now." }, { "code": null, "e": 2887, "s": 2695, "text": "train = train.drop(['belongs_to_collection', 'genres', 'crew','cast', 'Keywords', 'spoken_languages', 'production_companies', 'production_countries', 'tagline','overview','homepage'], axis=1)" }, { "code": null, "e": 2941, "s": 2887, "text": "Now it time to have a look at statistics of the data." }, { "code": null, "e": 3013, "s": 2941, "text": "print(\"Shape of data is \")train.shape# OutputShape of data is(3000, 12)" }, { "code": null, "e": 3036, "s": 3013, "text": "Dataframe information." }, { "code": null, "e": 3881, "s": 3036, "text": "train.info()# Output<class 'pandas.core.frame.DataFrame'>RangeIndex: 3000 entries, 0 to 2999Data columns (total 12 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 id 3000 non-null int64 1 budget 3000 non-null int64 2 imdb_id 3000 non-null object 3 original_language 3000 non-null object 4 original_title 3000 non-null object 5 popularity 3000 non-null float64 6 poster_path 2999 non-null object 7 release_date 3000 non-null object 8 runtime 2998 non-null float64 9 status 3000 non-null object 10 title 3000 non-null object 11 revenue 3000 non-null int64 dtypes: float64(2), int64(3), object(7)memory usage: 281.4+ KB" }, { "code": null, "e": 3901, "s": 3881, "text": "Describe dataframe." }, { "code": null, "e": 3918, "s": 3901, "text": "train.describe()" }, { "code": null, "e": 3987, "s": 3918, "text": "Let’s create new columns for release weekday, date, month, and year." }, { "code": null, "e": 4395, "s": 3987, "text": "train['release_date'] = pd.to_datetime(train['release_date'], infer_datetime_format=True)train['release_day'] = train['release_date'].apply(lambda t: t.day)train['release_weekday'] = train['release_date'].apply(lambda t: t.weekday())train['release_month'] = train['release_date'].apply(lambda t: t.month)train['release_year'] = train['release_date'].apply(lambda t: t.year if t.year < 2018 else t.year -100)" }, { "code": null, "e": 4445, "s": 4395, "text": "train[train['revenue'] == train['revenue'].max()]" }, { "code": null, "e": 4686, "s": 4445, "text": "train[['id','title','budget','revenue']].sort_values(['revenue'], ascending=False).head(10).style.background_gradient(subset='revenue', cmap='BuGn')# Please note that output has a gradient style, but in a medium, it is not possible to show." }, { "code": null, "e": 4735, "s": 4686, "text": "The Avengers movie has made the highest revenue." }, { "code": null, "e": 4783, "s": 4735, "text": "train[train['budget'] == train['budget'].max()]" }, { "code": null, "e": 4944, "s": 4783, "text": "train[['id','title','budget', 'revenue']].sort_values(['budget'], ascending=False).head(10).style.background_gradient(subset=['budget', 'revenue'], cmap='PuBu')" }, { "code": null, "e": 5013, "s": 4944, "text": "Pirates of the Caribbean: On Stranger Tides is most expensive movie." }, { "code": null, "e": 5063, "s": 5013, "text": "train[train['runtime'] == train['runtime'].max()]" }, { "code": null, "e": 5266, "s": 5063, "text": "plt.hist(train['runtime'].fillna(0) / 60, bins=40);plt.title('Distribution of length of film in hours', fontsize=16, color='white');plt.xlabel('Duration of Movie in Hours')plt.ylabel('Number of Movies')" }, { "code": null, "e": 5447, "s": 5266, "text": "train[['id','title','runtime', 'budget', 'revenue']].sort_values(['runtime'],ascending=False).head(10).style.background_gradient(subset=['runtime','budget','revenue'], cmap='YlGn')" }, { "code": null, "e": 5530, "s": 5447, "text": "Carlos is the longest movie, with 338 minutes (5 hours and 38 minutes) of runtime." }, { "code": null, "e": 5825, "s": 5530, "text": "plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.countplot(train['release_year'].sort_values(), palette = \"Dark2\", edgecolor=(0,0,0))plt.title(\"Movie Release count by Year\",fontsize=20)plt.xlabel('Release Year')plt.ylabel('Number of Movies Release')plt.xticks(fontsize=12,rotation=90)plt.show()" }, { "code": null, "e": 5964, "s": 5825, "text": "train['release_year'].value_counts().head()# Output2013 1412015 1282010 1262016 1252012 125Name: release_year, dtype: int64" }, { "code": null, "e": 6004, "s": 5964, "text": "In 2013 total 141 movies were released." }, { "code": null, "e": 6024, "s": 6004, "text": "Most popular Movie:" }, { "code": null, "e": 6136, "s": 6024, "text": "train[train['popularity']==train['popularity'].max()][['original_title','popularity','release_date','revenue']]" }, { "code": null, "e": 6157, "s": 6136, "text": "Least Popular Movie:" }, { "code": null, "e": 6269, "s": 6157, "text": "train[train['popularity']==train['popularity'].min()][['original_title','popularity','release_date','revenue']]" }, { "code": null, "e": 6311, "s": 6269, "text": "Lets create popularity distribution plot." }, { "code": null, "e": 6536, "s": 6311, "text": "plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.distplot(train['popularity'], kde=False)plt.title(\"Movie Popularity Count\",fontsize=20)plt.xlabel('Popularity')plt.ylabel('Count')plt.xticks(fontsize=12,rotation=90)plt.show()" }, { "code": null, "e": 6647, "s": 6536, "text": "Wonder Woman movie have highest popularity of 294.33 whereas Big Time movie have lowest popularity which is 0." }, { "code": null, "e": 6933, "s": 6647, "text": "plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.countplot(train['release_month'].sort_values(), palette = \"Dark2\", edgecolor=(0,0,0))plt.title(\"Movie Release count by Month\",fontsize=20)plt.xlabel('Release Month')plt.ylabel('Number of Movies Release')plt.xticks(fontsize=12)plt.show()" }, { "code": null, "e": 7120, "s": 6933, "text": "train['release_month'].value_counts()# Output9 36210 30712 2638 2564 2453 2386 2372 2265 22411 2211 2127 209Name: release_month, dtype: int64" }, { "code": null, "e": 7184, "s": 7120, "text": "In september month most movies are relesed which is around 362." }, { "code": null, "e": 7473, "s": 7184, "text": "plt.figure(figsize=(20,12))edgecolor=(0,0,0),sns.countplot(train['release_day'].sort_values(), palette = \"Dark2\", edgecolor=(0,0,0))plt.title(\"Movie Release count by Day of Month\",fontsize=20)plt.xlabel('Release Day')plt.ylabel('Number of Movies Release')plt.xticks(fontsize=12)plt.show()" }, { "code": null, "e": 7599, "s": 7473, "text": "train['release_day'].value_counts().head()#Output1 15215 12612 1227 1106 107Name: release_day, dtype: int64" }, { "code": null, "e": 7941, "s": 7599, "text": "plt.figure(figsize=(20,12))sns.countplot(train['release_weekday'].sort_values(), palette='Dark2')loc = np.array(range(len(train['release_weekday'].unique())))day_labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']plt.xlabel('Release Day of Week')plt.ylabel('Number of Movies Release')plt.xticks(loc, day_labels, fontsize=12)plt.show()" }, { "code": null, "e": 8087, "s": 7941, "text": "train['release_weekday'].value_counts()# Output4 13343 6092 4491 1965 1580 1356 119Name: release_weekday, dtype: int64" }, { "code": null, "e": 8370, "s": 8087, "text": "I hope this article was helpful to you. I tried to answer a few questions using data science. There are many more questions to ask. Now, I will move towards another dataset tomorrow. All the codes of data analysis and visuals can be found at this GitHub repository or Kaggle kernel." }, { "code": null, "e": 8390, "s": 8370, "text": "Thanks for reading." }, { "code": null, "e": 8417, "s": 8390, "text": "I appreciate any feedback." }, { "code": null, "e": 8440, "s": 8417, "text": "towardsdatascience.com" }, { "code": null, "e": 8556, "s": 8440, "text": "If you like my work and want to support me, I’d greatly appreciate it if you follow me on my social media channels:" }, { "code": null, "e": 8613, "s": 8556, "text": "The best way to support me is by following me on Medium." }, { "code": null, "e": 8650, "s": 8613, "text": "Subscribe to my new YouTube channel." } ]
Create a pandas column using for loop - GeeksforGeeks
14 Jan, 2019 Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the data. It can be easily done by for-loop. The data of column can be taken from the existing Dataframe or any of the array. # importing librariesimport pandas as pdimport numpy as np raw_Data = {'Voter_name': ['Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5', 'Geek6', 'Geek7', 'Geek8'], 'Voter_age': [15, 23, 25, 9, 67, 54, 42, np.NaN]} df = pd.DataFrame(raw_Data, columns = ['Voter_name', 'Voter_age'])# //DataFrame will look like## Voter_name Voter_age# Geek1 15# Geek2 23# Geek3 25# Geek4 09# Geek5 67# Geek6 54# Geek7 42# Geek8 not a number eligible = [] # For each row in the columnfor age in df['Voter_age']: if age >= 18: # if Voter eligible eligible.append('Yes') elif age < 18: # if voter is not eligible eligible.append("No") else: eligible.append("Not Sure") # Create a column from the listdf['Voter'] = eligible print(df) Voter_name Voter_age Voter 0 Geek1 15 No 1 Geek2 23 Yes 2 Geek3 25 Yes 3 Geek4 9 No 4 Geek5 67 Yes 5 Geek6 54 Yes 6 Geek7 42 Yes 7 Geek8 NaN Not Sure pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas 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 ? 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 Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24292, "s": 24264, "text": "\n14 Jan, 2019" }, { "code": null, "e": 24591, "s": 24292, "text": "Let’s see how to create a column in pandas dataframe using for loop. Such operation is needed sometimes when we need to process the data of dataframe created earlier for that purpose, we need this type of computation so we can process the existing data and make a separate column to store the data." }, { "code": null, "e": 24707, "s": 24591, "text": "It can be easily done by for-loop. The data of column can be taken from the existing Dataframe or any of the array." }, { "code": "# importing librariesimport pandas as pdimport numpy as np raw_Data = {'Voter_name': ['Geek1', 'Geek2', 'Geek3', 'Geek4', 'Geek5', 'Geek6', 'Geek7', 'Geek8'], 'Voter_age': [15, 23, 25, 9, 67, 54, 42, np.NaN]} df = pd.DataFrame(raw_Data, columns = ['Voter_name', 'Voter_age'])# //DataFrame will look like## Voter_name Voter_age# Geek1 15# Geek2 23# Geek3 25# Geek4 09# Geek5 67# Geek6 54# Geek7 42# Geek8 not a number eligible = [] # For each row in the columnfor age in df['Voter_age']: if age >= 18: # if Voter eligible eligible.append('Yes') elif age < 18: # if voter is not eligible eligible.append(\"No\") else: eligible.append(\"Not Sure\") # Create a column from the listdf['Voter'] = eligible print(df)", "e": 25672, "s": 24707, "text": null }, { "code": null, "e": 25981, "s": 25672, "text": " Voter_name Voter_age Voter\n0 Geek1 15 No\n1 Geek2 23 Yes\n2 Geek3 25 Yes\n3 Geek4 9 No\n4 Geek5 67 Yes\n5 Geek6 54 Yes\n6 Geek7 42 Yes\n7 Geek8 NaN Not Sure\n" }, { "code": null, "e": 26006, "s": 25981, "text": "pandas-dataframe-program" }, { "code": null, "e": 26013, "s": 26006, "text": "Picked" }, { "code": null, "e": 26037, "s": 26013, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26051, "s": 26037, "text": "Python-pandas" }, { "code": null, "e": 26058, "s": 26051, "text": "Python" }, { "code": null, "e": 26156, "s": 26058, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26165, "s": 26156, "text": "Comments" }, { "code": null, "e": 26178, "s": 26165, "text": "Old Comments" }, { "code": null, "e": 26210, "s": 26178, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26266, "s": 26210, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26321, "s": 26266, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26363, "s": 26321, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26405, "s": 26363, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26436, "s": 26405, "text": "Python | os.path.join() method" }, { "code": null, "e": 26475, "s": 26436, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26504, "s": 26475, "text": "Create a directory in Python" }, { "code": null, "e": 26526, "s": 26504, "text": "Defaultdict in Python" } ]
Is it possible to have an HTML canvas element in the background of my page?
Yes, try to set the CSS style with position: fixed (or absolute): canvas{ position:absolute; left:0; top:0; z-index:-1; } You can also set it to the following: <style> #canvasSection{ position:fixed; } </style>
[ { "code": null, "e": 1128, "s": 1062, "text": "Yes, try to set the CSS style with position: fixed (or absolute):" }, { "code": null, "e": 1196, "s": 1128, "text": "canvas{\n position:absolute;\n left:0;\n top:0;\n z-index:-1;\n}" }, { "code": null, "e": 1234, "s": 1196, "text": "You can also set it to the following:" }, { "code": null, "e": 1297, "s": 1234, "text": "<style>\n #canvasSection{\n position:fixed;\n }\n</style>" } ]
Python program display any message on heart - GeeksforGeeks
31 May, 2021 This article focuses on discussing how to draw a heart with a beautiful message to your loved ones to express what you feel about them. Three types of variants of the above problem statement will be discussed here: Red Heart with a message. Pink-Red Heart with a message. Pink Heart with a message in a different font and color than in the above two cases. Program 1: Below is the python code for a simple red heart with a message: Python3 # Python3 program for the above approach# import libraryimport pylabimport numpy as np # Width of heartXaxis = np.linspace(-2, 2, 100000) # Setting upper y Y1axis = np.sqrt(1 - (abs(Xaxis) - 1) **2) # Setting -yY2axis = -3 * np.sqrt(1 - (abs(Xaxis) / 2) **0.5) # Adjust colour for upper part # of heratpylab.fill_between(Xaxis, Y1axis, color = 'red') # Adjust colour for lower part # of heartpylab.fill_between(Xaxis, Y2axis, color = 'red') pylab.xlim([-2.5, 2.5])pylab.axis("off") # Driver Codetext = "Geeksforgeeks" pylab.text(0, -0.4, text, fontsize = 24, fontweight = 'bold', color = 'white', horizontalalignment = 'center') Output: Program 2: Below is the python code to change the color of a part of the heart to pink and the rest of the heart is red and print a message on the heart: Python3 # Python3 program for the above approachimport pylabimport numpy as np # Width of heartXaxis = np.linspace(-2, 2, 100000) # Setting upper y Y1axis = np.sqrt(1 - (abs(Xaxis) - 1) **2) # Setting -yY2axis = -3 * np.sqrt(1 - (abs(Xaxis) / 2) **0.5) # Adjust colour for upper part# of heratpylab.fill_between(Xaxis, Y1axis, color = 'pink') # Adjust colour for lower part # of heartpylab.fill_between(Xaxis, Y2axis, color = 'red') pylab.xlim([-2.5, 2.5])pylab.axis("off") # Driver Codetext = "Geeksforgeeks" pylab.text(0, -0.6, text, fontsize = 24, fontweight = 'bold', color = 'grey', horizontalalignment = 'center') Output: Program 3: Below is the python code to implement a pink color heart with a message in different font size and color: Python3 # Python3 program for the above approachimport pylabimport numpy as np # Width of heartXaxis = np.linspace(-2, 2, 100000) # Setting upper y Y1axis = np.sqrt(1 - (abs(Xaxis) - 1) **2) # Setting lower -yY2axis = -3 * np.sqrt(1 - (abs(Xaxis) / 2) **0.5) # Adjust colour for upper part # of heratpylab.fill_between(Xaxis, Y1axis, color = 'pink') # Adjust colour for lower part of heartpylab.fill_between(Xaxis, Y2axis, color = 'pink') pylab.xlim([-2.5, 2.5])pylab.axis("off") # Driver Codetext = "Geeksforgeeks - \n Best platform to explore" # Explore your change herepylab.text(0, -0.6, text, fontsize = 14, fontweight = 'bold', color = 'red', horizontalalignment = 'center') # To save the above image, execute the # line- pylab.savefig('heart.png') Output: python Python Python Programs python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method 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": 24318, "s": 24290, "text": "\n31 May, 2021" }, { "code": null, "e": 24533, "s": 24318, "text": "This article focuses on discussing how to draw a heart with a beautiful message to your loved ones to express what you feel about them. Three types of variants of the above problem statement will be discussed here:" }, { "code": null, "e": 24559, "s": 24533, "text": "Red Heart with a message." }, { "code": null, "e": 24590, "s": 24559, "text": "Pink-Red Heart with a message." }, { "code": null, "e": 24675, "s": 24590, "text": "Pink Heart with a message in a different font and color than in the above two cases." }, { "code": null, "e": 24750, "s": 24675, "text": "Program 1: Below is the python code for a simple red heart with a message:" }, { "code": null, "e": 24758, "s": 24750, "text": "Python3" }, { "code": "# Python3 program for the above approach# import libraryimport pylabimport numpy as np # Width of heartXaxis = np.linspace(-2, 2, 100000) # Setting upper y Y1axis = np.sqrt(1 - (abs(Xaxis) - 1) **2) # Setting -yY2axis = -3 * np.sqrt(1 - (abs(Xaxis) / 2) **0.5) # Adjust colour for upper part # of heratpylab.fill_between(Xaxis, Y1axis, color = 'red') # Adjust colour for lower part # of heartpylab.fill_between(Xaxis, Y2axis, color = 'red') pylab.xlim([-2.5, 2.5])pylab.axis(\"off\") # Driver Codetext = \"Geeksforgeeks\" pylab.text(0, -0.4, text, fontsize = 24, fontweight = 'bold', color = 'white', horizontalalignment = 'center')", "e": 25516, "s": 24758, "text": null }, { "code": null, "e": 25524, "s": 25516, "text": "Output:" }, { "code": null, "e": 25678, "s": 25524, "text": "Program 2: Below is the python code to change the color of a part of the heart to pink and the rest of the heart is red and print a message on the heart:" }, { "code": null, "e": 25686, "s": 25678, "text": "Python3" }, { "code": "# Python3 program for the above approachimport pylabimport numpy as np # Width of heartXaxis = np.linspace(-2, 2, 100000) # Setting upper y Y1axis = np.sqrt(1 - (abs(Xaxis) - 1) **2) # Setting -yY2axis = -3 * np.sqrt(1 - (abs(Xaxis) / 2) **0.5) # Adjust colour for upper part# of heratpylab.fill_between(Xaxis, Y1axis, color = 'pink') # Adjust colour for lower part # of heartpylab.fill_between(Xaxis, Y2axis, color = 'red') pylab.xlim([-2.5, 2.5])pylab.axis(\"off\") # Driver Codetext = \"Geeksforgeeks\" pylab.text(0, -0.6, text, fontsize = 24, fontweight = 'bold', color = 'grey', horizontalalignment = 'center')", "e": 26425, "s": 25686, "text": null }, { "code": null, "e": 26433, "s": 26425, "text": "Output:" }, { "code": null, "e": 26550, "s": 26433, "text": "Program 3: Below is the python code to implement a pink color heart with a message in different font size and color:" }, { "code": null, "e": 26558, "s": 26550, "text": "Python3" }, { "code": "# Python3 program for the above approachimport pylabimport numpy as np # Width of heartXaxis = np.linspace(-2, 2, 100000) # Setting upper y Y1axis = np.sqrt(1 - (abs(Xaxis) - 1) **2) # Setting lower -yY2axis = -3 * np.sqrt(1 - (abs(Xaxis) / 2) **0.5) # Adjust colour for upper part # of heratpylab.fill_between(Xaxis, Y1axis, color = 'pink') # Adjust colour for lower part of heartpylab.fill_between(Xaxis, Y2axis, color = 'pink') pylab.xlim([-2.5, 2.5])pylab.axis(\"off\") # Driver Codetext = \"Geeksforgeeks - \\n Best platform to explore\" # Explore your change herepylab.text(0, -0.6, text, fontsize = 14, fontweight = 'bold', color = 'red', horizontalalignment = 'center') # To save the above image, execute the # line- pylab.savefig('heart.png')", "e": 27433, "s": 26558, "text": null }, { "code": null, "e": 27441, "s": 27433, "text": "Output:" }, { "code": null, "e": 27448, "s": 27441, "text": "python" }, { "code": null, "e": 27455, "s": 27448, "text": "Python" }, { "code": null, "e": 27471, "s": 27455, "text": "Python Programs" }, { "code": null, "e": 27478, "s": 27471, "text": "python" }, { "code": null, "e": 27576, "s": 27478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27608, "s": 27576, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27650, "s": 27608, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27706, "s": 27650, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27748, "s": 27706, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27779, "s": 27748, "text": "Python | os.path.join() method" }, { "code": null, "e": 27801, "s": 27779, "text": "Defaultdict in Python" }, { "code": null, "e": 27847, "s": 27801, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27886, "s": 27847, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27924, "s": 27886, "text": "Python | Convert a list to dictionary" } ]
Python datetime to integer timestamp - GeeksforGeeks
04 Sep, 2021 In this article, we are going to see how to convert python DateTime to integer timestamp. The timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That zero moment is known as the epoch. First, we will get the current time or explicitly mention the required date and time we want the timestamp of. There are several ways to get the date and time. We will see them as we go through the examples. Then we will convert the datetime into timestamp using timestamp() function. At last, we will round off the timestamp in seconds and milliseconds and explicitly typecast into integer datatype and our work is done! Here we import the DateTime module to use the DateTime function from it. And then use datetime.now() function to get the current date and time. Convert the DateTime object into timestamp using DateTime.timestamp() method. We will get the timestamp in seconds. And then round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds. Python3 from datetime import datetimecurr_dt = datetime.now() print("Current datetime: ", curr_dt)timestamp = int(round(curr_dt.timestamp())) print("Integer timestamp of current datetime: ", timestamp) Output: Current datetime: 2021-08-25 15:04:33.794484 Integer timestamp of current datetime: 1629884074 Give the date and time as parameters inside the datetime() function. Convert the datetime object into timestamp using datetime.timestamp() method. We will get the timestamp in seconds. Round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds. We can also convert it into milliseconds by multiplying it by1000 to get the integer timestamp in milliseconds. Python3 from datetime import datetimedtime = datetime(2018, 1, 1, 20)print("Datetime: ", dtime) dtimestamp = dtime.timestamp()print("Integer timestamp in seconds: ", int(round(dtimestamp))) milliseconds = int(round(dtimestamp * 1000))print("Integer timestamp in milliseconds: ", milliseconds) Output: Datetime: 2018-01-01 20:00:00 Integer timestamp in seconds: 1514817000 Integer timestamp in milliseconds: 1514817000000 First, we enter the UTIC time inside the datetime.datetime() object. Then we pass the object to d.timtuple() function which gives a tuple containing the parameters like year, month, day, and so on, and then using the calendar function we convert the datetime to integer UTC timestamp. Python3 import datetimeimport calendar d = datetime.datetime(1970, 1, 1, 2, 1, 0)ttuple = d.timetuple() itimestamp = calendar.timegm(ttuple)print("Timestamp in integer since epoch:", itimestamp) Output: Timestamp in integer since epoch: 7260 First, we get the current time using datetime.datetime.now(). And then import the pytz library to instantiate the timezone object to localize the datetime. Convert the datetime object into timestamp using datetime.timestamp() method. We will get the timestamp in seconds. Round off and convert the timestamp in integer to get the integer timestamp. Python3 import datetimeimport pytz dtime = datetime.datetime.now()timezone = pytz.timezone("Asia/Kolkata")dtzone = timezone.localize(dtime) print("Time Zone: ", dtzone.tzinfo)print("Datetime: ", dtzone) tstamp = dtzone.timestamp()print("Integer timestamp: ", int(round(tstamp))) Output: Time Zone: Asia/Kolkata Datetime: 2021-08-25 15:09:05.194413+05:30 Integer timestamp: 1629884345 saurabh1990aror Picked Python datetime-program Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python *args and **kwargs in Python
[ { "code": null, "e": 24132, "s": 24104, "text": "\n04 Sep, 2021" }, { "code": null, "e": 24223, "s": 24132, "text": "In this article, we are going to see how to convert python DateTime to integer timestamp. " }, { "code": null, "e": 24665, "s": 24223, "text": "The timestamp() function returns the time expressed as the number of seconds that have passed since January 1, 1970. That zero moment is known as the epoch. First, we will get the current time or explicitly mention the required date and time we want the timestamp of. There are several ways to get the date and time. We will see them as we go through the examples. Then we will convert the datetime into timestamp using timestamp() function." }, { "code": null, "e": 24802, "s": 24665, "text": "At last, we will round off the timestamp in seconds and milliseconds and explicitly typecast into integer datatype and our work is done!" }, { "code": null, "e": 25202, "s": 24802, "text": "Here we import the DateTime module to use the DateTime function from it. And then use datetime.now() function to get the current date and time. Convert the DateTime object into timestamp using DateTime.timestamp() method. We will get the timestamp in seconds. And then round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds." }, { "code": null, "e": 25210, "s": 25202, "text": "Python3" }, { "code": "from datetime import datetimecurr_dt = datetime.now() print(\"Current datetime: \", curr_dt)timestamp = int(round(curr_dt.timestamp())) print(\"Integer timestamp of current datetime: \", timestamp)", "e": 25409, "s": 25210, "text": null }, { "code": null, "e": 25417, "s": 25409, "text": "Output:" }, { "code": null, "e": 25514, "s": 25417, "text": "Current datetime: 2021-08-25 15:04:33.794484\nInteger timestamp of current datetime: 1629884074" }, { "code": null, "e": 25942, "s": 25514, "text": "Give the date and time as parameters inside the datetime() function. Convert the datetime object into timestamp using datetime.timestamp() method. We will get the timestamp in seconds. Round off the timestamp and explicitly typecast the floating-point number into an integer to get the integer timestamp in seconds. We can also convert it into milliseconds by multiplying it by1000 to get the integer timestamp in milliseconds." }, { "code": null, "e": 25950, "s": 25942, "text": "Python3" }, { "code": "from datetime import datetimedtime = datetime(2018, 1, 1, 20)print(\"Datetime: \", dtime) dtimestamp = dtime.timestamp()print(\"Integer timestamp in seconds: \", int(round(dtimestamp))) milliseconds = int(round(dtimestamp * 1000))print(\"Integer timestamp in milliseconds: \", milliseconds)", "e": 26245, "s": 25950, "text": null }, { "code": null, "e": 26253, "s": 26245, "text": "Output:" }, { "code": null, "e": 26376, "s": 26253, "text": "Datetime: 2018-01-01 20:00:00\nInteger timestamp in seconds: 1514817000\nInteger timestamp in milliseconds: 1514817000000" }, { "code": null, "e": 26661, "s": 26376, "text": "First, we enter the UTIC time inside the datetime.datetime() object. Then we pass the object to d.timtuple() function which gives a tuple containing the parameters like year, month, day, and so on, and then using the calendar function we convert the datetime to integer UTC timestamp." }, { "code": null, "e": 26669, "s": 26661, "text": "Python3" }, { "code": "import datetimeimport calendar d = datetime.datetime(1970, 1, 1, 2, 1, 0)ttuple = d.timetuple() itimestamp = calendar.timegm(ttuple)print(\"Timestamp in integer since epoch:\", itimestamp)", "e": 26861, "s": 26669, "text": null }, { "code": null, "e": 26869, "s": 26861, "text": "Output:" }, { "code": null, "e": 26908, "s": 26869, "text": "Timestamp in integer since epoch: 7260" }, { "code": null, "e": 27257, "s": 26908, "text": "First, we get the current time using datetime.datetime.now(). And then import the pytz library to instantiate the timezone object to localize the datetime. Convert the datetime object into timestamp using datetime.timestamp() method. We will get the timestamp in seconds. Round off and convert the timestamp in integer to get the integer timestamp." }, { "code": null, "e": 27265, "s": 27257, "text": "Python3" }, { "code": "import datetimeimport pytz dtime = datetime.datetime.now()timezone = pytz.timezone(\"Asia/Kolkata\")dtzone = timezone.localize(dtime) print(\"Time Zone: \", dtzone.tzinfo)print(\"Datetime: \", dtzone) tstamp = dtzone.timestamp()print(\"Integer timestamp: \", int(round(tstamp)))", "e": 27536, "s": 27265, "text": null }, { "code": null, "e": 27544, "s": 27536, "text": "Output:" }, { "code": null, "e": 27644, "s": 27544, "text": "Time Zone: Asia/Kolkata\nDatetime: 2021-08-25 15:09:05.194413+05:30\nInteger timestamp: 1629884345" }, { "code": null, "e": 27660, "s": 27644, "text": "saurabh1990aror" }, { "code": null, "e": 27667, "s": 27660, "text": "Picked" }, { "code": null, "e": 27691, "s": 27667, "text": "Python datetime-program" }, { "code": null, "e": 27707, "s": 27691, "text": "Python-datetime" }, { "code": null, "e": 27714, "s": 27707, "text": "Python" }, { "code": null, "e": 27812, "s": 27714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27821, "s": 27812, "text": "Comments" }, { "code": null, "e": 27834, "s": 27821, "text": "Old Comments" }, { "code": null, "e": 27869, "s": 27834, "text": "Read a file line by line in Python" }, { "code": null, "e": 27891, "s": 27869, "text": "Enumerate() in Python" }, { "code": null, "e": 27923, "s": 27891, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27953, "s": 27923, "text": "Iterate over a list in Python" }, { "code": null, "e": 27995, "s": 27953, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28021, "s": 27995, "text": "Python String | replace()" }, { "code": null, "e": 28064, "s": 28021, "text": "Python program to convert a list to string" }, { "code": null, "e": 28101, "s": 28064, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28145, "s": 28101, "text": "Reading and Writing to text files in Python" } ]
C library function - vsprintf()
The C library function int vsprintf(char *str, const char *format, va_list arg) sends formatted output to a string using an argument list passed to it. Following is the declaration for vsprintf() function. int vsprintf(char *str, const char *format, va_list arg) str − This is the array of char elements where the resulting string is to be stored. str − This is the array of char elements where the resulting string is to be stored. format − This is the C string that contains the text to be written to the str. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and are formatted as requested. Format tags prototype − %[flags][width][.precision][length]specifier, as explained below − format − This is the C string that contains the text to be written to the str. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and are formatted as requested. Format tags prototype − %[flags][width][.precision][length]specifier, as explained below − c Character d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f. G Uses the shorter of %E or %f o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character - Left-justify within the given field width; Right justification is the default (see width sub-specifier). + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign. (space) If no sign is going to be written, a blank space is inserted before the value. # Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed. 0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier). (number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. * The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. .number For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers − this is the number of digits to be printed after the decimal point. For g and G specifiers − This is the maximum number of significant digits to be printed. For s − this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type − it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed. .* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers − i, d, o, u, x and X). l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s. L The argument is interpreted as a long double (only applies to floating point specifiers − e, E, f, g and G). arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>. arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>. If successful, the total number of characters written is returned, otherwise a negative number is returned. The following example shows the usage of vsprintf() function. #include <stdio.h> #include <stdarg.h> char buffer[80]; int vspfunc(char *format, ...) { va_list aptr; int ret; va_start(aptr, format); ret = vsprintf(buffer, format, aptr); va_end(aptr); return(ret); } int main () { int i = 5; float f = 27.0; char str[50] = "tutoriaspoint.com"; vspfunc("%d %f %s", i, f, str); printf("%s\n", buffer); return(0); } Let us compile and run the above program, this will produce the following result − 5 27.000000 tutoriaspoint.com 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2159, "s": 2007, "text": "The C library function int vsprintf(char *str, const char *format, va_list arg) sends formatted output to a string using an argument list passed to it." }, { "code": null, "e": 2213, "s": 2159, "text": "Following is the declaration for vsprintf() function." }, { "code": null, "e": 2270, "s": 2213, "text": "int vsprintf(char *str, const char *format, va_list arg)" }, { "code": null, "e": 2355, "s": 2270, "text": "str − This is the array of char elements where the resulting string is to be stored." }, { "code": null, "e": 2440, "s": 2355, "text": "str − This is the array of char elements where the resulting string is to be stored." }, { "code": null, "e": 2766, "s": 2440, "text": "format − This is the C string that contains the text to be written to the str. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and are formatted as requested. Format tags prototype − %[flags][width][.precision][length]specifier, as explained below −" }, { "code": null, "e": 3092, "s": 2766, "text": "format − This is the C string that contains the text to be written to the str. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and are formatted as requested. Format tags prototype − %[flags][width][.precision][length]specifier, as explained below −" }, { "code": null, "e": 3094, "s": 3092, "text": "c" }, { "code": null, "e": 3104, "s": 3094, "text": "Character" }, { "code": null, "e": 3111, "s": 3104, "text": "d or i" }, { "code": null, "e": 3134, "s": 3111, "text": "Signed decimal integer" }, { "code": null, "e": 3136, "s": 3134, "text": "e" }, { "code": null, "e": 3194, "s": 3136, "text": "Scientific notation (mantissa/exponent) using e character" }, { "code": null, "e": 3196, "s": 3194, "text": "E" }, { "code": null, "e": 3254, "s": 3196, "text": "Scientific notation (mantissa/exponent) using E character" }, { "code": null, "e": 3256, "s": 3254, "text": "f" }, { "code": null, "e": 3279, "s": 3256, "text": "Decimal floating point" }, { "code": null, "e": 3281, "s": 3279, "text": "g" }, { "code": null, "e": 3311, "s": 3281, "text": "Uses the shorter of %e or %f." }, { "code": null, "e": 3313, "s": 3311, "text": "G" }, { "code": null, "e": 3342, "s": 3313, "text": "Uses the shorter of %E or %f" }, { "code": null, "e": 3344, "s": 3342, "text": "o" }, { "code": null, "e": 3357, "s": 3344, "text": "Signed octal" }, { "code": null, "e": 3359, "s": 3357, "text": "s" }, { "code": null, "e": 3380, "s": 3359, "text": "String of characters" }, { "code": null, "e": 3382, "s": 3380, "text": "u" }, { "code": null, "e": 3407, "s": 3382, "text": "Unsigned decimal integer" }, { "code": null, "e": 3409, "s": 3407, "text": "x" }, { "code": null, "e": 3438, "s": 3409, "text": "Unsigned hexadecimal integer" }, { "code": null, "e": 3440, "s": 3438, "text": "X" }, { "code": null, "e": 3487, "s": 3440, "text": "Unsigned hexadecimal integer (capital letters)" }, { "code": null, "e": 3489, "s": 3487, "text": "p" }, { "code": null, "e": 3505, "s": 3489, "text": "Pointer address" }, { "code": null, "e": 3507, "s": 3505, "text": "n" }, { "code": null, "e": 3523, "s": 3507, "text": "Nothing printed" }, { "code": null, "e": 3525, "s": 3523, "text": "%" }, { "code": null, "e": 3535, "s": 3525, "text": "Character" }, { "code": null, "e": 3537, "s": 3535, "text": "-" }, { "code": null, "e": 3642, "s": 3537, "text": "Left-justify within the given field width; Right justification is the default (see width sub-specifier)." }, { "code": null, "e": 3644, "s": 3642, "text": "+" }, { "code": null, "e": 3799, "s": 3644, "text": "Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign." }, { "code": null, "e": 3807, "s": 3799, "text": "(space)" }, { "code": null, "e": 3886, "s": 3807, "text": "If no sign is going to be written, a blank space is inserted before the value." }, { "code": null, "e": 3888, "s": 3886, "text": "#" }, { "code": null, "e": 4266, "s": 3888, "text": "Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed." }, { "code": null, "e": 4268, "s": 4266, "text": "0" }, { "code": null, "e": 4378, "s": 4268, "text": "Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier)." }, { "code": null, "e": 4387, "s": 4378, "text": "(number)" }, { "code": null, "e": 4584, "s": 4387, "text": "Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger." }, { "code": null, "e": 4586, "s": 4584, "text": "*" }, { "code": null, "e": 4728, "s": 4586, "text": "The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted." }, { "code": null, "e": 4736, "s": 4728, "text": ".number" }, { "code": null, "e": 5565, "s": 4736, "text": "For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers − this is the number of digits to be printed after the decimal point. For g and G specifiers − This is the maximum number of significant digits to be printed. For s − this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type − it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed." }, { "code": null, "e": 5568, "s": 5565, "text": ".*" }, { "code": null, "e": 5714, "s": 5568, "text": "The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted." }, { "code": null, "e": 5716, "s": 5714, "text": "h" }, { "code": null, "e": 5841, "s": 5716, "text": "The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers − i, d, o, u, x and X)." }, { "code": null, "e": 5843, "s": 5841, "text": "l" }, { "code": null, "e": 6025, "s": 5843, "text": "The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s." }, { "code": null, "e": 6027, "s": 6025, "text": "L" }, { "code": null, "e": 6136, "s": 6027, "text": "The argument is interpreted as a long double (only applies to floating point specifiers − e, E, f, g and G)." }, { "code": null, "e": 6264, "s": 6136, "text": "arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>." }, { "code": null, "e": 6392, "s": 6264, "text": "arg − An object representing the variable arguments list. This should be initialized by the va_start macro defined in <stdarg>." }, { "code": null, "e": 6500, "s": 6392, "text": "If successful, the total number of characters written is returned, otherwise a negative number is returned." }, { "code": null, "e": 6562, "s": 6500, "text": "The following example shows the usage of vsprintf() function." }, { "code": null, "e": 6956, "s": 6562, "text": "#include <stdio.h>\n#include <stdarg.h>\n\nchar buffer[80];\nint vspfunc(char *format, ...) {\n va_list aptr;\n int ret;\n\n va_start(aptr, format);\n ret = vsprintf(buffer, format, aptr);\n va_end(aptr);\n\n return(ret);\n}\n\nint main () {\n int i = 5;\n float f = 27.0;\n char str[50] = \"tutoriaspoint.com\";\n\n vspfunc(\"%d %f %s\", i, f, str);\n printf(\"%s\\n\", buffer);\n \n return(0);\n}" }, { "code": null, "e": 7039, "s": 6956, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 7070, "s": 7039, "text": "5 27.000000 tutoriaspoint.com\n" }, { "code": null, "e": 7103, "s": 7070, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 7118, "s": 7103, "text": " Nishant Malik" }, { "code": null, "e": 7153, "s": 7118, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7168, "s": 7153, "text": " Nishant Malik" }, { "code": null, "e": 7203, "s": 7168, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7217, "s": 7203, "text": " Asif Hussain" }, { "code": null, "e": 7250, "s": 7217, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 7268, "s": 7250, "text": " Richa Maheshwari" }, { "code": null, "e": 7303, "s": 7268, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7322, "s": 7303, "text": " Vandana Annavaram" }, { "code": null, "e": 7355, "s": 7322, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 7367, "s": 7355, "text": " Amit Diwan" }, { "code": null, "e": 7374, "s": 7367, "text": " Print" }, { "code": null, "e": 7385, "s": 7374, "text": " Add Notes" } ]
JavaScript - While Loops
While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines. JavaScript supports all the necessary loops to ease down the pressure of programming. The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates. The flow chart of while loop looks as follows − The syntax of while loop in JavaScript is as follows − while (expression) { Statement(s) to be executed if expression is true } Try the following example to implement while loop. <html> <body> <script type = "text/javascript"> <!-- var count = 0; document.write("Starting Loop "); while (count < 10) { document.write("Current Count : " + count + "<br />"); count++; } document.write("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Current Count : 5 Current Count : 6 Current Count : 7 Current Count : 8 Current Count : 9 Loop stopped! Set the variable to different value and then try... The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. The flow chart of a do-while loop would be as follows − The syntax for do-while loop in JavaScript is as follows − do { Statement(s) to be executed; } while (expression); Note − Don’t miss the semicolon used at the end of the do...while loop. Try the following example to learn how to implement a do-while loop in JavaScript. <html> <body> <script type = "text/javascript"> <!-- var count = 0; document.write("Starting Loop" + "<br />"); do { document.write("Current Count : " + count + "<br />"); count++; } while (count < 5); document.write ("Loop stopped!"); //--> </script> <p>Set the variable to different value and then try...</p> </body> </html> Starting Loop Current Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4 Loop Stopped! Set the variable to different value and then try... 25 Lectures 2.5 hours Anadi Sharma 74 Lectures 10 hours Lets Kode It 72 Lectures 4.5 hours Frahaan Hussain 70 Lectures 4.5 hours Frahaan Hussain 46 Lectures 6 hours Eduonix Learning Solutions 88 Lectures 14 hours Eduonix Learning Solutions Print Add Notes Bookmark this page
[ { "code": null, "e": 2669, "s": 2466, "text": "While writing a program, you may encounter a situation where you need to perform an action over and over again. In such situations, you would need to write loop statements to reduce the number of lines." }, { "code": null, "e": 2755, "s": 2669, "text": "JavaScript supports all the necessary loops to ease down the pressure of programming." }, { "code": null, "e": 3018, "s": 2755, "text": "The most basic loop in JavaScript is the while loop which would be discussed in this chapter. The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true. Once the expression becomes false, the loop terminates." }, { "code": null, "e": 3066, "s": 3018, "text": "The flow chart of while loop looks as follows −" }, { "code": null, "e": 3121, "s": 3066, "text": "The syntax of while loop in JavaScript is as follows −" }, { "code": null, "e": 3198, "s": 3121, "text": "while (expression) {\n Statement(s) to be executed if expression is true\n}\n" }, { "code": null, "e": 3249, "s": 3198, "text": "Try the following example to implement while loop." }, { "code": null, "e": 3728, "s": 3249, "text": "<html>\n <body>\n \n <script type = \"text/javascript\">\n <!--\n var count = 0;\n document.write(\"Starting Loop \");\n \n while (count < 10) {\n document.write(\"Current Count : \" + count + \"<br />\");\n count++;\n }\n \n document.write(\"Loop stopped!\");\n //-->\n </script>\n \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 3990, "s": 3728, "text": "Starting Loop\nCurrent Count : 0\nCurrent Count : 1\nCurrent Count : 2\nCurrent Count : 3\nCurrent Count : 4\nCurrent Count : 5\nCurrent Count : 6\nCurrent Count : 7\nCurrent Count : 8\nCurrent Count : 9\nLoop stopped!\nSet the variable to different value and then try... \n" }, { "code": null, "e": 4199, "s": 3990, "text": "The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false." }, { "code": null, "e": 4255, "s": 4199, "text": "The flow chart of a do-while loop would be as follows −" }, { "code": null, "e": 4314, "s": 4255, "text": "The syntax for do-while loop in JavaScript is as follows −" }, { "code": null, "e": 4374, "s": 4314, "text": "do {\n Statement(s) to be executed;\n} while (expression);\n" }, { "code": null, "e": 4446, "s": 4374, "text": "Note − Don’t miss the semicolon used at the end of the do...while loop." }, { "code": null, "e": 4529, "s": 4446, "text": "Try the following example to learn how to implement a do-while loop in JavaScript." }, { "code": null, "e": 5035, "s": 4529, "text": "<html>\n <body> \n <script type = \"text/javascript\">\n <!--\n var count = 0;\n \n document.write(\"Starting Loop\" + \"<br />\");\n do {\n document.write(\"Current Count : \" + count + \"<br />\");\n count++;\n }\n \n while (count < 5);\n document.write (\"Loop stopped!\");\n //-->\n </script> \n <p>Set the variable to different value and then try...</p>\n </body>\n</html>" }, { "code": null, "e": 5210, "s": 5035, "text": "Starting Loop\nCurrent Count : 0 \nCurrent Count : 1 \nCurrent Count : 2 \nCurrent Count : 3 \nCurrent Count : 4\nLoop Stopped!\nSet the variable to different value and then try...\n" }, { "code": null, "e": 5245, "s": 5210, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5259, "s": 5245, "text": " Anadi Sharma" }, { "code": null, "e": 5293, "s": 5259, "text": "\n 74 Lectures \n 10 hours \n" }, { "code": null, "e": 5307, "s": 5293, "text": " Lets Kode It" }, { "code": null, "e": 5342, "s": 5307, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5359, "s": 5342, "text": " Frahaan Hussain" }, { "code": null, "e": 5394, "s": 5359, "text": "\n 70 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5411, "s": 5394, "text": " Frahaan Hussain" }, { "code": null, "e": 5444, "s": 5411, "text": "\n 46 Lectures \n 6 hours \n" }, { "code": null, "e": 5472, "s": 5444, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5506, "s": 5472, "text": "\n 88 Lectures \n 14 hours \n" }, { "code": null, "e": 5534, "s": 5506, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 5541, "s": 5534, "text": " Print" }, { "code": null, "e": 5552, "s": 5541, "text": " Add Notes" } ]
BigQuery UNNEST example | Towards Data Science
We frequently apply machine learning techniques to event-based data in order to generate high-value insights; from predicting customer churn using people’s recent activity of say, a subscription-based product, to scoring how engaged a user is on a piece of content for feeding into a recommendation engine. Event-based data is a good example of semi-structured-data. Structured data is data that adheres to a rigid tabular format. This makes it ideal for storing in say, a database table or a spreadsheet. Semi-structured data, however, has variations in its structure; attributes are not fixed(equivalent to columns in a database table), and, to further complicate things, the data itself can be nested. To illustrate this, consider the following use case: We want to consolidate event data generated from 3 different apps that users interact with via mobile devices and laptops/desktop PCs. Some of the attributes received in the event data will be common across all apps. A timestamp, for example, to indicate when the event occurred. Other attributes will only apply to certain applications/devices. Furthermore, some of these attributes may have multiple occurrences within the context of a single event, and therefore creates a need for the data to be nested. Semi-structured data is typically stored as JSON or XML, and is the foundation of no-SQL data stores such as Google’s Firebase, or MongoDB. Alongside structured data, Google’s BigQuery also supports the storage of semi-structured data via two nested datatypes: the array and the struct. Furthermore, BigQuery makes it really easy to ingest JSON, XML, and other such data into its tables, to facilitate further analysis. We will explore a common example of event-data exported from Firebase and loaded into BigQuery. We will show how to work with the data and explore useful BigQuery functions, including UNNEST. We assume you already have a Google Cloud Project with access to BigQuery. If not, you can easily create one (for free) using the link below. cloud.google.com For this example, we use some really good, publically available Firebase data from here. These are simulated events from an online game. We start by creating a dataset in our BigQuery project to contain our example tables. To do this: Navigate to your BigQuery project in the Google Cloud Console. Click your project-id in the nav menu on the left.You should see a CREATE DATASET option appear like this. Click the link. Navigate to your BigQuery project in the Google Cloud Console. Click your project-id in the nav menu on the left. You should see a CREATE DATASET option appear like this. Click the link. 3. Enter “blog_unnest” as the dataset name, and leave all other defaults. Click Create Dataset. Now we have a dataset, we can create a table called firebase_raw that contains a sample (1,000 rows) of Firebase event data. To do this, simply run this in the BigQuery UI: create table blog_unnest.firebase_rawasselect *from `firebase-public-project.analytics_153293282.events_20180801`where event_name = ‘level_complete_quickplay’limit 1000 Tip: Notice the Firebase to BigQuery export generates an events table that is sharded by the event date (in bold above). In this example, we are extracting data from shard 20180801, which contains all events seen on 1 Aug 2018. The limit keyword tells BigQuery to limit rows to 1,000. Like the top n feature if you come from an MS SQL background. With the sample data loaded, we can explore its structure. Clicking on the firebase_raw table, we see the columns listed. Note the event_params is of type RECORD — indicating it is a nested field. If we run the simple query below, we can see what the data looks like. select *from blog_unnest.firebase_raw Event_params (highlighted) is a nested field, with each nested row representing a parameter for that event. We can see there are 5 nested rows for this “level complete quickplay” event, one row per parameter. In Firebase, typically each event needs its own unique set of supporting parameters, and you can see how storing them in this way makes it possible. Event_date is a regular column, indicating which day the event occurred. Event_timestamp represents a derivative of Unix time to denote when the event took place. Tip: Event_timestamp in Firebase denotes the number of microseconds since 1 Jan 1970. To convert this into a BigQuery timestamp, you can use BigQuery’s timestamp_micros function: select timestamp_micros(event_timestamp) as event_ts, event_timestampfrom blog_unnest.firebase_raw Which gives: 2018–08–01 13:45:54.159108 UTC for event_timestamp 1533131154159108 The UNNEST function allows us to easily query nested fields, such as the parameters in our event data. Suppose we want to flatten our event data into rows, and extract: The event_timestampThe event_nameThe value from the nested params (the number of moves a player made)The board from the nested params (size of board played, S M or L) The event_timestamp The event_name The value from the nested params (the number of moves a player made) The board from the nested params (size of board played, S M or L) The first two are easy. But the last two are more difficult. Here is where the UNNEST function comes into play: select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, param_value.value.int_value as move_count, param_board.value.string_value as board_sizefrom blog_unnest.firebase_raw r cross join unnest(event_params) param_value cross join unnest(event_params) param_board where param_value.key = ‘value’and param_board.key = ‘board’ This produces the output that we want: Let’s break this down. cross join unnest(event_params) param_value UNNEST takes the rows in our nested event_params struct, unpacks these, and produces a table with a single struct for each row in the original event_params nested field. In our case, this nested field contained 5 rows per parent event row. The cross join applies a cartesian product of the 5 nested rows with the parent event row. The total row count returned is therefore 5,000 (5 parameters per 1,000 rows). In our case, the first attribute we wanted to extract from event_params was the value. So, we alias our cross join unnest function call as param_value, and then add the following where clause to filter on the key: where param_value.key = ‘value’ Remember, the rows in our param_value are themselves a struct. So, when we extract the int_value in the select clause, we need to use this notation to reference the value: select param_value.value.int_value as move_count, Tip: if you want to select all the attributes in a struct, and not just the int_value as we did here, you can just do this: select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, param_valuefrom blog_unnest.firebase_raw rcross join unnest(event_params) param_value Which will add each attribute is a column in the result set. Useful if you want to explore structs where you don’t really know what the structure is: There is another way to use the UNNEST function to achieve the same output as our previous example. We can use an inline select, instead of the multipe cross joins: select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, ( select event_params.value.int_value from unnest(event_params) event_params where event_params.key = ‘value’ ) as move_count, ( select event_params.value.string_value from unnest(event_params) event_params where event_params.key = ‘board’ ) as board_sizefrom blog_unnest.firebase_raw r One advantage of using the inline select approach over cross join, is it handles missing attributes much better. For example, say we want to bring back a third attribute, “foo”, from the event_params. This parameter only applies to certain events, and if it is missing, we still want our other data returned. Note foo does not exist in our test data. Modifying the first approach: select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, param_value.value.int_value as move_count, param_board.value.string_value as board_size, param_foo.value.int_value as foo from blog_unnest.firebase_raw r cross join unnest(event_params) param_value cross join unnest(event_params) param_board cross join unnest(event_params) param_foo where param_value.key = ‘value’and param_board.key = ‘board’and param_foo.key = ‘foo’ Running this returns 0 rows. This is because, in a similar way to how applying a where clause limits rows to a left outer join, the same applies to a cross join. However, if we amend our inline select approach: select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, ( select event_params.value.int_value from unnest(event_params) event_params where event_params.key = ‘value’ ) as move_count, ( select event_params.value.string_value from unnest(event_params) event_params where event_params.key = ‘board’ ) as board_size, ( select event_params.value.string_value from unnest(event_params) event_params where event_params.key = ‘foo’ ) as foofrom blog_unnest.firebase_raw r This time, we get our expected result; rows returned with the foo column containing nulls. In some ways, this approach is also easier to read and is easier to add additional attributes because only the select clause needs to be modified. In terms of the amount of data scanned, the two approaches are identical. Tip: as a general rule we try to avoid inline selects as joins are typically more performant; however in this use case, the performance is identical and we would typically opt for the inline select approach. Lastly, we show you how to convert a data type (or do other manipulations) to nested data whilst maintaining the data in its nested form. Again, we use the BigQuery UNNEST function to achieve this. The basic approach is to: Call UNNEST to unpack the nested dataApply cast function (or other data manipulation)Reconstruct the structure using the ARRAY and STRUCT datatypes accordingly. Call UNNEST to unpack the nested data Apply cast function (or other data manipulation) Reconstruct the structure using the ARRAY and STRUCT datatypes accordingly. Keeping with the Firebase event data, in the user_properties nested field we find another timestamp attribute called set_timestamp_micros that is again in the Unix like format and therefore difficult to read. We want to apply a timestamp_micros() function to this attribute, converting it to a human-readable timestamp. We can achieve this using the following combination of UNNEST, ARRAY, and STRUCT: select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, array( select struct( user_properties.key, struct( user_properties.value.string_value, user_properties.value.int_value, user_properties.value.float_value, user_properties.value.double_value, timestamp_micros ( user_properties.value.set_timestamp_micros ) as set_timestamp_micros ) as value ) from unnest(user_properties) user_properties ) as user_propertiesfrom blog_unnest.firebase_raw r If you take the time to understand the above, you should be well on your way to mastering the UNNEST function and working with Firebase, and other semi-structured data. As we have seen, BigQuery is really flexible in that it can store both structured and semi-structured data via its support for nested data types. This lends itself really well for analysing and applying machine learning activities on event data, which is inherently semi-structured. The notation in BigQuery for working with nested data does have a bit of a learning curve, and this was partly the motivation for writing this article — to help fellow data scientists and analysts who might be faced with this challenge to see a working example complete with explanations. We specifically hope those of you who are working with Firebase event data (a very common use case in the field), will find this helpful and should hopefully save you some time! You can read the official Google Cloud documentation on working with nested data here. You can read the official Google Cloud documentation on working with nested data here. 2. Learn more about Ancoris Data, Analytics & AI
[ { "code": null, "e": 353, "s": 46, "text": "We frequently apply machine learning techniques to event-based data in order to generate high-value insights; from predicting customer churn using people’s recent activity of say, a subscription-based product, to scoring how engaged a user is on a piece of content for feeding into a recommendation engine." }, { "code": null, "e": 413, "s": 353, "text": "Event-based data is a good example of semi-structured-data." }, { "code": null, "e": 552, "s": 413, "text": "Structured data is data that adheres to a rigid tabular format. This makes it ideal for storing in say, a database table or a spreadsheet." }, { "code": null, "e": 751, "s": 552, "text": "Semi-structured data, however, has variations in its structure; attributes are not fixed(equivalent to columns in a database table), and, to further complicate things, the data itself can be nested." }, { "code": null, "e": 939, "s": 751, "text": "To illustrate this, consider the following use case: We want to consolidate event data generated from 3 different apps that users interact with via mobile devices and laptops/desktop PCs." }, { "code": null, "e": 1312, "s": 939, "text": "Some of the attributes received in the event data will be common across all apps. A timestamp, for example, to indicate when the event occurred. Other attributes will only apply to certain applications/devices. Furthermore, some of these attributes may have multiple occurrences within the context of a single event, and therefore creates a need for the data to be nested." }, { "code": null, "e": 1452, "s": 1312, "text": "Semi-structured data is typically stored as JSON or XML, and is the foundation of no-SQL data stores such as Google’s Firebase, or MongoDB." }, { "code": null, "e": 1599, "s": 1452, "text": "Alongside structured data, Google’s BigQuery also supports the storage of semi-structured data via two nested datatypes: the array and the struct." }, { "code": null, "e": 1732, "s": 1599, "text": "Furthermore, BigQuery makes it really easy to ingest JSON, XML, and other such data into its tables, to facilitate further analysis." }, { "code": null, "e": 1924, "s": 1732, "text": "We will explore a common example of event-data exported from Firebase and loaded into BigQuery. We will show how to work with the data and explore useful BigQuery functions, including UNNEST." }, { "code": null, "e": 2066, "s": 1924, "text": "We assume you already have a Google Cloud Project with access to BigQuery. If not, you can easily create one (for free) using the link below." }, { "code": null, "e": 2083, "s": 2066, "text": "cloud.google.com" }, { "code": null, "e": 2220, "s": 2083, "text": "For this example, we use some really good, publically available Firebase data from here. These are simulated events from an online game." }, { "code": null, "e": 2318, "s": 2220, "text": "We start by creating a dataset in our BigQuery project to contain our example tables. To do this:" }, { "code": null, "e": 2504, "s": 2318, "text": "Navigate to your BigQuery project in the Google Cloud Console. Click your project-id in the nav menu on the left.You should see a CREATE DATASET option appear like this. Click the link." }, { "code": null, "e": 2618, "s": 2504, "text": "Navigate to your BigQuery project in the Google Cloud Console. Click your project-id in the nav menu on the left." }, { "code": null, "e": 2691, "s": 2618, "text": "You should see a CREATE DATASET option appear like this. Click the link." }, { "code": null, "e": 2787, "s": 2691, "text": "3. Enter “blog_unnest” as the dataset name, and leave all other defaults. Click Create Dataset." }, { "code": null, "e": 2960, "s": 2787, "text": "Now we have a dataset, we can create a table called firebase_raw that contains a sample (1,000 rows) of Firebase event data. To do this, simply run this in the BigQuery UI:" }, { "code": null, "e": 3129, "s": 2960, "text": "create table blog_unnest.firebase_rawasselect *from `firebase-public-project.analytics_153293282.events_20180801`where event_name = ‘level_complete_quickplay’limit 1000" }, { "code": null, "e": 3357, "s": 3129, "text": "Tip: Notice the Firebase to BigQuery export generates an events table that is sharded by the event date (in bold above). In this example, we are extracting data from shard 20180801, which contains all events seen on 1 Aug 2018." }, { "code": null, "e": 3476, "s": 3357, "text": "The limit keyword tells BigQuery to limit rows to 1,000. Like the top n feature if you come from an MS SQL background." }, { "code": null, "e": 3673, "s": 3476, "text": "With the sample data loaded, we can explore its structure. Clicking on the firebase_raw table, we see the columns listed. Note the event_params is of type RECORD — indicating it is a nested field." }, { "code": null, "e": 3744, "s": 3673, "text": "If we run the simple query below, we can see what the data looks like." }, { "code": null, "e": 3782, "s": 3744, "text": "select *from blog_unnest.firebase_raw" }, { "code": null, "e": 3991, "s": 3782, "text": "Event_params (highlighted) is a nested field, with each nested row representing a parameter for that event. We can see there are 5 nested rows for this “level complete quickplay” event, one row per parameter." }, { "code": null, "e": 4140, "s": 3991, "text": "In Firebase, typically each event needs its own unique set of supporting parameters, and you can see how storing them in this way makes it possible." }, { "code": null, "e": 4213, "s": 4140, "text": "Event_date is a regular column, indicating which day the event occurred." }, { "code": null, "e": 4303, "s": 4213, "text": "Event_timestamp represents a derivative of Unix time to denote when the event took place." }, { "code": null, "e": 4482, "s": 4303, "text": "Tip: Event_timestamp in Firebase denotes the number of microseconds since 1 Jan 1970. To convert this into a BigQuery timestamp, you can use BigQuery’s timestamp_micros function:" }, { "code": null, "e": 4587, "s": 4482, "text": "select timestamp_micros(event_timestamp) as event_ts, event_timestampfrom blog_unnest.firebase_raw" }, { "code": null, "e": 4668, "s": 4587, "text": "Which gives: 2018–08–01 13:45:54.159108 UTC for event_timestamp 1533131154159108" }, { "code": null, "e": 4771, "s": 4668, "text": "The UNNEST function allows us to easily query nested fields, such as the parameters in our event data." }, { "code": null, "e": 4837, "s": 4771, "text": "Suppose we want to flatten our event data into rows, and extract:" }, { "code": null, "e": 5004, "s": 4837, "text": "The event_timestampThe event_nameThe value from the nested params (the number of moves a player made)The board from the nested params (size of board played, S M or L)" }, { "code": null, "e": 5024, "s": 5004, "text": "The event_timestamp" }, { "code": null, "e": 5039, "s": 5024, "text": "The event_name" }, { "code": null, "e": 5108, "s": 5039, "text": "The value from the nested params (the number of moves a player made)" }, { "code": null, "e": 5174, "s": 5108, "text": "The board from the nested params (size of board played, S M or L)" }, { "code": null, "e": 5286, "s": 5174, "text": "The first two are easy. But the last two are more difficult. Here is where the UNNEST function comes into play:" }, { "code": null, "e": 5672, "s": 5286, "text": "select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, param_value.value.int_value as move_count, param_board.value.string_value as board_sizefrom blog_unnest.firebase_raw r cross join unnest(event_params) param_value cross join unnest(event_params) param_board where param_value.key = ‘value’and param_board.key = ‘board’" }, { "code": null, "e": 5711, "s": 5672, "text": "This produces the output that we want:" }, { "code": null, "e": 5734, "s": 5711, "text": "Let’s break this down." }, { "code": null, "e": 5778, "s": 5734, "text": "cross join unnest(event_params) param_value" }, { "code": null, "e": 6018, "s": 5778, "text": "UNNEST takes the rows in our nested event_params struct, unpacks these, and produces a table with a single struct for each row in the original event_params nested field. In our case, this nested field contained 5 rows per parent event row." }, { "code": null, "e": 6109, "s": 6018, "text": "The cross join applies a cartesian product of the 5 nested rows with the parent event row." }, { "code": null, "e": 6188, "s": 6109, "text": "The total row count returned is therefore 5,000 (5 parameters per 1,000 rows)." }, { "code": null, "e": 6402, "s": 6188, "text": "In our case, the first attribute we wanted to extract from event_params was the value. So, we alias our cross join unnest function call as param_value, and then add the following where clause to filter on the key:" }, { "code": null, "e": 6434, "s": 6402, "text": "where param_value.key = ‘value’" }, { "code": null, "e": 6606, "s": 6434, "text": "Remember, the rows in our param_value are themselves a struct. So, when we extract the int_value in the select clause, we need to use this notation to reference the value:" }, { "code": null, "e": 6662, "s": 6606, "text": "select param_value.value.int_value as move_count," }, { "code": null, "e": 6786, "s": 6662, "text": "Tip: if you want to select all the attributes in a struct, and not just the int_value as we did here, you can just do this:" }, { "code": null, "e": 6978, "s": 6786, "text": "select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, param_valuefrom blog_unnest.firebase_raw rcross join unnest(event_params) param_value" }, { "code": null, "e": 7128, "s": 6978, "text": "Which will add each attribute is a column in the result set. Useful if you want to explore structs where you don’t really know what the structure is:" }, { "code": null, "e": 7293, "s": 7128, "text": "There is another way to use the UNNEST function to achieve the same output as our previous example. We can use an inline select, instead of the multipe cross joins:" }, { "code": null, "e": 7760, "s": 7293, "text": "select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, ( select event_params.value.int_value from unnest(event_params) event_params where event_params.key = ‘value’ ) as move_count, ( select event_params.value.string_value from unnest(event_params) event_params where event_params.key = ‘board’ ) as board_sizefrom blog_unnest.firebase_raw r" }, { "code": null, "e": 7873, "s": 7760, "text": "One advantage of using the inline select approach over cross join, is it handles missing attributes much better." }, { "code": null, "e": 8111, "s": 7873, "text": "For example, say we want to bring back a third attribute, “foo”, from the event_params. This parameter only applies to certain events, and if it is missing, we still want our other data returned. Note foo does not exist in our test data." }, { "code": null, "e": 8141, "s": 8111, "text": "Modifying the first approach:" }, { "code": null, "e": 8642, "s": 8141, "text": "select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, param_value.value.int_value as move_count, param_board.value.string_value as board_size, param_foo.value.int_value as foo from blog_unnest.firebase_raw r cross join unnest(event_params) param_value cross join unnest(event_params) param_board cross join unnest(event_params) param_foo where param_value.key = ‘value’and param_board.key = ‘board’and param_foo.key = ‘foo’" }, { "code": null, "e": 8804, "s": 8642, "text": "Running this returns 0 rows. This is because, in a similar way to how applying a where clause limits rows to a left outer join, the same applies to a cross join." }, { "code": null, "e": 8853, "s": 8804, "text": "However, if we amend our inline select approach:" }, { "code": null, "e": 9446, "s": 8853, "text": "select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, ( select event_params.value.int_value from unnest(event_params) event_params where event_params.key = ‘value’ ) as move_count, ( select event_params.value.string_value from unnest(event_params) event_params where event_params.key = ‘board’ ) as board_size, ( select event_params.value.string_value from unnest(event_params) event_params where event_params.key = ‘foo’ ) as foofrom blog_unnest.firebase_raw r" }, { "code": null, "e": 9537, "s": 9446, "text": "This time, we get our expected result; rows returned with the foo column containing nulls." }, { "code": null, "e": 9758, "s": 9537, "text": "In some ways, this approach is also easier to read and is easier to add additional attributes because only the select clause needs to be modified. In terms of the amount of data scanned, the two approaches are identical." }, { "code": null, "e": 9966, "s": 9758, "text": "Tip: as a general rule we try to avoid inline selects as joins are typically more performant; however in this use case, the performance is identical and we would typically opt for the inline select approach." }, { "code": null, "e": 10104, "s": 9966, "text": "Lastly, we show you how to convert a data type (or do other manipulations) to nested data whilst maintaining the data in its nested form." }, { "code": null, "e": 10190, "s": 10104, "text": "Again, we use the BigQuery UNNEST function to achieve this. The basic approach is to:" }, { "code": null, "e": 10351, "s": 10190, "text": "Call UNNEST to unpack the nested dataApply cast function (or other data manipulation)Reconstruct the structure using the ARRAY and STRUCT datatypes accordingly." }, { "code": null, "e": 10389, "s": 10351, "text": "Call UNNEST to unpack the nested data" }, { "code": null, "e": 10438, "s": 10389, "text": "Apply cast function (or other data manipulation)" }, { "code": null, "e": 10514, "s": 10438, "text": "Reconstruct the structure using the ARRAY and STRUCT datatypes accordingly." }, { "code": null, "e": 10834, "s": 10514, "text": "Keeping with the Firebase event data, in the user_properties nested field we find another timestamp attribute called set_timestamp_micros that is again in the Unix like format and therefore difficult to read. We want to apply a timestamp_micros() function to this attribute, converting it to a human-readable timestamp." }, { "code": null, "e": 10916, "s": 10834, "text": "We can achieve this using the following combination of UNNEST, ARRAY, and STRUCT:" }, { "code": null, "e": 11600, "s": 10916, "text": "select timestamp_micros(event_timestamp) as event_ts, event_name, event_timestamp, array( select struct( user_properties.key, struct( user_properties.value.string_value, user_properties.value.int_value, user_properties.value.float_value, user_properties.value.double_value, timestamp_micros ( user_properties.value.set_timestamp_micros ) as set_timestamp_micros ) as value ) from unnest(user_properties) user_properties ) as user_propertiesfrom blog_unnest.firebase_raw r" }, { "code": null, "e": 11769, "s": 11600, "text": "If you take the time to understand the above, you should be well on your way to mastering the UNNEST function and working with Firebase, and other semi-structured data." }, { "code": null, "e": 12052, "s": 11769, "text": "As we have seen, BigQuery is really flexible in that it can store both structured and semi-structured data via its support for nested data types. This lends itself really well for analysing and applying machine learning activities on event data, which is inherently semi-structured." }, { "code": null, "e": 12341, "s": 12052, "text": "The notation in BigQuery for working with nested data does have a bit of a learning curve, and this was partly the motivation for writing this article — to help fellow data scientists and analysts who might be faced with this challenge to see a working example complete with explanations." }, { "code": null, "e": 12519, "s": 12341, "text": "We specifically hope those of you who are working with Firebase event data (a very common use case in the field), will find this helpful and should hopefully save you some time!" }, { "code": null, "e": 12606, "s": 12519, "text": "You can read the official Google Cloud documentation on working with nested data here." }, { "code": null, "e": 12693, "s": 12606, "text": "You can read the official Google Cloud documentation on working with nested data here." } ]
\enspace - Tex Command
\enspace - Used to add 0.5 em space. { \enspace } \enspace command adds 0.5 em space. |\enspace|\enspace| ||| |\enspace|\enspace| ||| |\enspace|\enspace| 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8023, "s": 7986, "text": "\\enspace - Used to add 0.5 em space." }, { "code": null, "e": 8036, "s": 8023, "text": "{ \\enspace }" }, { "code": null, "e": 8072, "s": 8036, "text": "\\enspace command adds 0.5 em space." }, { "code": null, "e": 8101, "s": 8072, "text": "\n|\\enspace|\\enspace|\n\n|||\n\n\n" }, { "code": null, "e": 8128, "s": 8101, "text": "|\\enspace|\\enspace|\n\n|||\n\n" }, { "code": null, "e": 8148, "s": 8128, "text": "|\\enspace|\\enspace|" }, { "code": null, "e": 8180, "s": 8148, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8193, "s": 8180, "text": " Ashraf Said" }, { "code": null, "e": 8226, "s": 8193, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8239, "s": 8226, "text": " Ashraf Said" }, { "code": null, "e": 8271, "s": 8239, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8307, "s": 8271, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8342, "s": 8307, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8359, "s": 8342, "text": " Mohammad Nauman" }, { "code": null, "e": 8392, "s": 8359, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8406, "s": 8392, "text": " Daniel Stern" }, { "code": null, "e": 8438, "s": 8406, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8453, "s": 8438, "text": " Nishant Kumar" }, { "code": null, "e": 8460, "s": 8453, "text": " Print" }, { "code": null, "e": 8471, "s": 8460, "text": " Add Notes" } ]
Plotting graph using Seaborn | Python
09 May, 2022 This article will introduce you to graphing in Python with Seaborn, which is the most popular statistical visualization library in Python. Installation: The easiest way to install seaborn is to use pip. Type following command in terminal: pip install seaborn OR, you can download it from here and install it manually. Plotting categorical scatter plots with Seaborn Python3 # Python program to illustrate# Plotting categorical scatter# plots with Seaborn # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # x axis valuesx =['sun', 'mon', 'fri', 'sat', 'tue', 'wed', 'thu'] # y axis valuesy =[5, 6.7, 4, 6, 2, 4.9, 1.8] # plotting strip plot with seabornax = sns.stripplot(x, y); # giving labels to x-axis and y-axisax.set(xlabel ='Days', ylabel ='Amount_spend') # giving title to the plotplt.title('My first graph'); # function to show plotplt.show() Output: Explanation: This is the one kind of scatter plot of categorical data with the help of seaborn. Categorical data is represented on the x-axis and values correspond to them represented through the y-axis. .striplot() function is used to define the type of the plot and to plot them on canvas using. .set() function is used to set labels of x-axis and y-axis. .title() function is used to give a title to the graph. To view plot we use .show() function. Stripplot using inbuilt data-set given in seaborn : Python3 # Python program to illustrate# Stripplot using inbuilt data-set# given in seaborn # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # use to set style of background of plotsns.set(style="whitegrid") # loading data-setiris = sns.load_dataset('iris') # plotting strip plot with seaborn# deciding the attributes of dataset on# which plot should be madeax = sns.stripplot(x='species', y='sepal_length', data=iris) # giving title to the plotplt.title('Graph') # function to show plotplt.show() Output: Explanation: iris is the dataset already present in seaborn module for use. We use .load_dataset() function in order to load the data.We can also load any other file by giving the path and name of the file in the argument. .set(style=”whitegrid”) function here is also use to define the background of plot.We can use “darkgrid” instead of whitegrid if we want the dark-colored background. In .stripplot() function we have to define which attribute of the dataset to be on the x-axis and which attribute of the dataset should on y-axis.data = iris means attributes which we define earlier should be taken from the given data. We can also draw this plot with matplotlib but the problem with matplotlib is its default parameters. The reason why Seaborn is so great with DataFrames is, for example, labels from DataFrames are automatically propagated to plots or other data structures as you see in the above figure column name species comes on the x-axis and column name stepal_length comes on the y-axis, that is not possible with matplotlib. We have to explicitly define the labels of the x-axis and y-axis. Python3 # Python program to illustrate# plotting using Swarmplot # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # use to set style of background of plotsns.set(style="whitegrid") # loading data-setiris = sns.load_dataset('iris') # plotting strip plot with seaborn# deciding the attributes of dataset on# which plot should be madeax = sns.swarmplot(x='species', y='sepal_length', data=iris) # giving title to the plotplt.title('Graph') # function to show plotplt.show() Output: Explanation: This is very much similar to stripplot but the only difference is that it does not allow overlapping of markers. It causes jittering in the markers of the plot so that graph can easily be read without information loss as seen in the above plot. We use .swarmplot() function to plot swarm plot. Another difference that we can notice in Seaborn and Matplotlib is that working with DataFrames doesn’t go quite as smoothly with Matplotlib, which can be annoying if we doing exploratory analysis with Pandas. And that’s exactly what Seaborn does easily, the plotting functions operate on DataFrames and arrays that contain a whole dataset. Note: If we want we can also change the representation of data on a particular axis. Example : Python3 # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # use to set style of background of plotsns.set(style="whitegrid") # loading data-setiris = sns.load_dataset('iris') # plotting strip plot with seaborn# deciding the attributes of dataset on# which plot should be madeax = sns.swarmplot(x='sepal_length', y='species', data=iris) # giving title to the plotplt.title('Graph') # function to show plotplt.show() Output: The same can be done in striplot. At last, we can say that Seaborn is an extended version of matplotlib which tries to make a well-defined set of hard things easy. A barplot is basically used to aggregate the categorical data according to some methods and by default it’s the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x-axis and a numerical column for the y-axis, and we see that it creates a plot taking a mean per categorical column. Syntax: barplot([x, y, hue, data, order, hue_order, ...]) Python3 # import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips') # change the estimator from mean to# standard deviationsns.barplot(x ='sex', y ='total_bill', data = df, palette ='plasma') Output: Explanation:Looking at the plot we can say that the average total_bill for the male is more than compared to the female. Palette is used to set the color of the plot The estimator is used as a statistical function for estimation within each categorical bin. A countplot basically counts the categories and returns a count of their occurrences. It is one of the simplest plots provided by the seaborn library. Syntax: countplot([x, y, hue, data, order, ...]) Python3 # import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips') sns.countplot(x ='sex', data = df) Output: Explanation: Looking at the plot we can say that the number of males is more than the number of females in the dataset. As it only returns the count based on a categorical column, we need to specify only the x parameter. Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used to detect the outlier in the data set. Syntax: boxplot([x, y, hue, data, order, hue_order, ...]) Python3 # import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips') sns.boxplot(x='day', y='total_bill', data=df, hue='smoker') Output: Explanation: x takes the categorical column and y is a numerical column. Hence we can see the total bill spent each day.” hue” parameter is used to further add a categorical separation. By looking at the plot we can say that the people who do not smoke had a higher bill on Friday as compared to the people who smoked. It is similar to the boxplot except that it provides a higher, more advanced visualization and uses the kernel density estimation to give a better description about the data distribution. Syntax: violinplot([x, y, hue, data, order, ...]) Python3 # import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips')sns.violinplot(x='day', y='total_bill', data=df, hue='sex', split=True) Output: Explanation: hue is used to separate the data further using the sex category setting split=True will draw half of a violin for each level. This can make it easier to directly compare the distributions. It basically creates a scatter plot based on the category. Syntax: stripplot([x, y, hue, data, order, ...]) Python3 # import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips')sns.stripplot(x='day', y='total_bill', data=df, jitter=True, hue='smoker', dodge=True) Output: Explanation: One problem with strip plot is that you can’t really tell which points are stacked on top of each other and hence we use the jitter parameter to add some random noise. jitter parameter is used to add an amount of jitter (only along the categorical axis) which can be useful when you have many points and they overlap so that it is easier to see the distribution. hue is used to provide an additional categorical separation setting split=True is used to draw separate strip plots based on the category specified by the hue parameter. kumar_satyam sagartomar9927 sagar0719kumar simmytarika5 GBlog Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ... GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial Naive Bayes Classifiers ML | Linear Regression Reinforcement learning Linear Regression (Python Implementation) Agents in Artificial Intelligence
[ { "code": null, "e": 52, "s": 24, "text": "\n09 May, 2022" }, { "code": null, "e": 191, "s": 52, "text": "This article will introduce you to graphing in Python with Seaborn, which is the most popular statistical visualization library in Python." }, { "code": null, "e": 293, "s": 191, "text": "Installation: The easiest way to install seaborn is to use pip. Type following command in terminal: " }, { "code": null, "e": 313, "s": 293, "text": "pip install seaborn" }, { "code": null, "e": 374, "s": 313, "text": "OR, you can download it from here and install it manually. " }, { "code": null, "e": 422, "s": 374, "text": "Plotting categorical scatter plots with Seaborn" }, { "code": null, "e": 430, "s": 422, "text": "Python3" }, { "code": "# Python program to illustrate# Plotting categorical scatter# plots with Seaborn # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # x axis valuesx =['sun', 'mon', 'fri', 'sat', 'tue', 'wed', 'thu'] # y axis valuesy =[5, 6.7, 4, 6, 2, 4.9, 1.8] # plotting strip plot with seabornax = sns.stripplot(x, y); # giving labels to x-axis and y-axisax.set(xlabel ='Days', ylabel ='Amount_spend') # giving title to the plotplt.title('My first graph'); # function to show plotplt.show()", "e": 941, "s": 430, "text": null }, { "code": null, "e": 949, "s": 941, "text": "Output:" }, { "code": null, "e": 1047, "s": 949, "text": "Explanation: This is the one kind of scatter plot of categorical data with the help of seaborn. " }, { "code": null, "e": 1155, "s": 1047, "text": "Categorical data is represented on the x-axis and values correspond to them represented through the y-axis." }, { "code": null, "e": 1249, "s": 1155, "text": ".striplot() function is used to define the type of the plot and to plot them on canvas using." }, { "code": null, "e": 1309, "s": 1249, "text": ".set() function is used to set labels of x-axis and y-axis." }, { "code": null, "e": 1365, "s": 1309, "text": ".title() function is used to give a title to the graph." }, { "code": null, "e": 1403, "s": 1365, "text": "To view plot we use .show() function." }, { "code": null, "e": 1456, "s": 1403, "text": "Stripplot using inbuilt data-set given in seaborn : " }, { "code": null, "e": 1464, "s": 1456, "text": "Python3" }, { "code": "# Python program to illustrate# Stripplot using inbuilt data-set# given in seaborn # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # use to set style of background of plotsns.set(style=\"whitegrid\") # loading data-setiris = sns.load_dataset('iris') # plotting strip plot with seaborn# deciding the attributes of dataset on# which plot should be madeax = sns.stripplot(x='species', y='sepal_length', data=iris) # giving title to the plotplt.title('Graph') # function to show plotplt.show()", "e": 1988, "s": 1464, "text": null }, { "code": null, "e": 1997, "s": 1988, "text": "Output: " }, { "code": null, "e": 2010, "s": 1997, "text": "Explanation:" }, { "code": null, "e": 2073, "s": 2010, "text": "iris is the dataset already present in seaborn module for use." }, { "code": null, "e": 2220, "s": 2073, "text": "We use .load_dataset() function in order to load the data.We can also load any other file by giving the path and name of the file in the argument." }, { "code": null, "e": 2386, "s": 2220, "text": ".set(style=”whitegrid”) function here is also use to define the background of plot.We can use “darkgrid” instead of whitegrid if we want the dark-colored background." }, { "code": null, "e": 2622, "s": 2386, "text": "In .stripplot() function we have to define which attribute of the dataset to be on the x-axis and which attribute of the dataset should on y-axis.data = iris means attributes which we define earlier should be taken from the given data." }, { "code": null, "e": 3104, "s": 2622, "text": "We can also draw this plot with matplotlib but the problem with matplotlib is its default parameters. The reason why Seaborn is so great with DataFrames is, for example, labels from DataFrames are automatically propagated to plots or other data structures as you see in the above figure column name species comes on the x-axis and column name stepal_length comes on the y-axis, that is not possible with matplotlib. We have to explicitly define the labels of the x-axis and y-axis." }, { "code": null, "e": 3112, "s": 3104, "text": "Python3" }, { "code": "# Python program to illustrate# plotting using Swarmplot # importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # use to set style of background of plotsns.set(style=\"whitegrid\") # loading data-setiris = sns.load_dataset('iris') # plotting strip plot with seaborn# deciding the attributes of dataset on# which plot should be madeax = sns.swarmplot(x='species', y='sepal_length', data=iris) # giving title to the plotplt.title('Graph') # function to show plotplt.show()", "e": 3610, "s": 3112, "text": null }, { "code": null, "e": 3619, "s": 3610, "text": "Output: " }, { "code": null, "e": 3879, "s": 3619, "text": "Explanation: This is very much similar to stripplot but the only difference is that it does not allow overlapping of markers. It causes jittering in the markers of the plot so that graph can easily be read without information loss as seen in the above plot. " }, { "code": null, "e": 3928, "s": 3879, "text": "We use .swarmplot() function to plot swarm plot." }, { "code": null, "e": 4269, "s": 3928, "text": "Another difference that we can notice in Seaborn and Matplotlib is that working with DataFrames doesn’t go quite as smoothly with Matplotlib, which can be annoying if we doing exploratory analysis with Pandas. And that’s exactly what Seaborn does easily, the plotting functions operate on DataFrames and arrays that contain a whole dataset." }, { "code": null, "e": 4355, "s": 4269, "text": "Note: If we want we can also change the representation of data on a particular axis. " }, { "code": null, "e": 4366, "s": 4355, "text": "Example : " }, { "code": null, "e": 4374, "s": 4366, "text": "Python3" }, { "code": "# importing the required moduleimport matplotlib.pyplot as pltimport seaborn as sns # use to set style of background of plotsns.set(style=\"whitegrid\") # loading data-setiris = sns.load_dataset('iris') # plotting strip plot with seaborn# deciding the attributes of dataset on# which plot should be madeax = sns.swarmplot(x='sepal_length', y='species', data=iris) # giving title to the plotplt.title('Graph') # function to show plotplt.show()", "e": 4816, "s": 4374, "text": null }, { "code": null, "e": 4825, "s": 4816, "text": "Output: " }, { "code": null, "e": 4989, "s": 4825, "text": "The same can be done in striplot. At last, we can say that Seaborn is an extended version of matplotlib which tries to make a well-defined set of hard things easy." }, { "code": null, "e": 5350, "s": 4989, "text": "A barplot is basically used to aggregate the categorical data according to some methods and by default it’s the mean. It can also be understood as a visualization of the group by action. To use this plot we choose a categorical column for the x-axis and a numerical column for the y-axis, and we see that it creates a plot taking a mean per categorical column." }, { "code": null, "e": 5358, "s": 5350, "text": "Syntax:" }, { "code": null, "e": 5408, "s": 5358, "text": "barplot([x, y, hue, data, order, hue_order, ...])" }, { "code": null, "e": 5416, "s": 5408, "text": "Python3" }, { "code": "# import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips') # change the estimator from mean to# standard deviationsns.barplot(x ='sex', y ='total_bill', data = df, palette ='plasma')", "e": 5653, "s": 5416, "text": null }, { "code": null, "e": 5661, "s": 5653, "text": "Output:" }, { "code": null, "e": 5782, "s": 5661, "text": "Explanation:Looking at the plot we can say that the average total_bill for the male is more than compared to the female." }, { "code": null, "e": 5827, "s": 5782, "text": "Palette is used to set the color of the plot" }, { "code": null, "e": 5919, "s": 5827, "text": "The estimator is used as a statistical function for estimation within each categorical bin." }, { "code": null, "e": 6070, "s": 5919, "text": "A countplot basically counts the categories and returns a count of their occurrences. It is one of the simplest plots provided by the seaborn library." }, { "code": null, "e": 6078, "s": 6070, "text": "Syntax:" }, { "code": null, "e": 6119, "s": 6078, "text": "countplot([x, y, hue, data, order, ...])" }, { "code": null, "e": 6127, "s": 6119, "text": "Python3" }, { "code": "# import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips') sns.countplot(x ='sex', data = df)", "e": 6263, "s": 6127, "text": null }, { "code": null, "e": 6271, "s": 6263, "text": "Output:" }, { "code": null, "e": 6284, "s": 6271, "text": "Explanation:" }, { "code": null, "e": 6492, "s": 6284, "text": "Looking at the plot we can say that the number of males is more than the number of females in the dataset. As it only returns the count based on a categorical column, we need to specify only the x parameter." }, { "code": null, "e": 6657, "s": 6492, "text": "Box Plot is the visual representation of the depicting groups of numerical data through their quartiles. Boxplot is also used to detect the outlier in the data set." }, { "code": null, "e": 6665, "s": 6657, "text": "Syntax:" }, { "code": null, "e": 6715, "s": 6665, "text": "boxplot([x, y, hue, data, order, hue_order, ...])" }, { "code": null, "e": 6723, "s": 6715, "text": "Python3" }, { "code": "# import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips') sns.boxplot(x='day', y='total_bill', data=df, hue='smoker')", "e": 6884, "s": 6723, "text": null }, { "code": null, "e": 6892, "s": 6884, "text": "Output:" }, { "code": null, "e": 6905, "s": 6892, "text": "Explanation:" }, { "code": null, "e": 7211, "s": 6905, "text": "x takes the categorical column and y is a numerical column. Hence we can see the total bill spent each day.” hue” parameter is used to further add a categorical separation. By looking at the plot we can say that the people who do not smoke had a higher bill on Friday as compared to the people who smoked." }, { "code": null, "e": 7399, "s": 7211, "text": "It is similar to the boxplot except that it provides a higher, more advanced visualization and uses the kernel density estimation to give a better description about the data distribution." }, { "code": null, "e": 7407, "s": 7399, "text": "Syntax:" }, { "code": null, "e": 7449, "s": 7407, "text": "violinplot([x, y, hue, data, order, ...])" }, { "code": null, "e": 7457, "s": 7449, "text": "Python3" }, { "code": "# import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips')sns.violinplot(x='day', y='total_bill', data=df, hue='sex', split=True)", "e": 7643, "s": 7457, "text": null }, { "code": null, "e": 7651, "s": 7643, "text": "Output:" }, { "code": null, "e": 7664, "s": 7651, "text": "Explanation:" }, { "code": null, "e": 7728, "s": 7664, "text": "hue is used to separate the data further using the sex category" }, { "code": null, "e": 7853, "s": 7728, "text": "setting split=True will draw half of a violin for each level. This can make it easier to directly compare the distributions." }, { "code": null, "e": 7912, "s": 7853, "text": "It basically creates a scatter plot based on the category." }, { "code": null, "e": 7920, "s": 7912, "text": "Syntax:" }, { "code": null, "e": 7961, "s": 7920, "text": "stripplot([x, y, hue, data, order, ...])" }, { "code": null, "e": 7969, "s": 7961, "text": "Python3" }, { "code": "# import the seaborn libraryimport seaborn as sns # reading the datasetdf = sns.load_dataset('tips')sns.stripplot(x='day', y='total_bill', data=df, jitter=True, hue='smoker', dodge=True)", "e": 8169, "s": 7969, "text": null }, { "code": null, "e": 8177, "s": 8169, "text": "Output:" }, { "code": null, "e": 8190, "s": 8177, "text": "Explanation:" }, { "code": null, "e": 8358, "s": 8190, "text": "One problem with strip plot is that you can’t really tell which points are stacked on top of each other and hence we use the jitter parameter to add some random noise." }, { "code": null, "e": 8553, "s": 8358, "text": "jitter parameter is used to add an amount of jitter (only along the categorical axis) which can be useful when you have many points and they overlap so that it is easier to see the distribution." }, { "code": null, "e": 8613, "s": 8553, "text": "hue is used to provide an additional categorical separation" }, { "code": null, "e": 8723, "s": 8613, "text": "setting split=True is used to draw separate strip plots based on the category specified by the hue parameter." }, { "code": null, "e": 8736, "s": 8723, "text": "kumar_satyam" }, { "code": null, "e": 8751, "s": 8736, "text": "sagartomar9927" }, { "code": null, "e": 8766, "s": 8751, "text": "sagar0719kumar" }, { "code": null, "e": 8779, "s": 8766, "text": "simmytarika5" }, { "code": null, "e": 8785, "s": 8779, "text": "GBlog" }, { "code": null, "e": 8802, "s": 8785, "text": "Machine Learning" }, { "code": null, "e": 8809, "s": 8802, "text": "Python" }, { "code": null, "e": 8826, "s": 8809, "text": "Machine Learning" }, { "code": null, "e": 8924, "s": 8826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8949, "s": 8924, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 9023, "s": 8949, "text": "Must Do Coding Questions for Companies like Amazon, Microsoft, Adobe, ..." }, { "code": null, "e": 9078, "s": 9023, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 9115, "s": 9078, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 9153, "s": 9115, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 9177, "s": 9153, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 9200, "s": 9177, "text": "ML | Linear Regression" }, { "code": null, "e": 9223, "s": 9200, "text": "Reinforcement learning" }, { "code": null, "e": 9265, "s": 9223, "text": "Linear Regression (Python Implementation)" } ]
Sum of list with stream filter in Java
15 May, 2021 We generally iterate through the list when adding integers in a range, but java.util.stream.Stream has a sum() method that when used with filter() gives the required result easily. Java // Simple method (without filter) to find sum of a listimport java.util.*; class Addition { public static void main(String[] args) { // create a list of integers List<Integer> list = new ArrayList<Integer>(); // add elements to the list list.add(1); list.add(5); list.add(6); list.add(7); list.add(8); list.add(9); list.add(10); System.out.println(sum(list)); } public static int sum(List<Integer> list) { // iterator for accessing the elements Iterator<Integer> it = list.iterator(); int res = 0; while (it.hasNext()) { int num = it.next(); // adding the elements greater than 5 if (num > 5) { res += num; } } return res; }} 40 The above task can be easily performed using sum() method with filter() method Java // Using stream filter to find sum of a listimport java.util.*; class Addition { public static void main(String[] args) { // create a list of integers List<Integer> list = new ArrayList<Integer>(); // add elements to the list list.add(1); list.add(5); list.add(6); list.add(7); list.add(8); list.add(9); list.add(10); System.out.println(sum(list)); } public static int sum(List<Integer> list) { // create a stream of integers // filter the stream // add the integers return list.stream() .filter(i -> i > 5) .mapToInt(i -> i) .sum(); }} 40 Stefan Vlahov Java-ArrayList java-list Java-List-Programs java-stream Java-Stream-programs Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n15 May, 2021" }, { "code": null, "e": 235, "s": 54, "text": "We generally iterate through the list when adding integers in a range, but java.util.stream.Stream has a sum() method that when used with filter() gives the required result easily." }, { "code": null, "e": 240, "s": 235, "text": "Java" }, { "code": "// Simple method (without filter) to find sum of a listimport java.util.*; class Addition { public static void main(String[] args) { // create a list of integers List<Integer> list = new ArrayList<Integer>(); // add elements to the list list.add(1); list.add(5); list.add(6); list.add(7); list.add(8); list.add(9); list.add(10); System.out.println(sum(list)); } public static int sum(List<Integer> list) { // iterator for accessing the elements Iterator<Integer> it = list.iterator(); int res = 0; while (it.hasNext()) { int num = it.next(); // adding the elements greater than 5 if (num > 5) { res += num; } } return res; }}", "e": 1068, "s": 240, "text": null }, { "code": null, "e": 1071, "s": 1068, "text": "40" }, { "code": null, "e": 1154, "s": 1073, "text": "The above task can be easily performed using sum() method with filter() method " }, { "code": null, "e": 1159, "s": 1154, "text": "Java" }, { "code": "// Using stream filter to find sum of a listimport java.util.*; class Addition { public static void main(String[] args) { // create a list of integers List<Integer> list = new ArrayList<Integer>(); // add elements to the list list.add(1); list.add(5); list.add(6); list.add(7); list.add(8); list.add(9); list.add(10); System.out.println(sum(list)); } public static int sum(List<Integer> list) { // create a stream of integers // filter the stream // add the integers return list.stream() .filter(i -> i > 5) .mapToInt(i -> i) .sum(); }}", "e": 1855, "s": 1159, "text": null }, { "code": null, "e": 1858, "s": 1855, "text": "40" }, { "code": null, "e": 1874, "s": 1860, "text": "Stefan Vlahov" }, { "code": null, "e": 1889, "s": 1874, "text": "Java-ArrayList" }, { "code": null, "e": 1899, "s": 1889, "text": "java-list" }, { "code": null, "e": 1918, "s": 1899, "text": "Java-List-Programs" }, { "code": null, "e": 1930, "s": 1918, "text": "java-stream" }, { "code": null, "e": 1951, "s": 1930, "text": "Java-Stream-programs" }, { "code": null, "e": 1956, "s": 1951, "text": "Java" }, { "code": null, "e": 1961, "s": 1956, "text": "Java" } ]
GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 42 - GeeksforGeeks
26 Dec, 2019 A computer system uses 16-bit memory addresses. It has a 2K-byte cache organized in a direct-mapped manner with 64 bytes per cache block. Assume that the size of each memory word is 1 byte. When a program is executed, the processor reads data sequentially from the following word addresses: 128, 144, 2176, 2180, 128, 2176 All the above addresses are shown in decimal values. Assume that the cache is initially empty. The cache hits ratio occur for for above given addresses is __________ .(A) 0.333(B) 0.666(C) 0.353(D) 0.535Answer: (A)Explanation: First, find word, block and tag size:Block size = 64 bytes = 26 bytes = 26 words (since 1 word = 1 byte)Therefore, Number of bits in the Word field = 6 Cache size = 2K-byte = 211 bytesNumber of cache blocks = Cache size / Block size = 211/26 = 25Therefore, Number of bits in the Block field = 5Total number of address bits = 16Therefore, Number of bits in the Tag field = 16 – 6 – 5 = 5For a given 16-bit address, the 5 most significant bits, represent the Tag, the next 5 bits represent the Block, and the 6 least significant bits represent the Word. Now, check cache hit or miss for given addresses:The cache is initially empty. Therefore, all the cache blocks are invalid. Access # 2:Address = (144)10 = (0000000010010000)2For this address, Tag = 00000, Block = 00010, Word = 010000Since tag field for cache block 00010 is 00000 before this access, this will be a cache hit (becauseaddress tag = block tag) Access # 3:Address = (2176)10 = (0000100010000000)2For this address, Tag = 00001, Block = 00010, Word = 000000Since tag field for cache block 00010 is 00000 before this access, this will be a cache miss(address tag ≠ block tag)After this access, Tag field for cache block 00010 is set to 00001 Access # 4:Address = (2180)10 = (0000100010000100)2For this address, Tag = 00001, Block = 00010, Word = 000100Since tag field for cache block 00010 is 00001 before this access, this will be a cache hit (addresstag = block tag) Access # 5:Address = (128)10 = (0000000010000000)2For this address, Tag = 00000, Block = 00010, Word = 000000Since tag field for cache block 00010 is 00001 before this access, this will be a cache miss(address tag ≠ block tag)After this access, Tag field for cache block 00010 is set to 00000 Access # 6:Address = (2176)10 = (0000100010000000)2For this address, Tag = 00001, Block = 00010, Word = 000000Since tag field for cache block 00010 is 00001 before this access, this will be a cache miss(address tag ≠ block tag)After this access, Tag field for cache block 00010 is set to 00001 Therefore, cache hit rate = Number of hits / Number of accesses = 2/6 = 0.333. Option (A) is true.Quiz of this Question GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE-CS-2006 | Question 47 GATE | GATE MOCK 2017 | Question 24 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n26 Dec, 2019" }, { "code": null, "e": 25885, "s": 25695, "text": "A computer system uses 16-bit memory addresses. It has a 2K-byte cache organized in a direct-mapped manner with 64 bytes per cache block. Assume that the size of each memory word is 1 byte." }, { "code": null, "e": 25986, "s": 25885, "text": "When a program is executed, the processor reads data sequentially from the following word addresses:" }, { "code": null, "e": 26019, "s": 25986, "text": "128, 144, 2176, 2180, 128, 2176 " }, { "code": null, "e": 26398, "s": 26019, "text": "All the above addresses are shown in decimal values. Assume that the cache is initially empty. The cache hits ratio occur for for above given addresses is __________ .(A) 0.333(B) 0.666(C) 0.353(D) 0.535Answer: (A)Explanation: First, find word, block and tag size:Block size = 64 bytes = 26 bytes = 26 words (since 1 word = 1 byte)Therefore, Number of bits in the Word field = 6" }, { "code": null, "e": 26798, "s": 26398, "text": "Cache size = 2K-byte = 211 bytesNumber of cache blocks = Cache size / Block size = 211/26 = 25Therefore, Number of bits in the Block field = 5Total number of address bits = 16Therefore, Number of bits in the Tag field = 16 – 6 – 5 = 5For a given 16-bit address, the 5 most significant bits, represent the Tag, the next 5 bits represent the Block, and the 6 least significant bits represent the Word." }, { "code": null, "e": 26922, "s": 26798, "text": "Now, check cache hit or miss for given addresses:The cache is initially empty. Therefore, all the cache blocks are invalid." }, { "code": null, "e": 27156, "s": 26922, "text": "Access # 2:Address = (144)10 = (0000000010010000)2For this address, Tag = 00000, Block = 00010, Word = 010000Since tag field for cache block 00010 is 00000 before this access, this will be a cache hit (becauseaddress tag = block tag)" }, { "code": null, "e": 27451, "s": 27156, "text": "Access # 3:Address = (2176)10 = (0000100010000000)2For this address, Tag = 00001, Block = 00010, Word = 000000Since tag field for cache block 00010 is 00000 before this access, this will be a cache miss(address tag ≠ block tag)After this access, Tag field for cache block 00010 is set to 00001" }, { "code": null, "e": 27678, "s": 27451, "text": "Access # 4:Address = (2180)10 = (0000100010000100)2For this address, Tag = 00001, Block = 00010, Word = 000100Since tag field for cache block 00010 is 00001 before this access, this will be a cache hit (addresstag = block tag)" }, { "code": null, "e": 27972, "s": 27678, "text": "Access # 5:Address = (128)10 = (0000000010000000)2For this address, Tag = 00000, Block = 00010, Word = 000000Since tag field for cache block 00010 is 00001 before this access, this will be a cache miss(address tag ≠ block tag)After this access, Tag field for cache block 00010 is set to 00000" }, { "code": null, "e": 28267, "s": 27972, "text": "Access # 6:Address = (2176)10 = (0000100010000000)2For this address, Tag = 00001, Block = 00010, Word = 000000Since tag field for cache block 00010 is 00001 before this access, this will be a cache miss(address tag ≠ block tag)After this access, Tag field for cache block 00010 is set to 00001" }, { "code": null, "e": 28346, "s": 28267, "text": "Therefore, cache hit rate = Number of hits / Number of accesses = 2/6 = 0.333." }, { "code": null, "e": 28387, "s": 28346, "text": "Option (A) is true.Quiz of this Question" }, { "code": null, "e": 28392, "s": 28387, "text": "GATE" }, { "code": null, "e": 28490, "s": 28392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28524, "s": 28490, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 28558, "s": 28524, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 28592, "s": 28558, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 28625, "s": 28592, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 28661, "s": 28625, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 28695, "s": 28661, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 28731, "s": 28695, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 28765, "s": 28731, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 28799, "s": 28765, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Convert a UTF8 value to Integer in R Programming - utf8ToInt() Function - GeeksforGeeks
16 Jun, 2020 utf8ToInt() function in R Language is used to convert a UTF8 value to an integer value. Syntax: utf8ToInt(x, multiple) Parameters:x: Integer or integer vectormultiple: Boolean value to convert into single or multiple strings Example 1: # R program to convert a UTF8 to Integer # Calling the utf8ToInt() functionutf8ToInt("[")utf8ToInt("+")utf8ToInt(":") Output: [1] 91 [1] 43 [1] 58 Example 2: # R program to convert a UTF8 to Integer # Creating a vectorx1 <- c("&@\n")x2 <- c("[+:")x3 <- c("1d<U>") # Calling the utf8ToInt() functionutf8ToInt(x1)utf8ToInt(x2)utf8ToInt(x3) Output: [1] 38 64 10 [1] 91 43 58 [1] 49 100 60 85 62 R Math-Function 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? R - if statement How to filter R dataframe by multiple conditions? Plot mean and standard deviation using ggplot2 in R How to import an Excel File into R ?
[ { "code": null, "e": 26487, "s": 26459, "text": "\n16 Jun, 2020" }, { "code": null, "e": 26575, "s": 26487, "text": "utf8ToInt() function in R Language is used to convert a UTF8 value to an integer value." }, { "code": null, "e": 26606, "s": 26575, "text": "Syntax: utf8ToInt(x, multiple)" }, { "code": null, "e": 26712, "s": 26606, "text": "Parameters:x: Integer or integer vectormultiple: Boolean value to convert into single or multiple strings" }, { "code": null, "e": 26723, "s": 26712, "text": "Example 1:" }, { "code": "# R program to convert a UTF8 to Integer # Calling the utf8ToInt() functionutf8ToInt(\"[\")utf8ToInt(\"+\")utf8ToInt(\":\")", "e": 26842, "s": 26723, "text": null }, { "code": null, "e": 26850, "s": 26842, "text": "Output:" }, { "code": null, "e": 26872, "s": 26850, "text": "[1] 91\n[1] 43\n[1] 58\n" }, { "code": null, "e": 26883, "s": 26872, "text": "Example 2:" }, { "code": "# R program to convert a UTF8 to Integer # Creating a vectorx1 <- c(\"&@\\n\")x2 <- c(\"[+:\")x3 <- c(\"1d<U>\") # Calling the utf8ToInt() functionutf8ToInt(x1)utf8ToInt(x2)utf8ToInt(x3)", "e": 27065, "s": 26883, "text": null }, { "code": null, "e": 27073, "s": 27065, "text": "Output:" }, { "code": null, "e": 27124, "s": 27073, "text": "[1] 38 64 10\n[1] 91 43 58\n[1] 49 100 60 85 62\n" }, { "code": null, "e": 27140, "s": 27124, "text": "R Math-Function" }, { "code": null, "e": 27151, "s": 27140, "text": "R Language" }, { "code": null, "e": 27249, "s": 27151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27301, "s": 27249, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 27336, "s": 27301, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 27374, "s": 27336, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 27432, "s": 27374, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 27475, "s": 27432, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 27524, "s": 27475, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 27541, "s": 27524, "text": "R - if statement" }, { "code": null, "e": 27591, "s": 27541, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 27643, "s": 27591, "text": "Plot mean and standard deviation using ggplot2 in R" } ]
How to set “checked” for a checkbox with jQuery?
Use the checked attribute to set the checkbox with jQuery. Also, the prop() method is used to get the property value. You can try to run the following code to learn how to set checked for a checkbox: Live Demo <!DOCTYPE html> <html> <head> <title>jQuery Example</title> <style> b { color: green; } </style> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <input id="checkbox1" type="checkbox" checked="checked"> <label for="checkbox1">Check/ Uncheck this checkbox</label> <p></p> <script> $( "input" ).change(function() { var $input = $( this ); $( "p" ).html( ".attr( \"checked\" ): <b>" + $input.attr( "checked" ) + "</b><br>" + ".prop( \"checked\" ): <b>" + $input.prop( "checked" ) + "</b><br>" + ".is( \":checked\" ): <b>" + $input.is( ":checked" ) + "</b>" ); }).change(); </script> </body> </html>
[ { "code": null, "e": 1180, "s": 1062, "text": "Use the checked attribute to set the checkbox with jQuery. Also, the prop() method is used to get the property value." }, { "code": null, "e": 1262, "s": 1180, "text": "You can try to run the following code to learn how to set checked for a checkbox:" }, { "code": null, "e": 1272, "s": 1262, "text": "Live Demo" }, { "code": null, "e": 1938, "s": 1272, "text": "<!DOCTYPE html>\n<html>\n<head>\n <title>jQuery Example</title>\n <style>\n b {\n color: green;\n }\n </style>\n <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script>\n</head>\n<body>\n \n<input id=\"checkbox1\" type=\"checkbox\" checked=\"checked\">\n<label for=\"checkbox1\">Check/ Uncheck this checkbox</label>\n<p></p>\n \n<script>\n$( \"input\" ).change(function() {\n var $input = $( this );\n $( \"p\" ).html(\n \".attr( \\\"checked\\\" ): <b>\" + $input.attr( \"checked\" ) + \"</b><br>\" +\n \".prop( \\\"checked\\\" ): <b>\" + $input.prop( \"checked\" ) + \"</b><br>\" +\n \".is( \\\":checked\\\" ): <b>\" + $input.is( \":checked\" ) + \"</b>\" );\n}).change();\n</script>\n \n</body>\n</html>" } ]
Make your pictures beautiful with a touch of deep learning magic | by George Seif | Towards Data Science
Want to be inspired? Come join my Super Quotes newsletter. 😎 Camera technology is beautiful. It’s given us all a chance to save our memories, and to relive them when we see them again in our photos. That technology has come quite a long way over the past several years. With all kinds of new features like 4K, HDR, and colour enhancement, the photos one can capture are awe-inspiring. But it does come at a price. Not everyone can afford the best-of-the-best camera. Consumer DSLR cameras range anywhere from a few hundred to several thousand dollars. Not only that, but not everyone can get the most out of those camera; we’re not all expert photographers after all! Most of us just use our phones. But smartphones often take very bland photos in comparison to high-end DSLRs. Deep learning changes all of that. Research from the ETH Zurich’s Computer Vision Lab shows how you can automatically enhance photos taken by low quality cameras and make them look like they were taken by a pro photographer with a DSLR. Here’s how they did it. The team first collected a dataset of low-quality (from cell phones) and high-quality (from DSLR) photos, which you can download from the project page. This is exactly the data we want for such an enhancement task: input a low-quality image (from the phone) and have the deep network try to predict what the high-quality version (from the DSLR) would look like. An image has several attributes that we may want to enhance: lighting, colors, texture, contrast, and sharpness. The deep network is trained to hit on all of these attributes with four different loss functions: Color loss: euclidean distance between the blurred versions of the predicted and target images. Texture loss: based on the classification loss from a Generative Adversarial Network (GAN). The GAN is trained to predict whether a grayscale photo is of high or low quality. Since grayscale is used, the network will be nicely focused on the textures of the image rather than color. Content loss: difference between VGG features of the predicted image and the ground truth. This loss ensures that the overall structure and objects in the image (i.e image semantics) remain the same. Total Variation loss: total vertical and horizontal gradients in the image. This enforces smoothness in the image, such that the final result is not too grainy or noisy. Finally, these losses are all added up and an end-to-end network is trained to make the prediction! The over all GAN architecture is shown below. You can check out the paper for more details if you’d like to learn more too. Thanks to the beauty of the open source mindset in the AI community, there is a publicly available implementation of this photo enhancer right here! Here’s how you can use it. First clone the repository git clone https://github.com/aiff22/DPED Install the required libraries pip install tensorflow-gpupip install numpypip install scipy All of the pre-trained models already come with the repository in the models_orig folder, so there’s no need to download them! Place the photos you want to enhance in the following directory: dped/iphone/test_data/full_size_test_images/ This is the default directory for “iphone”, but you can change the code in the test_model.py script if you want to change it. The reason it says “iphone” is because the authors originally trained 3 separate models using photos from 3 smartphones: iphone, sony, and blackberry, so those are your three options. But the model works quite well on most photos with any of these options, so we can just pick one and run with it! Finally, to enhance the photos we just run one simple script: python test_model.py model=iphone_orig \ test_subset=full \ Voila! Your enhanced and professional-looking photos will be saved in the visual_results folder! Give the code a try yourself, it’s great fun! See how your photos look after the enhancement. Feel free to post a link below to share your photos with the community. In the mean time, here’s a few results from my own tests. Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science!
[ { "code": null, "e": 232, "s": 171, "text": "Want to be inspired? Come join my Super Quotes newsletter. 😎" }, { "code": null, "e": 370, "s": 232, "text": "Camera technology is beautiful. It’s given us all a chance to save our memories, and to relive them when we see them again in our photos." }, { "code": null, "e": 556, "s": 370, "text": "That technology has come quite a long way over the past several years. With all kinds of new features like 4K, HDR, and colour enhancement, the photos one can capture are awe-inspiring." }, { "code": null, "e": 839, "s": 556, "text": "But it does come at a price. Not everyone can afford the best-of-the-best camera. Consumer DSLR cameras range anywhere from a few hundred to several thousand dollars. Not only that, but not everyone can get the most out of those camera; we’re not all expert photographers after all!" }, { "code": null, "e": 949, "s": 839, "text": "Most of us just use our phones. But smartphones often take very bland photos in comparison to high-end DSLRs." }, { "code": null, "e": 984, "s": 949, "text": "Deep learning changes all of that." }, { "code": null, "e": 1186, "s": 984, "text": "Research from the ETH Zurich’s Computer Vision Lab shows how you can automatically enhance photos taken by low quality cameras and make them look like they were taken by a pro photographer with a DSLR." }, { "code": null, "e": 1210, "s": 1186, "text": "Here’s how they did it." }, { "code": null, "e": 1572, "s": 1210, "text": "The team first collected a dataset of low-quality (from cell phones) and high-quality (from DSLR) photos, which you can download from the project page. This is exactly the data we want for such an enhancement task: input a low-quality image (from the phone) and have the deep network try to predict what the high-quality version (from the DSLR) would look like." }, { "code": null, "e": 1783, "s": 1572, "text": "An image has several attributes that we may want to enhance: lighting, colors, texture, contrast, and sharpness. The deep network is trained to hit on all of these attributes with four different loss functions:" }, { "code": null, "e": 1879, "s": 1783, "text": "Color loss: euclidean distance between the blurred versions of the predicted and target images." }, { "code": null, "e": 2162, "s": 1879, "text": "Texture loss: based on the classification loss from a Generative Adversarial Network (GAN). The GAN is trained to predict whether a grayscale photo is of high or low quality. Since grayscale is used, the network will be nicely focused on the textures of the image rather than color." }, { "code": null, "e": 2362, "s": 2162, "text": "Content loss: difference between VGG features of the predicted image and the ground truth. This loss ensures that the overall structure and objects in the image (i.e image semantics) remain the same." }, { "code": null, "e": 2532, "s": 2362, "text": "Total Variation loss: total vertical and horizontal gradients in the image. This enforces smoothness in the image, such that the final result is not too grainy or noisy." }, { "code": null, "e": 2756, "s": 2532, "text": "Finally, these losses are all added up and an end-to-end network is trained to make the prediction! The over all GAN architecture is shown below. You can check out the paper for more details if you’d like to learn more too." }, { "code": null, "e": 2932, "s": 2756, "text": "Thanks to the beauty of the open source mindset in the AI community, there is a publicly available implementation of this photo enhancer right here! Here’s how you can use it." }, { "code": null, "e": 2959, "s": 2932, "text": "First clone the repository" }, { "code": null, "e": 3000, "s": 2959, "text": "git clone https://github.com/aiff22/DPED" }, { "code": null, "e": 3031, "s": 3000, "text": "Install the required libraries" }, { "code": null, "e": 3092, "s": 3031, "text": "pip install tensorflow-gpupip install numpypip install scipy" }, { "code": null, "e": 3219, "s": 3092, "text": "All of the pre-trained models already come with the repository in the models_orig folder, so there’s no need to download them!" }, { "code": null, "e": 3284, "s": 3219, "text": "Place the photos you want to enhance in the following directory:" }, { "code": null, "e": 3329, "s": 3284, "text": "dped/iphone/test_data/full_size_test_images/" }, { "code": null, "e": 3753, "s": 3329, "text": "This is the default directory for “iphone”, but you can change the code in the test_model.py script if you want to change it. The reason it says “iphone” is because the authors originally trained 3 separate models using photos from 3 smartphones: iphone, sony, and blackberry, so those are your three options. But the model works quite well on most photos with any of these options, so we can just pick one and run with it!" }, { "code": null, "e": 3815, "s": 3753, "text": "Finally, to enhance the photos we just run one simple script:" }, { "code": null, "e": 3895, "s": 3815, "text": "python test_model.py model=iphone_orig \\ test_subset=full \\" }, { "code": null, "e": 3992, "s": 3895, "text": "Voila! Your enhanced and professional-looking photos will be saved in the visual_results folder!" }, { "code": null, "e": 4216, "s": 3992, "text": "Give the code a try yourself, it’s great fun! See how your photos look after the enhancement. Feel free to post a link below to share your photos with the community. In the mean time, here’s a few results from my own tests." } ]
Adding a line to a scatter plot using Python's Matplotlib
To add a line to a scatter plot using Python's Matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Initialize a variable, n, for number of data points. Plot x and y data points using scatter() method. Plot a line using plot() method. Limt the X-axis using xlim() method. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True n = 100 x = np.random.rand(n) y = np.random.rand(n) plt.scatter(x, y, c=x) plt.plot([0.1, 0.4, 0.3, 0.2]) plt.xlim(0, 1) plt.show()
[ { "code": null, "e": 1155, "s": 1062, "text": "To add a line to a scatter plot using Python's Matplotlib, we can take the following steps −" }, { "code": null, "e": 1231, "s": 1155, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1284, "s": 1231, "text": "Initialize a variable, n, for number of data points." }, { "code": null, "e": 1333, "s": 1284, "text": "Plot x and y data points using scatter() method." }, { "code": null, "e": 1366, "s": 1333, "text": "Plot a line using plot() method." }, { "code": null, "e": 1403, "s": 1366, "text": "Limt the X-axis using xlim() method." }, { "code": null, "e": 1445, "s": 1403, "text": "To display the figure, use show() method." }, { "code": null, "e": 1724, "s": 1445, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nn = 100\nx = np.random.rand(n)\ny = np.random.rand(n)\n\nplt.scatter(x, y, c=x)\nplt.plot([0.1, 0.4, 0.3, 0.2])\nplt.xlim(0, 1)\n\nplt.show()" } ]
JqueryUI - Autocomplete
Auto completion is a mechanism frequently used in modern websites to provide the user with a list of suggestions for the beginning of the word, which he/she has typed in a text box. The user can then select an item from the list, which will be displayed in the input field. This feature prevents the user from having to enter an entire word or a set of words. JQueryUI provides an autocomplete widget — a control that acts a lot like a <select> dropdown, but filters the choices to present only those that match what the user is typing into a control. jQueryUI provides the autocomplete() method to create a list of suggestions below the input field and adds new CSS classes to the elements concerned to give them the appropriate style. The autocomplete() method can be used in two forms − $(selector, context).autocomplete (options) Method $(selector, context).autocomplete (options) Method $(selector, context).autocomplete ("action", params) Method $(selector, context).autocomplete ("action", params) Method The autocomplete (options) method declares that an HTML <input> element must be managed as an input field that will be displayed above a list of suggestions. The options parameter is an object that specifies the behavior of the list of suggestions when the user is typing in the input field. $(selector, context).autocomplete (options); You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows − $(selector, context).autocomplete({option1: value1, option2: value2..... }); The following table lists the different options that can be used with this method − This option is used append an element to the menu. By default its value is null. Option - appendTo This option is used append an element to the menu. By default its value is null. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element. Syntax $( ".selector" ).autocomplete({ appendTo: "#identifier" }); This option when set to true, the first item of the menu will automatically be focused when the menu is shown. By default its value is false. Option - autoFocus This option when set to true, the first item of the menu will automatically be focused when the menu is shown. By default its value is false. Syntax $( ".selector" ).autocomplete({ autoFocus: true }); This option is an Integer representing number of milliseconds to wait before trying to obtain the matching values (as specified by the source option). This can help reduce thrashing when non-local data is being obtained by giving the user time to enter more characters before the search is initiated. By default its value is 300. Option - delay This option is an Integer representing number of milliseconds to wait before trying to obtain the matching values (as specified by the source option). This can help reduce thrashing when non-local data is being obtained by giving the user time to enter more characters before the search is initiated. By default its value is 300. Syntax $( ".selector" ).autocomplete({ delay: 500 }); This option if specified and true, the autocomplete widget is initially disabled. By default its value is false. Option - disabled This option if specified and true, the autocomplete widget is initially disabled. By default its value is false. Syntax $( ".selector" ).autocomplete({ disabled: true }); The number of characters that must be entered before trying to obtain the matching values (as specified by the source option). This can prevent too large a value set from being presented when a few characters isn’t enough to whittle the set down to a reasonable level. By default its value is 1. Option - minLength The number of characters that must be entered before trying to obtain the matching values (as specified by the source option). This can prevent too large a value set from being presented when a few characters isn’t enough to whittle the set down to a reasonable level. By default its value is 1. Syntax $( ".selector" ).autocomplete({ minLength: 0 }); This option identifies the position of the suggestions menu in relation to the associated input element. The of option defaults to the input element, but you can specify another element to position against. By default its value is { my: "left top", at: "left bottom", collision: "none" }. Option - position This option identifies the position of the suggestions menu in relation to the associated input element. The of option defaults to the input element, but you can specify another element to position against. By default its value is { my: "left top", at: "left bottom", collision: "none" }. Syntax $( ".selector" ).autocomplete({ position: { my : "right top", at: "right bottom" } }); This option specifies the manner in which the data that matches the input data is obtained. A value must be provided or the autocomplete widget won’t be created. By default its value is none; must be specified. Option - source This option specifies the manner in which the data that matches the input data is obtained. A value must be provided or the autocomplete widget won’t be created. This value can be a : String representing the URL of a server resource that will return matching data, String representing the URL of a server resource that will return matching data, an array of local data from which the value will be matched,or an array of local data from which the value will be matched,or a function that serves as a general callback from providing the matching values. a function that serves as a general callback from providing the matching values. Syntax $( ".selector" ).autocomplete({ source: [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] }); The following section will show you a few working examples of autocomplete widget functionality. The following example demonstrates a simple example of autocomplete widget functionality, passing no parameters to the autocomplete() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { var availableTutorials = [ "ActionScript", "Bootstrap", "C", "C++", ]; $( "#automplete-1" ).autocomplete({ source: availableTutorials }); }); </script> </head> <body> <!-- HTML --> <div class = "ui-widget"> <p>Type "a" or "s"</p> <label for = "automplete-1">Tags: </label> <input id = "automplete-1"> </div> </body> </html> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result − Type "a" or "s" The following example demonstrates the usage of option autoFocus in the autocomplete widget of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { var availableTutorials = [ "ActionScript", "Bootstrap", "C", "C++", ]; $( "#automplete-2" ).autocomplete({ source: availableTutorials, autoFocus:true }); }); </script> </head> <body> <!-- HTML --> <div class = "ui-widget"> <p>Type "a" or "s"</p> <label for = "automplete-2">Tags: </label> <input id = "automplete-2"> </div> </body> </html> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Type "a" or "s" The following example demonstrates the usage of two options minLength and delay in the autocomplete widget of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { var availableTutorials = [ "ActionScript", "Bootstrap", "C", "C++", "Ecommerce", "Jquery", "Groovy", "Java", "JavaScript", "Lua", "Perl", "Ruby", "Scala", "Swing", "XHTML" ]; $( "#automplete-3" ).autocomplete({ minLength:2, delay:500, source: availableTutorials }); }); </script> </head> <body> <!-- HTML --> <div class = "ui-widget"> <p>Type two letter for e.g:ja,sc etc</p> <label for = "automplete-3">Tags: </label> <input id = "automplete-3"> </div> </body> </html> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Type two letter for e.g:ja,sc etc The following example demonstrates the usage of option label in the autocomplete widget of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#autocomplete-4" ).autocomplete({ source: [ { label: "India", value: "IND" }, { label: "Australia", value: "AUS" } ] }); }); </script> </head> <body> <!-- HTML --> <div class = "ui-widget"> <p>Type I OR A</p> <input id = "autocomplete-4"> </div> </body> </html> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Type I OR A The following example demonstrates the use of external file for source option in the autocomplete widget of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { $( "#autocomplete-5" ).autocomplete({ source: "/jqueryui/search.php", minLength: 2 }); }); </script> </head> <body> <input id = "autocomplete-5"> </body> </html> The file search.php is placed at the same location as the above file (autocompleteexample.html). Contents of search.php are as below − <? $term = $_GET[ "term" ]; $companies = array( array( "label" => "JAVA", "value" => "1" ), array( "label" => "DATA IMAGE PROCESSING", "value" => "2" ), array( "label" => "JAVASCRIPT", "value" => "3" ), array( "label" => "DATA MANAGEMENT SYSTEM", "value" => "4" ), array( "label" => "COMPUTER PROGRAMMING", "value" => "5" ), array( "label" => "SOFTWARE DEVELOPMENT LIFE CYCLE", "value" => "6" ), array( "label" => "LEARN COMPUTER FUNDAMENTALS", "value" => "7" ), array( "label" => "IMAGE PROCESSING USING JAVA", "value" => "8" ), array( "label" => "CLOUD COMPUTING", "value" => "9" ), array( "label" => "DATA MINING", "value" => "10" ), array( "label" => "DATA WAREHOUSE", "value" => "11" ), array( "label" => "E-COMMERCE", "value" => "12" ), array( "label" => "DBMS", "value" => "13" ), array( "label" => "HTTP", "value" => "14" ) ); $result = array(); foreach ($companies as $company) { $companyLabel = $company[ "label" ]; if ( strpos( strtoupper($companyLabel), strtoupper($term) )!== false ) { array_push( $result, $company ); } } echo json_encode( $result ); ?> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result − Type two letter words for e.g: ja, sc etc The autocomplete ("action", params) method can perform an action on the list of suggestions, such as show or hide. The action is specified as a String in the first argument (e.g., "close" to hide the list). Check out the actions that can be passed, in the following table. $(selector, context).autocomplete ("action", params);; The following table lists the different actions that can be used with this method − This action hides the list of suggestions in the Autocomplete menu. This method does not accept any arguments. Action - close This action hides the list of suggestions in the Autocomplete menu. This method does not accept any arguments. Syntax $( ".selector" ).autocomplete("close"); This action removes the autocomplete functionality. Lists of suggestions are deleted. This method does not accept any arguments. Action - destroy This action removes the autocomplete functionality. Lists of suggestions are deleted. This method does not accept any arguments. Syntax $( ".selector" ).autocomplete("destroy"); This action disables the autocompletion mechanism. The list of suggestions no longer appears. This method does not accept any arguments. Action - disable This action disables the autocompletion mechanism. The list of suggestions no longer appears. This method does not accept any arguments. Syntax $( ".selector" ).autocomplete("disable"); This action reactivates the autocompletion mechanism. The list of suggestions will again be displayed. This method does not accept any arguments. Action - enable This action reactivates the autocompletion mechanism. The list of suggestions will again be displayed. This method does not accept any arguments. Syntax $( ".selector" ).autocomplete("enable"); This action retrieves the value of the specified param optionName. This option corresponds to one of those used with autocomplete (options). Action - option( optionName ) This action retrieves the value of the specified param optionName. This option corresponds to one of those used with autocomplete (options). Syntax var isDisabled = $( ".selector" ).autocomplete( "option", "disabled" ); This action gets an object containing key/value pairs representing the current autocomplete options hash. Action - option This action gets an object containing key/value pairs representing the current autocomplete options hash. Syntax var options = $( ".selector" ).autocomplete( "option" ); This action sets the value of the autocomplete option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option. Action - option( optionName, value ) This action sets the value of the autocomplete option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option. Syntax $( ".selector" ).autocomplete( "option", "disabled", true ); This action is sets one or more options for the autocomplete. The argument options is a map of option-value pairs to be set. Action - option( options ) This action is sets one or more options for the autocomplete. The argument options is a map of option-value pairs to be set. Syntax $( ".selector" ).autocomplete( "option", { disabled: true } ); This action searches for correspondence between the string value and the data source (specified in options.source). The minimum number of characters (indicated in options.minLength) must be reached in value, otherwise the search is not performed. Action - search( [value ] ) This action searches for correspondence between the string value and the data source (specified in options.source). The minimum number of characters (indicated in options.minLength) must be reached in value, otherwise the search is not performed. Syntax $( ".selector" ).autocomplete( "search", "" ); Retrieve the <ul> DOM element corresponding to the list of suggestions. This is an object of jQuery class that allows easy access to the list without using jQuery selectors. Action - widget Retrieve the <ul> DOM element corresponding to the list of suggestions. This is an object of jQuery class that allows easy access to the list without using jQuery selectors. Syntax $( ".selector" ).autocomplete("widget"); Now let us see an example using the actions from the above table. The following example demonstrates the use of option( optionName, value ) method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <!-- Javascript --> <script> $(function() { var availableTutorials = [ "ActionScript", "Bootstrap", "C", "C++", "Ecommerce", "Jquery", "Groovy", "Java", "JavaScript", "Lua", "Perl", "Ruby", "Scala", "Swing", "XHTML" ]; $( "#automplete-6" ).autocomplete({ source: availableTutorials }); $( "#automplete-6" ).autocomplete("option", "position", { my : "right-10 top+10", at: "right top" }) }); </script> </head> <body> <!-- HTML --> <div class = "ui-widget"> <p>Type "a" or "s"</p> <label for = "automplete-6">Tags: </label> <input id = "automplete-6"> </div> </body> </html> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output − Type "a" or "s" The autocomplete widget can be extended as its built with the widget factory. When extending widgets, you have the ability to override or add to the behavior of existing methods. The following table lists methods that act as extension points with the same API stability as the plugin methods listed above. This method controls the creation of each option in the widget's menu. This method creates a new <li> element, appends it to the menu and return it. _renderItem( ul, item ) This method controls the creation of each option in the widget's menu. This method creates a new <li> element, appends it to the menu and return it. Where − <ul> is the element that must be appended to the newly created <li> element. <ul> is the element that must be appended to the newly created <li> element. item can be a label(String), the string to display for the item, or a value(String), the value to insert into the input when the item is selected. item This method controls building the widget's menu. _renderMenu( ul, items ) This method controls building the widget's menu. Where − <ul> is an Array of items that match the user typed term. Each item is an Object with label and value properties. <ul> is an Array of items that match the user typed term. Each item is an Object with label and value properties. This method controls sizing the menu before it is displayed.The menu element is available at this.menu.element. This method does not accept any arguments. _resizeMenu() This method controls sizing the menu before it is displayed.The menu element is available at this.menu.element. This method does not accept any arguments. In addition to the autocomplete (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below − This event is triggered when the value of the <input> element is changed based upon a selection. When triggered, this event will always come after the close event is triggered. Event - change(event, ui) This event is triggered when the value of the <input> element is changed based upon a selection. When triggered, this event will always come after the close event is triggered. Where event is of type Event, and ui is of type Object. Possible values of ui are − item − The item selected from the menu, if any. Otherwise the property is null. item − The item selected from the menu, if any. Otherwise the property is null. Syntax $( ".selector" ).autocomplete({ change: function( event, ui ) {} }); This event is triggered whenever the autocomplete menu closes. Event - close(event, ui) This event is triggered whenever the autocomplete menu closes. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).autocomplete({ close: function( event, ui ) {} }); This event is triggered when the autocomplete is created. Event - create(event, ui) This event is triggered when the autocomplete is created.. Where event is of type Event, and ui is of type Object. Possible values of ui are − item − The item selected from the menu, if any. Otherwise the property is null. item − The item selected from the menu, if any. Otherwise the property is null. Syntax $( ".selector" ).autocomplete({ create: function( event, ui ) {} }); This event is triggered whenever one of the menu choices receives focus. Unless canceled (for example, by returning false), the focused value is set into the <input> element. Event - focus(event, ui) This event is triggered whenever one of the menu choices receives focus. Unless canceled (for example, by returning false), the focused value is set into the <input> element. Where event is of type Event, and ui is of type Object. Possible values of ui are − item − The focused item. item − The focused item. Syntax $( ".selector" ).autocomplete({ focus: function( event, ui ) {} }); This event is triggered after the data has been readied and the menu is about to open. Event - open(event, ui) This event is triggered after the data has been readied and the menu is about to open. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).autocomplete({ open: function( event, ui ) {} }); This event is triggered after a search completes, before the menu is shown. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled. Event - response(event, ui) This event is triggered after a search completes, before the menu is shown. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled. Where event is of type Event, and ui is of type Object. Possible values of ui are − content − Contains the response data and can be modified to change the results that will be shown. content − Contains the response data and can be modified to change the results that will be shown. Syntax $( ".selector" ).autocomplete({ response: function( event, ui ) {} }); This event is triggered after any delay and minLength criteria have been met, just before the mechanism specified by source is activated. If canceled, the search operation is aborted. Event - search(event, ui) This event is triggered after any delay and minLength criteria have been met, just before the mechanism specified by source is activated. If canceled, the search operation is aborted. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).autocomplete({ search: function( event, ui ) {} }); This event is triggered when a value is selected from the autocomplete menu. Canceling this event prevents the value from being set into the <input> element (but doesn’t prevent the menu from closing). Event - select(event, ui) This event is triggered when a value is selected from the autocomplete menu. Canceling this event prevents the value from being set into the <input> element (but doesn’t prevent the menu from closing). Where event is of type Event, and ui is of type Object. Possible values of ui are − item − An Object with label and value properties for the selected option. item − An Object with label and value properties for the selected option. Syntax $( ".selector" ).autocomplete({ select: function( event, ui ) {} }); The following example demonstrates the event method usage in autocomplete widgets. This example demonstrates the use of events focus, and select. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Autocomplete functionality</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> #project-label { display: block; font-weight: bold; margin-bottom: 1em; } #project-icon { float: left; height: 32px; width: 32px; } #project-description { margin: 0; padding: 0; } </style> <!-- Javascript --> <script> $(function() { var projects = [ { value: "java", label: "Java", desc: "write once run anywhere", }, { value: "jquery-ui", label: "jQuery UI", desc: "the official user interface library for jQuery", }, { value: "Bootstrap", label: "Twitter Bootstrap", desc: "popular front end frameworks ", } ]; $( "#project" ).autocomplete({ minLength: 0, source: projects, focus: function( event, ui ) { $( "#project" ).val( ui.item.label ); return false; }, select: function( event, ui ) { $( "#project" ).val( ui.item.label ); $( "#project-id" ).val( ui.item.value ); $( "#project-description" ).html( ui.item.desc ); return false; } }) .data( "ui-autocomplete" )._renderItem = function( ul, item ) { return $( "<li>" ) .append( "<a>" + item.label + "<br>" + item.desc + "</a>" ) .appendTo( ul ); }; }); </script> </head> <body> <div id = "project-label">Select a project (type "a" for a start):</div> <input id = "project"> <input type = "hidden" id = "project-id"> <p id = "project-description"></p> </body> </html> Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript. You must also see the following output − Print Add Notes Bookmark this page
[ { "code": null, "e": 2624, "s": 2264, "text": "Auto completion is a mechanism frequently used in modern websites to provide the user with a list of suggestions for the beginning of the word, which he/she has typed in a text box. The user can then select an item from the list, which will be displayed in the input field. This feature prevents the user from having to enter an entire word or a set of words." }, { "code": null, "e": 3001, "s": 2624, "text": "JQueryUI provides an autocomplete widget — a control that acts a lot like a <select> dropdown, but filters the choices to present only those that match what the user is typing into a control. jQueryUI provides the autocomplete() method to create a list of suggestions below the input field and adds new CSS classes to the elements concerned to give them the appropriate style." }, { "code": null, "e": 3054, "s": 3001, "text": "The autocomplete() method can be used in two forms −" }, { "code": null, "e": 3105, "s": 3054, "text": "$(selector, context).autocomplete (options) Method" }, { "code": null, "e": 3156, "s": 3105, "text": "$(selector, context).autocomplete (options) Method" }, { "code": null, "e": 3216, "s": 3156, "text": "$(selector, context).autocomplete (\"action\", params) Method" }, { "code": null, "e": 3276, "s": 3216, "text": "$(selector, context).autocomplete (\"action\", params) Method" }, { "code": null, "e": 3568, "s": 3276, "text": "The autocomplete (options) method declares that an HTML <input> element must be managed as an input field that will be displayed above a list of suggestions. The options parameter is an object that specifies the behavior of the list of suggestions when the user is typing in the input field." }, { "code": null, "e": 3614, "s": 3568, "text": "$(selector, context).autocomplete (options);\n" }, { "code": null, "e": 3790, "s": 3614, "text": "You can provide one or more options at a time using Javascript object. If there are more than one options to be provided then you will separate them using a comma as follows −" }, { "code": null, "e": 3867, "s": 3790, "text": "$(selector, context).autocomplete({option1: value1, option2: value2..... });" }, { "code": null, "e": 3951, "s": 3867, "text": "The following table lists the different options that can be used with this method −" }, { "code": null, "e": 4032, "s": 3951, "text": "This option is used append an element to the menu. By default its value is null." }, { "code": null, "e": 4050, "s": 4032, "text": "Option - appendTo" }, { "code": null, "e": 4318, "s": 4050, "text": "This option is used append an element to the menu. By default its value is null. When the value is null, the parents of the input field will be checked for a class of ui-front. If an element with the ui-front class is found, the menu will be appended to that element." }, { "code": null, "e": 4325, "s": 4318, "text": "Syntax" }, { "code": null, "e": 4386, "s": 4325, "text": "$( \".selector\" ).autocomplete({ appendTo: \"#identifier\" });\n" }, { "code": null, "e": 4528, "s": 4386, "text": "This option when set to true, the first item of the menu will automatically be focused when the menu is shown. By default its value is false." }, { "code": null, "e": 4547, "s": 4528, "text": "Option - autoFocus" }, { "code": null, "e": 4689, "s": 4547, "text": "This option when set to true, the first item of the menu will automatically be focused when the menu is shown. By default its value is false." }, { "code": null, "e": 4696, "s": 4689, "text": "Syntax" }, { "code": null, "e": 4749, "s": 4696, "text": "$( \".selector\" ).autocomplete({ autoFocus: true });\n" }, { "code": null, "e": 5079, "s": 4749, "text": "This option is an Integer representing number of milliseconds to wait before trying to obtain the matching values (as specified by the source option). This can help reduce thrashing when non-local data is being obtained by giving the user time to enter more characters before the search is initiated. By default its value is 300." }, { "code": null, "e": 5094, "s": 5079, "text": "Option - delay" }, { "code": null, "e": 5424, "s": 5094, "text": "This option is an Integer representing number of milliseconds to wait before trying to obtain the matching values (as specified by the source option). This can help reduce thrashing when non-local data is being obtained by giving the user time to enter more characters before the search is initiated. By default its value is 300." }, { "code": null, "e": 5431, "s": 5424, "text": "Syntax" }, { "code": null, "e": 5479, "s": 5431, "text": "$( \".selector\" ).autocomplete({ delay: 500 });\n" }, { "code": null, "e": 5592, "s": 5479, "text": "This option if specified and true, the autocomplete widget is initially disabled. By default its value is false." }, { "code": null, "e": 5610, "s": 5592, "text": "Option - disabled" }, { "code": null, "e": 5723, "s": 5610, "text": "This option if specified and true, the autocomplete widget is initially disabled. By default its value is false." }, { "code": null, "e": 5730, "s": 5723, "text": "Syntax" }, { "code": null, "e": 5782, "s": 5730, "text": "$( \".selector\" ).autocomplete({ disabled: true });\n" }, { "code": null, "e": 6078, "s": 5782, "text": "The number of characters that must be entered before trying to obtain the matching values (as specified by the source option). This can prevent too large a value set from being presented when a few characters isn’t enough to whittle the set down to a reasonable level. By default its value is 1." }, { "code": null, "e": 6097, "s": 6078, "text": "Option - minLength" }, { "code": null, "e": 6393, "s": 6097, "text": "The number of characters that must be entered before trying to obtain the matching values (as specified by the source option). This can prevent too large a value set from being presented when a few characters isn’t enough to whittle the set down to a reasonable level. By default its value is 1." }, { "code": null, "e": 6400, "s": 6393, "text": "Syntax" }, { "code": null, "e": 6450, "s": 6400, "text": "$( \".selector\" ).autocomplete({ minLength: 0 });\n" }, { "code": null, "e": 6739, "s": 6450, "text": "This option identifies the position of the suggestions menu in relation to the associated input element. The of option defaults to the input element, but you can specify another element to position against. By default its value is { my: \"left top\", at: \"left bottom\", collision: \"none\" }." }, { "code": null, "e": 6757, "s": 6739, "text": "Option - position" }, { "code": null, "e": 7046, "s": 6757, "text": "This option identifies the position of the suggestions menu in relation to the associated input element. The of option defaults to the input element, but you can specify another element to position against. By default its value is { my: \"left top\", at: \"left bottom\", collision: \"none\" }." }, { "code": null, "e": 7053, "s": 7046, "text": "Syntax" }, { "code": null, "e": 7141, "s": 7053, "text": "$( \".selector\" ).autocomplete({ position: { my : \"right top\", at: \"right bottom\" } });\n" }, { "code": null, "e": 7352, "s": 7141, "text": "This option specifies the manner in which the data that matches the input data is obtained. A value must be provided or the autocomplete widget won’t be created. By default its value is none; must be specified." }, { "code": null, "e": 7368, "s": 7352, "text": "Option - source" }, { "code": null, "e": 7553, "s": 7368, "text": "This option specifies the manner in which the data that matches the input data is obtained. A value must be provided or the autocomplete widget won’t be created. This value can be a :\n" }, { "code": null, "e": 7634, "s": 7553, "text": "String representing the URL of a server resource that will return matching data," }, { "code": null, "e": 7715, "s": 7634, "text": "String representing the URL of a server resource that will return matching data," }, { "code": null, "e": 7779, "s": 7715, "text": "an array of local data from which the value will be matched,or " }, { "code": null, "e": 7843, "s": 7779, "text": "an array of local data from which the value will be matched,or " }, { "code": null, "e": 7924, "s": 7843, "text": "a function that serves as a general callback from providing the matching values." }, { "code": null, "e": 8005, "s": 7924, "text": "a function that serves as a general callback from providing the matching values." }, { "code": null, "e": 8012, "s": 8005, "text": "Syntax" }, { "code": null, "e": 8125, "s": 8012, "text": "$( \".selector\" ).autocomplete({ source: [ \"c++\", \"java\", \"php\", \"coldfusion\", \"javascript\", \"asp\", \"ruby\" ] });\n" }, { "code": null, "e": 8222, "s": 8125, "text": "The following section will show you a few working examples of autocomplete widget functionality." }, { "code": null, "e": 8364, "s": 8222, "text": "The following example demonstrates a simple example of autocomplete widget functionality, passing no parameters to the autocomplete() method." }, { "code": null, "e": 9363, "s": 8364, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n var availableTutorials = [\n \"ActionScript\",\n \"Bootstrap\",\n \"C\",\n \"C++\",\n ];\n $( \"#automplete-1\" ).autocomplete({\n source: availableTutorials\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div class = \"ui-widget\">\n <p>Type \"a\" or \"s\"</p>\n <label for = \"automplete-1\">Tags: </label>\n <input id = \"automplete-1\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 9564, "s": 9363, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −" }, { "code": null, "e": 9580, "s": 9564, "text": "Type \"a\" or \"s\"" }, { "code": null, "e": 9685, "s": 9580, "text": "The following example demonstrates the usage of option autoFocus in the autocomplete widget of JqueryUI." }, { "code": null, "e": 10713, "s": 9685, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n var availableTutorials = [\n \"ActionScript\",\n \"Bootstrap\",\n \"C\",\n \"C++\",\n ];\n $( \"#automplete-2\" ).autocomplete({\n source: availableTutorials,\n autoFocus:true\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div class = \"ui-widget\">\n <p>Type \"a\" or \"s\"</p>\n <label for = \"automplete-2\">Tags: </label>\n <input id = \"automplete-2\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 10917, "s": 10713, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 10933, "s": 10917, "text": "Type \"a\" or \"s\"" }, { "code": null, "e": 11053, "s": 10933, "text": "The following example demonstrates the usage of two options minLength and delay in the autocomplete widget of JqueryUI." }, { "code": null, "e": 12398, "s": 11053, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n var availableTutorials = [\n \"ActionScript\",\n \"Bootstrap\",\n \"C\",\n \"C++\",\n \"Ecommerce\",\n \"Jquery\",\n \"Groovy\",\n \"Java\",\n \"JavaScript\",\n \"Lua\",\n \"Perl\",\n \"Ruby\",\n \"Scala\",\n \"Swing\",\n \"XHTML\"\t\n ];\n $( \"#automplete-3\" ).autocomplete({\n minLength:2, \n delay:500, \n source: availableTutorials\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div class = \"ui-widget\">\n <p>Type two letter for e.g:ja,sc etc</p>\n <label for = \"automplete-3\">Tags: </label>\n <input id = \"automplete-3\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 12602, "s": 12398, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 12636, "s": 12602, "text": "Type two letter for e.g:ja,sc etc" }, { "code": null, "e": 12737, "s": 12636, "text": "The following example demonstrates the usage of option label in the autocomplete widget of JqueryUI." }, { "code": null, "e": 13634, "s": 12737, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#autocomplete-4\" ).autocomplete({\n source: [\n { label: \"India\", value: \"IND\" },\n { label: \"Australia\", value: \"AUS\" }\n ]\n });\n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div class = \"ui-widget\">\n <p>Type I OR A</p>\n <input id = \"autocomplete-4\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 13838, "s": 13634, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 13850, "s": 13838, "text": "Type I OR A" }, { "code": null, "e": 13968, "s": 13850, "text": "The following example demonstrates the use of external file for source option in the autocomplete widget of JqueryUI." }, { "code": null, "e": 14695, "s": 13968, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n $( \"#autocomplete-5\" ).autocomplete({\n source: \"/jqueryui/search.php\",\n minLength: 2\n });\n });\n </script> \n </head>\n \n <body>\n <input id = \"autocomplete-5\">\n </body>\n</html>" }, { "code": null, "e": 14830, "s": 14695, "text": "The file search.php is placed at the same location as the above file (autocompleteexample.html). Contents of search.php are as below −" }, { "code": null, "e": 15959, "s": 14830, "text": "<?\n$term = $_GET[ \"term\" ];\n$companies = array(\n array( \"label\" => \"JAVA\", \"value\" => \"1\" ),\n array( \"label\" => \"DATA IMAGE PROCESSING\", \"value\" => \"2\" ),\n array( \"label\" => \"JAVASCRIPT\", \"value\" => \"3\" ),\n array( \"label\" => \"DATA MANAGEMENT SYSTEM\", \"value\" => \"4\" ),\n array( \"label\" => \"COMPUTER PROGRAMMING\", \"value\" => \"5\" ),\n array( \"label\" => \"SOFTWARE DEVELOPMENT LIFE CYCLE\", \"value\" => \"6\" ),\n array( \"label\" => \"LEARN COMPUTER FUNDAMENTALS\", \"value\" => \"7\" ),\n array( \"label\" => \"IMAGE PROCESSING USING JAVA\", \"value\" => \"8\" ),\n array( \"label\" => \"CLOUD COMPUTING\", \"value\" => \"9\" ),\n array( \"label\" => \"DATA MINING\", \"value\" => \"10\" ),\n array( \"label\" => \"DATA WAREHOUSE\", \"value\" => \"11\" ),\n array( \"label\" => \"E-COMMERCE\", \"value\" => \"12\" ),\n array( \"label\" => \"DBMS\", \"value\" => \"13\" ),\n array( \"label\" => \"HTTP\", \"value\" => \"14\" )\n\t\n);\n\n$result = array();\nforeach ($companies as $company) {\n $companyLabel = $company[ \"label\" ];\n if ( strpos( strtoupper($companyLabel), strtoupper($term) )!== false ) {\n array_push( $result, $company );\n }\n}\n\necho json_encode( $result );\n?>" }, { "code": null, "e": 16163, "s": 15959, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output. Now, you can play with the result −" }, { "code": null, "e": 16205, "s": 16163, "text": "Type two letter words for e.g: ja, sc etc" }, { "code": null, "e": 16478, "s": 16205, "text": "The autocomplete (\"action\", params) method can perform an action on the list of suggestions, such as show or hide. The action is specified as a String in the first argument (e.g., \"close\" to hide the list). Check out the actions that can be passed, in the following table." }, { "code": null, "e": 16534, "s": 16478, "text": "$(selector, context).autocomplete (\"action\", params);;\n" }, { "code": null, "e": 16618, "s": 16534, "text": "The following table lists the different actions that can be used with this method −" }, { "code": null, "e": 16729, "s": 16618, "text": "This action hides the list of suggestions in the Autocomplete menu. This method does not accept any arguments." }, { "code": null, "e": 16744, "s": 16729, "text": "Action - close" }, { "code": null, "e": 16855, "s": 16744, "text": "This action hides the list of suggestions in the Autocomplete menu. This method does not accept any arguments." }, { "code": null, "e": 16862, "s": 16855, "text": "Syntax" }, { "code": null, "e": 16903, "s": 16862, "text": "$( \".selector\" ).autocomplete(\"close\");\n" }, { "code": null, "e": 17032, "s": 16903, "text": "This action removes the autocomplete functionality. Lists of suggestions are deleted. This method does not accept any arguments." }, { "code": null, "e": 17049, "s": 17032, "text": "Action - destroy" }, { "code": null, "e": 17178, "s": 17049, "text": "This action removes the autocomplete functionality. Lists of suggestions are deleted. This method does not accept any arguments." }, { "code": null, "e": 17185, "s": 17178, "text": "Syntax" }, { "code": null, "e": 17228, "s": 17185, "text": "$( \".selector\" ).autocomplete(\"destroy\");\n" }, { "code": null, "e": 17365, "s": 17228, "text": "This action disables the autocompletion mechanism. The list of suggestions no longer appears. This method does not accept any arguments." }, { "code": null, "e": 17382, "s": 17365, "text": "Action - disable" }, { "code": null, "e": 17519, "s": 17382, "text": "This action disables the autocompletion mechanism. The list of suggestions no longer appears. This method does not accept any arguments." }, { "code": null, "e": 17526, "s": 17519, "text": "Syntax" }, { "code": null, "e": 17569, "s": 17526, "text": "$( \".selector\" ).autocomplete(\"disable\");\n" }, { "code": null, "e": 17715, "s": 17569, "text": "This action reactivates the autocompletion mechanism. The list of suggestions will again be displayed. This method does not accept any arguments." }, { "code": null, "e": 17731, "s": 17715, "text": "Action - enable" }, { "code": null, "e": 17877, "s": 17731, "text": "This action reactivates the autocompletion mechanism. The list of suggestions will again be displayed. This method does not accept any arguments." }, { "code": null, "e": 17884, "s": 17877, "text": "Syntax" }, { "code": null, "e": 17926, "s": 17884, "text": "$( \".selector\" ).autocomplete(\"enable\");\n" }, { "code": null, "e": 18067, "s": 17926, "text": "This action retrieves the value of the specified param optionName. This option corresponds to one of those used with autocomplete (options)." }, { "code": null, "e": 18097, "s": 18067, "text": "Action - option( optionName )" }, { "code": null, "e": 18238, "s": 18097, "text": "This action retrieves the value of the specified param optionName. This option corresponds to one of those used with autocomplete (options)." }, { "code": null, "e": 18245, "s": 18238, "text": "Syntax" }, { "code": null, "e": 18318, "s": 18245, "text": "var isDisabled = $( \".selector\" ).autocomplete( \"option\", \"disabled\" );\n" }, { "code": null, "e": 18424, "s": 18318, "text": "This action gets an object containing key/value pairs representing the current autocomplete options hash." }, { "code": null, "e": 18440, "s": 18424, "text": "Action - option" }, { "code": null, "e": 18546, "s": 18440, "text": "This action gets an object containing key/value pairs representing the current autocomplete options hash." }, { "code": null, "e": 18553, "s": 18546, "text": "Syntax" }, { "code": null, "e": 18611, "s": 18553, "text": "var options = $( \".selector\" ).autocomplete( \"option\" );\n" }, { "code": null, "e": 18812, "s": 18611, "text": "This action sets the value of the autocomplete option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option." }, { "code": null, "e": 18849, "s": 18812, "text": "Action - option( optionName, value )" }, { "code": null, "e": 19050, "s": 18849, "text": "This action sets the value of the autocomplete option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option." }, { "code": null, "e": 19057, "s": 19050, "text": "Syntax" }, { "code": null, "e": 19119, "s": 19057, "text": "$( \".selector\" ).autocomplete( \"option\", \"disabled\", true );\n" }, { "code": null, "e": 19244, "s": 19119, "text": "This action is sets one or more options for the autocomplete. The argument options is a map of option-value pairs to be set." }, { "code": null, "e": 19271, "s": 19244, "text": "Action - option( options )" }, { "code": null, "e": 19396, "s": 19271, "text": "This action is sets one or more options for the autocomplete. The argument options is a map of option-value pairs to be set." }, { "code": null, "e": 19403, "s": 19396, "text": "Syntax" }, { "code": null, "e": 19467, "s": 19403, "text": "$( \".selector\" ).autocomplete( \"option\", { disabled: true } );\n" }, { "code": null, "e": 19714, "s": 19467, "text": "This action searches for correspondence between the string value and the data source (specified in options.source). The minimum number of characters (indicated in options.minLength) must be reached in value, otherwise the search is not performed." }, { "code": null, "e": 19742, "s": 19714, "text": "Action - search( [value ] )" }, { "code": null, "e": 19989, "s": 19742, "text": "This action searches for correspondence between the string value and the data source (specified in options.source). The minimum number of characters (indicated in options.minLength) must be reached in value, otherwise the search is not performed." }, { "code": null, "e": 19996, "s": 19989, "text": "Syntax" }, { "code": null, "e": 20044, "s": 19996, "text": "$( \".selector\" ).autocomplete( \"search\", \"\" );\n" }, { "code": null, "e": 20218, "s": 20044, "text": "Retrieve the <ul> DOM element corresponding to the list of suggestions. This is an object of jQuery class that allows easy access to the list without using jQuery selectors." }, { "code": null, "e": 20234, "s": 20218, "text": "Action - widget" }, { "code": null, "e": 20408, "s": 20234, "text": "Retrieve the <ul> DOM element corresponding to the list of suggestions. This is an object of jQuery class that allows easy access to the list without using jQuery selectors." }, { "code": null, "e": 20415, "s": 20408, "text": "Syntax" }, { "code": null, "e": 20457, "s": 20415, "text": "$( \".selector\" ).autocomplete(\"widget\");\n" }, { "code": null, "e": 20605, "s": 20457, "text": "Now let us see an example using the actions from the above table. The following example demonstrates the use of option( optionName, value ) method." }, { "code": null, "e": 22001, "s": 20605, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <!-- Javascript -->\n <script>\n $(function() {\n var availableTutorials = [\n \"ActionScript\",\n \"Bootstrap\",\n \"C\",\n \"C++\",\n \"Ecommerce\",\n \"Jquery\",\n \"Groovy\",\n \"Java\",\n \"JavaScript\",\n \"Lua\",\n \"Perl\",\n \"Ruby\",\n \"Scala\",\n \"Swing\",\n \"XHTML\"\t\n ];\n $( \"#automplete-6\" ).autocomplete({\n source: availableTutorials\n });\n $( \"#automplete-6\" ).autocomplete(\"option\", \"position\",\n { my : \"right-10 top+10\", at: \"right top\" }) \n });\n </script>\n </head>\n \n <body>\n <!-- HTML --> \n <div class = \"ui-widget\">\n <p>Type \"a\" or \"s\"</p>\n <label for = \"automplete-6\">Tags: </label>\n <input id = \"automplete-6\">\n </div>\n </body>\n</html>" }, { "code": null, "e": 22170, "s": 22001, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript, you must also see the following output −" }, { "code": null, "e": 22186, "s": 22170, "text": "Type \"a\" or \"s\"" }, { "code": null, "e": 22492, "s": 22186, "text": "The autocomplete widget can be extended as its built with the widget factory. When extending widgets, you have the ability to override or add to the behavior of existing methods. The following table lists methods that act as extension points with the same API stability as the plugin methods listed above." }, { "code": null, "e": 22641, "s": 22492, "text": "This method controls the creation of each option in the widget's menu. This method creates a new <li> element, appends it to the menu and return it." }, { "code": null, "e": 22665, "s": 22641, "text": "_renderItem( ul, item )" }, { "code": null, "e": 22822, "s": 22665, "text": "This method controls the creation of each option in the widget's menu. This method creates a new <li> element, appends it to the menu and return it. Where −" }, { "code": null, "e": 22899, "s": 22822, "text": "<ul> is the element that must be appended to the newly created <li> element." }, { "code": null, "e": 22976, "s": 22899, "text": "<ul> is the element that must be appended to the newly created <li> element." }, { "code": null, "e": 23123, "s": 22976, "text": "item can be a label(String), the string to display for the item, or a value(String), the value to insert into the input when the item is selected." }, { "code": null, "e": 23128, "s": 23123, "text": "item" }, { "code": null, "e": 23177, "s": 23128, "text": "This method controls building the widget's menu." }, { "code": null, "e": 23202, "s": 23177, "text": "_renderMenu( ul, items )" }, { "code": null, "e": 23259, "s": 23202, "text": "This method controls building the widget's menu. Where −" }, { "code": null, "e": 23373, "s": 23259, "text": "<ul> is an Array of items that match the user typed term. Each item is an Object with label and value properties." }, { "code": null, "e": 23487, "s": 23373, "text": "<ul> is an Array of items that match the user typed term. Each item is an Object with label and value properties." }, { "code": null, "e": 23642, "s": 23487, "text": "This method controls sizing the menu before it is displayed.The menu element is available at this.menu.element. This method does not accept any arguments." }, { "code": null, "e": 23656, "s": 23642, "text": "_resizeMenu()" }, { "code": null, "e": 23811, "s": 23656, "text": "This method controls sizing the menu before it is displayed.The menu element is available at this.menu.element. This method does not accept any arguments." }, { "code": null, "e": 24015, "s": 23811, "text": "In addition to the autocomplete (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −" }, { "code": null, "e": 24192, "s": 24015, "text": "This event is triggered when the value of the <input> element is changed based upon a selection. When triggered, this event will always come after the close event is triggered." }, { "code": null, "e": 24218, "s": 24192, "text": "Event - change(event, ui)" }, { "code": null, "e": 24479, "s": 24218, "text": "This event is triggered when the value of the <input> element is changed based upon a selection. When triggered, this event will always come after the close event is triggered. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 24559, "s": 24479, "text": "item − The item selected from the menu, if any. Otherwise the property is null." }, { "code": null, "e": 24639, "s": 24559, "text": "item − The item selected from the menu, if any. Otherwise the property is null." }, { "code": null, "e": 24646, "s": 24639, "text": "Syntax" }, { "code": null, "e": 24719, "s": 24646, "text": "$( \".selector\" ).autocomplete({\n change: function( event, ui ) {}\n});\n" }, { "code": null, "e": 24782, "s": 24719, "text": "This event is triggered whenever the autocomplete menu closes." }, { "code": null, "e": 24807, "s": 24782, "text": "Event - close(event, ui)" }, { "code": null, "e": 24927, "s": 24807, "text": "This event is triggered whenever the autocomplete menu closes. Where event is of type Event, and ui is of type Object.\n" }, { "code": null, "e": 24934, "s": 24927, "text": "Syntax" }, { "code": null, "e": 25006, "s": 24934, "text": "$( \".selector\" ).autocomplete({\n close: function( event, ui ) {}\n});\n" }, { "code": null, "e": 25064, "s": 25006, "text": "This event is triggered when the autocomplete is created." }, { "code": null, "e": 25090, "s": 25064, "text": "Event - create(event, ui)" }, { "code": null, "e": 25233, "s": 25090, "text": "This event is triggered when the autocomplete is created.. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 25313, "s": 25233, "text": "item − The item selected from the menu, if any. Otherwise the property is null." }, { "code": null, "e": 25393, "s": 25313, "text": "item − The item selected from the menu, if any. Otherwise the property is null." }, { "code": null, "e": 25400, "s": 25393, "text": "Syntax" }, { "code": null, "e": 25473, "s": 25400, "text": "$( \".selector\" ).autocomplete({\n create: function( event, ui ) {}\n});\n" }, { "code": null, "e": 25648, "s": 25473, "text": "This event is triggered whenever one of the menu choices receives focus. Unless canceled (for example, by returning false), the focused value is set into the <input> element." }, { "code": null, "e": 25673, "s": 25648, "text": "Event - focus(event, ui)" }, { "code": null, "e": 25932, "s": 25673, "text": "This event is triggered whenever one of the menu choices receives focus. Unless canceled (for example, by returning false), the focused value is set into the <input> element. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 25957, "s": 25932, "text": "item − The focused item." }, { "code": null, "e": 25982, "s": 25957, "text": "item − The focused item." }, { "code": null, "e": 25989, "s": 25982, "text": "Syntax" }, { "code": null, "e": 26061, "s": 25989, "text": "$( \".selector\" ).autocomplete({\n focus: function( event, ui ) {}\n});\n" }, { "code": null, "e": 26148, "s": 26061, "text": "This event is triggered after the data has been readied and the menu is about to open." }, { "code": null, "e": 26172, "s": 26148, "text": "Event - open(event, ui)" }, { "code": null, "e": 26315, "s": 26172, "text": "This event is triggered after the data has been readied and the menu is about to open. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 26322, "s": 26315, "text": "Syntax" }, { "code": null, "e": 26393, "s": 26322, "text": "$( \".selector\" ).autocomplete({\n open: function( event, ui ) {}\n});\n" }, { "code": null, "e": 26622, "s": 26393, "text": "This event is triggered after a search completes, before the menu is shown. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled." }, { "code": null, "e": 26650, "s": 26622, "text": "Event - response(event, ui)" }, { "code": null, "e": 26963, "s": 26650, "text": "This event is triggered after a search completes, before the menu is shown. This event is always triggered when a search completes, even if the menu will not be shown because there are no results or the Autocomplete is disabled. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 27062, "s": 26963, "text": "content − Contains the response data and can be modified to change the results that will be shown." }, { "code": null, "e": 27161, "s": 27062, "text": "content − Contains the response data and can be modified to change the results that will be shown." }, { "code": null, "e": 27168, "s": 27161, "text": "Syntax" }, { "code": null, "e": 27243, "s": 27168, "text": "$( \".selector\" ).autocomplete({\n response: function( event, ui ) {}\n});\n" }, { "code": null, "e": 27427, "s": 27243, "text": "This event is triggered after any delay and minLength criteria have been met, just before the mechanism specified by source is activated. If canceled, the search operation is aborted." }, { "code": null, "e": 27453, "s": 27427, "text": "Event - search(event, ui)" }, { "code": null, "e": 27693, "s": 27453, "text": "This event is triggered after any delay and minLength criteria have been met, just before the mechanism specified by source is activated. If canceled, the search operation is aborted. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 27700, "s": 27693, "text": "Syntax" }, { "code": null, "e": 27773, "s": 27700, "text": "$( \".selector\" ).autocomplete({\n search: function( event, ui ) {}\n});\n" }, { "code": null, "e": 27975, "s": 27773, "text": "This event is triggered when a value is selected from the autocomplete menu. Canceling this event prevents the value from being set into the <input> element (but doesn’t prevent the menu from closing)." }, { "code": null, "e": 28001, "s": 27975, "text": "Event - select(event, ui)" }, { "code": null, "e": 28287, "s": 28001, "text": "This event is triggered when a value is selected from the autocomplete menu. Canceling this event prevents the value from being set into the <input> element (but doesn’t prevent the menu from closing). Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 28361, "s": 28287, "text": "item − An Object with label and value properties for the selected option." }, { "code": null, "e": 28435, "s": 28361, "text": "item − An Object with label and value properties for the selected option." }, { "code": null, "e": 28442, "s": 28435, "text": "Syntax" }, { "code": null, "e": 28515, "s": 28442, "text": "$( \".selector\" ).autocomplete({\n select: function( event, ui ) {}\n});\n" }, { "code": null, "e": 28662, "s": 28515, "text": "The following example demonstrates the event method usage in autocomplete widgets. This example demonstrates the use of events focus, and select." }, { "code": null, "e": 31121, "s": 28662, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Autocomplete functionality</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #project-label {\n display: block;\n font-weight: bold;\n margin-bottom: 1em;\n }\n #project-icon {\n float: left;\n height: 32px;\n width: 32px;\n }\n #project-description {\n margin: 0;\n padding: 0;\n }\n </style>\n \n <!-- Javascript -->\n <script>\n $(function() {\n var projects = [\n {\n value: \"java\",\n label: \"Java\",\n desc: \"write once run anywhere\",\n },\n {\n value: \"jquery-ui\",\n label: \"jQuery UI\",\n desc: \"the official user interface library for jQuery\",\n },\n {\n value: \"Bootstrap\",\n label: \"Twitter Bootstrap\",\n desc: \"popular front end frameworks \",\n }\n ];\n $( \"#project\" ).autocomplete({\n minLength: 0,\n source: projects,\n focus: function( event, ui ) {\n $( \"#project\" ).val( ui.item.label );\n return false;\n },\n select: function( event, ui ) {\n $( \"#project\" ).val( ui.item.label );\n $( \"#project-id\" ).val( ui.item.value );\n $( \"#project-description\" ).html( ui.item.desc );\n return false;\n }\n })\n\t\t\t\t\n .data( \"ui-autocomplete\" )._renderItem = function( ul, item ) {\n return $( \"<li>\" )\n .append( \"<a>\" + item.label + \"<br>\" + item.desc + \"</a>\" )\n .appendTo( ul );\n };\n });\n </script>\n </head>\n \n <body>\n <div id = \"project-label\">Select a project (type \"a\" for a start):</div>\n <input id = \"project\">\n <input type = \"hidden\" id = \"project-id\">\n <p id = \"project-description\"></p>\n </body>\n</html>" }, { "code": null, "e": 31290, "s": 31121, "text": "Let us save the above code in an HTML file autocompleteexample.htm and open it in a standard browser which supports javascript. You must also see the following output −" }, { "code": null, "e": 31297, "s": 31290, "text": " Print" }, { "code": null, "e": 31308, "s": 31297, "text": " Add Notes" } ]
C Program for Minimum Cost Path
Here, we will solve the minimum cost path problem in C. The implication is done on a 2D-matrix where each cell has a cost to travel. We have to find a path from the left top corner to the bottom right corner with minimum travel cost. You can only traverse down and right lower cells from a given cell. To solve this particular problem dynamic programming is much better to approach than recursion. Given cost matrix cost[ ][ ] and a position (m,n), we have to write a function that returns cost of minimum path to reach (m,n) from (0,0).The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination). Assumption − All costs are positive. Negative cost cycles do not exist in the input matrix Find the minimum cost path to (2,2) The costs are given within the image itself. The path will be (0, 0) ⇒ (0, 1) ⇒ (1, 2) ⇒ (2, 2). The value of the path is eight (1 +2+2+ 3). Approach − Create an answer matrix of a similar size as the given matrix. Fill this matrix in a bottom-up manner. Given − arrA[ ][ ]. At each cell, we’ve got 2 options(go right or down) and that we can select the minimum of those 2, for any i,j cell. solution[i][j]=A[0][j] if i=0, 1st row =A[i][0] if j=0, 1st column =A[i][j]+Min(solution[i=1],[j],solution[i][j-1]) if i>0 && j>0 The approach followed in the algorithmic answers can be used to efficiently solve this problem by applying dynamic programming. Create a minimum cost path table of size m,n and define− minimumCostPath[i][j] = minimum value to achieve (i, j) from (0, 0) Clearly, minimumCostPath[0][0] = costMatrix[0][0] minimumCostPath[i][0] = minimumCostPath[i - 1][0] + costMatrix[i][0], for all values of i > zero minimumCostPath[0][j] = minimumCostPath[0][j - 1] + costMatrix[0][j], for all values of j >zero Next, we will fill the minimum cost path matrix by applying a similar formula that we applied in the algorithm. Since all the previous values will already have been calculated within the minimum cost path matrix, we will not recalculate these as we did in the algorithmic answer. minimumCostPath[i][j] = costMatrix[i][j] +minimum(minimumCostPath[i - 1][j - 1],minimumCostPath[i - 1][j],minimumCostPath[i][j - 1]) Here, for calculating minimumCostPath[i][j] we tend to use minimumCostPath[i - 1][j - 1], minimumCostPath[i - 1][j] and minimumCostPath[i][j - 1] as a result, these are the sole permissible cells from which we will reach minimumCostPath[i][j].Finally, we return minimumCostPath[m][n]. The time complexity of the dynamic programming algorithm is O(mn). Live Demo #include <iostream> using namespace std; int min_(int a, int b, int c){ if (a < b) return (a < c) ? a : c; else return (b < c) ? b : c; } int min_cost(int cost[4][4], int m, int n){ int i, j; int tot_cost[4][4]; tot_cost[0][0] = cost[0][0]; for (i = 1; i <= m; i++) tot_cost[i][0] = tot_cost[i - 1][0] + cost[i][0]; for (j = 1; j <= n; j++) tot_cost[0][j] = tot_cost[0][j - 1] + cost[0][j]; for (i = 1; i <= m; i++) for (j = 1; j <= n; j++) tot_cost[i][j] = min_(tot_cost[i - 1][j - 1], tot_cost[i - 1][j], tot_cost[i][j - 1]) + cost[i][j]; return tot_cost[m][n]; } int main(){ int cost[4][4] = { { 9, 9, 4 }, { 8, 0, 9 }, {1, 2, 8} }; cout<<" The minimum cost is "<<min_cost(cost, 2, 2); return 0; } The minimum cost is 17
[ { "code": null, "e": 1364, "s": 1062, "text": "Here, we will solve the minimum cost path problem in C. The implication is done on a 2D-matrix where each cell has a cost to travel. We have to find a path from the left top corner to the bottom right corner with minimum travel cost. You can only traverse down and right lower cells from a given cell." }, { "code": null, "e": 1460, "s": 1364, "text": "To solve this particular problem dynamic programming is much better to approach than recursion." }, { "code": null, "e": 1722, "s": 1460, "text": "Given cost matrix cost[ ][ ] and a position (m,n), we have to write a function that returns cost of minimum path to reach (m,n) from (0,0).The total cost of a path to reach (m, n) is the sum of all the costs on that path (including both source and destination)." }, { "code": null, "e": 1813, "s": 1722, "text": "Assumption − All costs are positive. Negative cost cycles do not exist in the input matrix" }, { "code": null, "e": 1849, "s": 1813, "text": "Find the minimum cost path to (2,2)" }, { "code": null, "e": 1990, "s": 1849, "text": "The costs are given within the image itself. The path will be (0, 0) ⇒ (0, 1) ⇒ (1, 2) ⇒ (2, 2). The value of the path is eight (1 +2+2+ 3)." }, { "code": null, "e": 2064, "s": 1990, "text": "Approach − Create an answer matrix of a similar size as the given matrix." }, { "code": null, "e": 2104, "s": 2064, "text": "Fill this matrix in a bottom-up manner." }, { "code": null, "e": 2241, "s": 2104, "text": "Given − arrA[ ][ ]. At each cell, we’ve got 2 options(go right or down) and that we can select the minimum of those 2, for any i,j cell." }, { "code": null, "e": 2374, "s": 2241, "text": "solution[i][j]=A[0][j] if i=0, 1st row\n =A[i][0] if j=0, 1st column\n=A[i][j]+Min(solution[i=1],[j],solution[i][j-1]) if i>0 && j>0" }, { "code": null, "e": 2559, "s": 2374, "text": "The approach followed in the algorithmic answers can be used to efficiently solve this problem by applying dynamic programming. Create a minimum cost path table of size m,n and define−" }, { "code": null, "e": 2627, "s": 2559, "text": "minimumCostPath[i][j] = minimum value to achieve (i, j) from (0, 0)" }, { "code": null, "e": 2636, "s": 2627, "text": "Clearly," }, { "code": null, "e": 2870, "s": 2636, "text": "minimumCostPath[0][0] = costMatrix[0][0]\nminimumCostPath[i][0] = minimumCostPath[i - 1][0] + costMatrix[i][0], for all values of i > zero\nminimumCostPath[0][j] = minimumCostPath[0][j - 1] + costMatrix[0][j], for all values of j >zero" }, { "code": null, "e": 3150, "s": 2870, "text": "Next, we will fill the minimum cost path matrix by applying a similar formula that we applied in the algorithm. Since all the previous values will already have been calculated within the minimum cost path matrix, we will not recalculate these as we did in the algorithmic answer." }, { "code": null, "e": 3283, "s": 3150, "text": "minimumCostPath[i][j] = costMatrix[i][j] +minimum(minimumCostPath[i - 1][j - 1],minimumCostPath[i - 1][j],minimumCostPath[i][j - 1])" }, { "code": null, "e": 3568, "s": 3283, "text": "Here, for calculating minimumCostPath[i][j] we tend to use minimumCostPath[i - 1][j - 1], minimumCostPath[i - 1][j] and minimumCostPath[i][j - 1] as a result, these are the sole permissible cells from which we will reach minimumCostPath[i][j].Finally, we return minimumCostPath[m][n]." }, { "code": null, "e": 3635, "s": 3568, "text": "The time complexity of the dynamic programming algorithm is O(mn)." }, { "code": null, "e": 3646, "s": 3635, "text": " Live Demo" }, { "code": null, "e": 4443, "s": 3646, "text": "#include <iostream>\nusing namespace std;\nint min_(int a, int b, int c){\n if (a < b)\n return (a < c) ? a : c;\n else\n return (b < c) ? b : c;\n}\nint min_cost(int cost[4][4], int m, int n){\n int i, j;\n int tot_cost[4][4];\n tot_cost[0][0] = cost[0][0];\n for (i = 1; i <= m; i++)\n tot_cost[i][0] = tot_cost[i - 1][0] + cost[i][0];\n for (j = 1; j <= n; j++)\n tot_cost[0][j] = tot_cost[0][j - 1] + cost[0][j];\n for (i = 1; i <= m; i++)\n for (j = 1; j <= n; j++)\n tot_cost[i][j] = min_(tot_cost[i - 1][j - 1], tot_cost[i - 1][j], tot_cost[i][j - 1]) + cost[i][j];\n return tot_cost[m][n];\n}\nint main(){\n int cost[4][4] = {\n { 9, 9, 4 },\n { 8, 0, 9 },\n {1, 2, 8}\n };\n cout<<\" The minimum cost is \"<<min_cost(cost, 2, 2);\n return 0;\n}" }, { "code": null, "e": 4466, "s": 4443, "text": "The minimum cost is 17" } ]
Duration ofMinutes(long) method in Java with Examples - GeeksforGeeks
26 Nov, 2018 The ofMinutes(long) method of Duration Class in java.time package is used to get a duration in a 1 minute format. In this method, the seconds are calculated as total seconds in 1 minute format, i.e. 60 seconds per minute. Syntax: public static Duration ofMinutes(long minutes) Parameters: This method accepts a parameter minutes which is the number of minutes. It can be positive or negative. Return Value: This method returns a Duration representing the time in 1 minute format. Exception: This method throws ArithmeticException if the input minutes exceeds the capacity of Duration. Below examples illustrate the Duration.ofMinutes() method: Example 1: // Java code to illustrate ofMinutes() method import java.time.Duration; public class GFG { public static void main(String[] args) { // input number of Minutes long noOfMinutes = 5; // Duration using ofMinutes() method Duration duration = Duration.ofMinutes(noOfMinutes); System.out.println(duration.getSeconds()); }} 300 Example 2: // Java code to illustrate ofMinutes() method import java.time.Duration; public class GFG { public static void main(String[] args) { // input number of Minutes long noOfMinutes = -214545; // Duration using ofMinutes() method Duration duration = Duration.ofMinutes(noOfMinutes); System.out.println(duration.getSeconds()); }} -12872700 Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofMinutes-long- Java-Duration Java-Functions Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java Stream In Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Singleton Class in Java Multithreading in Java
[ { "code": null, "e": 26391, "s": 26363, "text": "\n26 Nov, 2018" }, { "code": null, "e": 26613, "s": 26391, "text": "The ofMinutes(long) method of Duration Class in java.time package is used to get a duration in a 1 minute format. In this method, the seconds are calculated as total seconds in 1 minute format, i.e. 60 seconds per minute." }, { "code": null, "e": 26621, "s": 26613, "text": "Syntax:" }, { "code": null, "e": 26669, "s": 26621, "text": "public static Duration ofMinutes(long minutes)\n" }, { "code": null, "e": 26785, "s": 26669, "text": "Parameters: This method accepts a parameter minutes which is the number of minutes. It can be positive or negative." }, { "code": null, "e": 26872, "s": 26785, "text": "Return Value: This method returns a Duration representing the time in 1 minute format." }, { "code": null, "e": 26977, "s": 26872, "text": "Exception: This method throws ArithmeticException if the input minutes exceeds the capacity of Duration." }, { "code": null, "e": 27036, "s": 26977, "text": "Below examples illustrate the Duration.ofMinutes() method:" }, { "code": null, "e": 27047, "s": 27036, "text": "Example 1:" }, { "code": "// Java code to illustrate ofMinutes() method import java.time.Duration; public class GFG { public static void main(String[] args) { // input number of Minutes long noOfMinutes = 5; // Duration using ofMinutes() method Duration duration = Duration.ofMinutes(noOfMinutes); System.out.println(duration.getSeconds()); }}", "e": 27428, "s": 27047, "text": null }, { "code": null, "e": 27433, "s": 27428, "text": "300\n" }, { "code": null, "e": 27444, "s": 27433, "text": "Example 2:" }, { "code": "// Java code to illustrate ofMinutes() method import java.time.Duration; public class GFG { public static void main(String[] args) { // input number of Minutes long noOfMinutes = -214545; // Duration using ofMinutes() method Duration duration = Duration.ofMinutes(noOfMinutes); System.out.println(duration.getSeconds()); }}", "e": 27831, "s": 27444, "text": null }, { "code": null, "e": 27842, "s": 27831, "text": "-12872700\n" }, { "code": null, "e": 27935, "s": 27842, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/time/Duration.html#ofMinutes-long-" }, { "code": null, "e": 27949, "s": 27935, "text": "Java-Duration" }, { "code": null, "e": 27964, "s": 27949, "text": "Java-Functions" }, { "code": null, "e": 27982, "s": 27964, "text": "Java-time package" }, { "code": null, "e": 27987, "s": 27982, "text": "Java" }, { "code": null, "e": 27992, "s": 27987, "text": "Java" }, { "code": null, "e": 28090, "s": 27992, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28141, "s": 28090, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28156, "s": 28141, "text": "Stream In Java" }, { "code": null, "e": 28186, "s": 28156, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28205, "s": 28186, "text": "Interfaces in Java" }, { "code": null, "e": 28236, "s": 28205, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28254, "s": 28236, "text": "ArrayList in Java" }, { "code": null, "e": 28286, "s": 28254, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28306, "s": 28286, "text": "Stack Class in Java" }, { "code": null, "e": 28330, "s": 28306, "text": "Singleton Class in Java" } ]
How to get the title and URL of the page in Selenium with python?
We can get the title and URL of the page in Selenium. For getting the title of the browser, the title method is to be used. For getting the URL of the page, the current_url method is to be used. Both these methods can be used for testing if we are navigated to the correct page and page title. Code Implementation from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://www.tutorialspoint.com/index.htm") # to print the page title in console print(driver.title) # to print the current URL in console print(driver.current_url) #to refresh the browser driver.refresh() #to close the browser driver.close()
[ { "code": null, "e": 1116, "s": 1062, "text": "We can get the title and URL of the page in Selenium." }, { "code": null, "e": 1186, "s": 1116, "text": "For getting the title of the browser, the title method is to be used." }, { "code": null, "e": 1257, "s": 1186, "text": "For getting the URL of the page, the current_url method is to be used." }, { "code": null, "e": 1356, "s": 1257, "text": "Both these methods can be used for testing if we are navigated to the correct page and page title." }, { "code": null, "e": 1376, "s": 1356, "text": "Code Implementation" }, { "code": null, "e": 1948, "s": 1376, "text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n# to print the page title in console\nprint(driver.title)\n# to print the current URL in console\nprint(driver.current_url)\n#to refresh the browser\ndriver.refresh()\n#to close the browser\ndriver.close()" } ]
Calculate Efficiency Of Binary Classifier - GeeksforGeeks
01 Oct, 2021 Prerequisite: target=”_blank”>Getting started with Classification In this article, we will discuss a method to calculate the efficiency of a Binary classifier. Let’s assume there is a problem where we have to classify a product that belongs to either class A or class B. Let us define few statistical parameters : TP (True Positive) = number of Class A products, which are classified as Class A products. FN (False Negative) = number of Class A products, which are classified as Class B products. TN (True Negative) = number of Class B products, which are classified as Class B products. FP (False Positive) = number of Class B products, which are classified as Class A products. FP = N-TP; // where number N is the number of class A type products FN = M-TN; // where number M is the number of class B type products We shall look at this example, to understand these parameters well. If (+) denotes fit candidates for Job and (-) denotes unfit candidates for Job. To calculate the Efficiency of the classifier we need to compute values of Sensitivity, Specificity, and Accuracy. Sensitivity measures the proportion of positives that are correctly identified as such. Also known as True positive rate(TPR). Specificity measures the proportion of negatives that are correctly identified as such. Also known as True negative rate(TNR). Accuracy measures how well the test predicts both TPR and TNR. Sensitivity = ( TP / (TP+FN) ) * 100; Specificity = ( TN/(TN+FP) ) * 100; Accuracy = ( (TP+TN) / (TP+TN+FP+FN) ) * 100; Efficiency = ( Sensitivity + Specificity + Accuracy ) / 3; Let’s take the above example and compute the efficiency of selection : Say fit candidates belong to class A and unfit candidates belong to class B. Before Interview : N = 4 and M = 4 After Interview : TP = 2 TN = 2 FP = N - TP = 2 FN = M - TN = 2 Sensitivity = 2/(2+2)*100 = 50 Specificity = 2/(2+2)*100 = 50 Accuracy = (2+2)/(2+2+2+2)*100 = 50 Efficiency = (50+50+50)/3 = 50 So,Efficiency of selection of candidates is 50% accurate. Other performance measures: Error rate = (FP + FN) / (TP + TN + FP + FN) Precision = TP / (TP + FP) Recall = TP / (TP + FN) BCR (Balanced Classification Rate) = 1/2* (TP / (TP + FN) + TN / (TN + FP)) AUC = Area under ROC curve Receiver Operating Characteristic Curve: Receiver operating characteristic(ROC) curve: 2-D curve parameterized by one parameter of the classification algorithm. AUC is always between 0 and 1. ROC curve can be obtained by plotting TPR on the y-axis and TNR on the x-axis. AUC gives accuracy to the proposed model. References: https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers http://www.lifenscience.com/bioinformatics/sensitivity-specificity-accuracy-and akshaysingh98088 vaibhavsinghtanwar GBlog Machine Learning Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar Top 10 Projects For Beginners To Practice HTML and CSS Skills Types of Software Testing Working with csv files in Python How to Start Learning DSA? Naive Bayes Classifiers Linear Regression (Python Implementation) ML | Linear Regression Reinforcement learning Removing stop words with NLTK in Python
[ { "code": null, "e": 25881, "s": 25853, "text": "\n01 Oct, 2021" }, { "code": null, "e": 25948, "s": 25881, "text": "Prerequisite: target=”_blank”>Getting started with Classification " }, { "code": null, "e": 26154, "s": 25948, "text": "In this article, we will discuss a method to calculate the efficiency of a Binary classifier. Let’s assume there is a problem where we have to classify a product that belongs to either class A or class B. " }, { "code": null, "e": 26199, "s": 26154, "text": "Let us define few statistical parameters : " }, { "code": null, "e": 26565, "s": 26199, "text": "TP (True Positive) = number of Class A products, which are classified as Class A products. FN (False Negative) = number of Class A products, which are classified as Class B products. TN (True Negative) = number of Class B products, which are classified as Class B products. FP (False Positive) = number of Class B products, which are classified as Class A products." }, { "code": null, "e": 26710, "s": 26565, "text": "FP = N-TP; // where number N is the number of class A type products\nFN = M-TN; // where number M is the number of class B type products" }, { "code": null, "e": 26779, "s": 26710, "text": "We shall look at this example, to understand these parameters well. " }, { "code": null, "e": 26860, "s": 26779, "text": "If (+) denotes fit candidates for Job and (-) denotes unfit candidates for Job. " }, { "code": null, "e": 26977, "s": 26860, "text": "To calculate the Efficiency of the classifier we need to compute values of Sensitivity, Specificity, and Accuracy. " }, { "code": null, "e": 27105, "s": 26977, "text": "Sensitivity measures the proportion of positives that are correctly identified as such. Also known as True positive rate(TPR). " }, { "code": null, "e": 27233, "s": 27105, "text": "Specificity measures the proportion of negatives that are correctly identified as such. Also known as True negative rate(TNR). " }, { "code": null, "e": 27297, "s": 27233, "text": "Accuracy measures how well the test predicts both TPR and TNR. " }, { "code": null, "e": 27477, "s": 27297, "text": "Sensitivity = ( TP / (TP+FN) ) * 100;\nSpecificity = ( TN/(TN+FP) ) * 100;\nAccuracy = ( (TP+TN) / (TP+TN+FP+FN) ) * 100;\nEfficiency = ( Sensitivity + Specificity + Accuracy ) / 3; " }, { "code": null, "e": 27549, "s": 27477, "text": "Let’s take the above example and compute the efficiency of selection : " }, { "code": null, "e": 27628, "s": 27549, "text": "Say fit candidates belong to class A and unfit candidates belong to class B. " }, { "code": null, "e": 27925, "s": 27628, "text": "Before Interview : N = 4 and M = 4\n\nAfter Interview : \nTP = 2 \nTN = 2 \nFP = N - TP = 2\nFN = M - TN = 2\n\nSensitivity = 2/(2+2)*100 = 50\nSpecificity = 2/(2+2)*100 = 50\nAccuracy = (2+2)/(2+2+2+2)*100 = 50\nEfficiency = (50+50+50)/3 = 50\n\nSo,Efficiency of selection of candidates is 50% accurate." }, { "code": null, "e": 27955, "s": 27925, "text": "Other performance measures: " }, { "code": null, "e": 28000, "s": 27955, "text": "Error rate = (FP + FN) / (TP + TN + FP + FN)" }, { "code": null, "e": 28027, "s": 28000, "text": "Precision = TP / (TP + FP)" }, { "code": null, "e": 28051, "s": 28027, "text": "Recall = TP / (TP + FN)" }, { "code": null, "e": 28127, "s": 28051, "text": "BCR (Balanced Classification Rate) = 1/2* (TP / (TP + FN) + TN / (TN + FP))" }, { "code": null, "e": 28154, "s": 28127, "text": "AUC = Area under ROC curve" }, { "code": null, "e": 28197, "s": 28154, "text": "Receiver Operating Characteristic Curve: " }, { "code": null, "e": 28318, "s": 28197, "text": "Receiver operating characteristic(ROC) curve: 2-D curve parameterized by one parameter of the classification algorithm. " }, { "code": null, "e": 28349, "s": 28318, "text": "AUC is always between 0 and 1." }, { "code": null, "e": 28428, "s": 28349, "text": "ROC curve can be obtained by plotting TPR on the y-axis and TNR on the x-axis." }, { "code": null, "e": 28470, "s": 28428, "text": "AUC gives accuracy to the proposed model." }, { "code": null, "e": 28484, "s": 28470, "text": " References: " }, { "code": null, "e": 28548, "s": 28484, "text": "https://en.wikipedia.org/wiki/Evaluation_of_binary_classifiers " }, { "code": null, "e": 28628, "s": 28548, "text": "http://www.lifenscience.com/bioinformatics/sensitivity-specificity-accuracy-and" }, { "code": null, "e": 28647, "s": 28630, "text": "akshaysingh98088" }, { "code": null, "e": 28666, "s": 28647, "text": "vaibhavsinghtanwar" }, { "code": null, "e": 28672, "s": 28666, "text": "GBlog" }, { "code": null, "e": 28689, "s": 28672, "text": "Machine Learning" }, { "code": null, "e": 28706, "s": 28689, "text": "Machine Learning" }, { "code": null, "e": 28804, "s": 28706, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28829, "s": 28804, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 28891, "s": 28829, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28917, "s": 28891, "text": "Types of Software Testing" }, { "code": null, "e": 28950, "s": 28917, "text": "Working with csv files in Python" }, { "code": null, "e": 28977, "s": 28950, "text": "How to Start Learning DSA?" }, { "code": null, "e": 29001, "s": 28977, "text": "Naive Bayes Classifiers" }, { "code": null, "e": 29043, "s": 29001, "text": "Linear Regression (Python Implementation)" }, { "code": null, "e": 29066, "s": 29043, "text": "ML | Linear Regression" }, { "code": null, "e": 29089, "s": 29066, "text": "Reinforcement learning" } ]
C# | String.Contains() Method - GeeksforGeeks
06 Jan, 2020 In C#, String.Contains() is a string method. This method is used to check whether the substring occurs within a given string or not. Syntax: public bool Contains(string str) Parameter: str: It is the string which is to be checked. Type of this parameter is System.String. Return Value: It returns the boolean value. If substring exists in string or value is the empty string (“”), then it returns True, otherwise returns False. Exception: This method can give ArgumentNullException if str is null. Note: This method performs the case-sensitive checking. The search will always begin from the first character position of the string and continues until the last character position. Below are the programs illustrate the Contains() Method. Program 1: // C# program to demonstrate the// String.Contains() Methodusing System; class Geeks { // Main Method public static void Main() { // string type String str = "GeeksforGeeks"; String substr1 = "for"; String substr2 = "For"; // using String.Contains() Method Console.WriteLine(str.Contains(substr1)); // Here case-sensitive comparison // And substr2 value is 'For' // So its return false Console.WriteLine(str.Contains(substr2)); }} True False Program 2: To determine whether a substring is present in a string using ordinal comparison and case-insensitive ordinal comparison. // C# program to illustrate the// String.Contains() Method using// ordinal comparison and case-// insensitive ordinal comparisonusing System; public static class StringExtensions { // defines a String extension method // which includes a StringComparison parameter public static bool Contains(this String str, String substr, StringComparison cmp) { if (substr == null) throw new ArgumentNullException("substring substring", " cannot be null."); else if (!Enum.IsDefined(typeof(StringComparison), cmp)) throw new ArgumentException("comp is not a member of", "StringComparison, comp"); return str.IndexOf(substr, cmp) >= 0; }} // Driver Classclass Geeks { // Main Method public static void Main() { String str = "GeeksforGeeks"; String substr = "FOR"; // For Ordinal StringComparison comp = StringComparison.Ordinal; Console.WriteLine("For {0:G}: {1}", comp, str.Contains(substr, comp)); // for OrdinalIgnoreCase comp = StringComparison.OrdinalIgnoreCase; Console.WriteLine("For {0:G}: {1}", comp, str.Contains(substr, comp)); }} For Ordinal: False For OrdinalIgnoreCase: True Program 3: The following example determines whether the string “Computer” is a substring of given string. If it is found in the string, it also displays its starting position. // C# program to demonstrate the// String.Contains() Method// along with the starting positionusing System; class Example { public static void Main() { string sub1 = "GeeksforGeeks is a Computer Science Portal"; string sub2 = "Computer"; // Check if the substring is // present in the main string bool b = sub1.Contains(sub2); Console.WriteLine("'{0}' is in the string '{1}': {2}", sub2, sub1, b); if (b) { int index = sub1.IndexOf(sub2); if (index >= 0) Console.WriteLine("{0} begins at character position {1}", sub2, index + 1); } }} 'Computer' is in the string 'GeeksforGeeks is a Computer Science Portal': True Computer begins at character position 20 Reference: https://msdn.microsoft.com/en-us/library/system.string.contains Akanksha_Rai CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Class and Object C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Delegates C# | Data Types Difference between Ref and Out keywords in C# HashSet in C# with Examples C# | Replace() Method C# | Abstract Classes
[ { "code": null, "e": 24406, "s": 24378, "text": "\n06 Jan, 2020" }, { "code": null, "e": 24539, "s": 24406, "text": "In C#, String.Contains() is a string method. This method is used to check whether the substring occurs within a given string or not." }, { "code": null, "e": 24547, "s": 24539, "text": "Syntax:" }, { "code": null, "e": 24580, "s": 24547, "text": "public bool Contains(string str)" }, { "code": null, "e": 24591, "s": 24580, "text": "Parameter:" }, { "code": null, "e": 24678, "s": 24591, "text": "str: It is the string which is to be checked. Type of this parameter is System.String." }, { "code": null, "e": 24834, "s": 24678, "text": "Return Value: It returns the boolean value. If substring exists in string or value is the empty string (“”), then it returns True, otherwise returns False." }, { "code": null, "e": 24904, "s": 24834, "text": "Exception: This method can give ArgumentNullException if str is null." }, { "code": null, "e": 25086, "s": 24904, "text": "Note: This method performs the case-sensitive checking. The search will always begin from the first character position of the string and continues until the last character position." }, { "code": null, "e": 25143, "s": 25086, "text": "Below are the programs illustrate the Contains() Method." }, { "code": null, "e": 25154, "s": 25143, "text": "Program 1:" }, { "code": "// C# program to demonstrate the// String.Contains() Methodusing System; class Geeks { // Main Method public static void Main() { // string type String str = \"GeeksforGeeks\"; String substr1 = \"for\"; String substr2 = \"For\"; // using String.Contains() Method Console.WriteLine(str.Contains(substr1)); // Here case-sensitive comparison // And substr2 value is 'For' // So its return false Console.WriteLine(str.Contains(substr2)); }}", "e": 25676, "s": 25154, "text": null }, { "code": null, "e": 25688, "s": 25676, "text": "True\nFalse\n" }, { "code": null, "e": 25821, "s": 25688, "text": "Program 2: To determine whether a substring is present in a string using ordinal comparison and case-insensitive ordinal comparison." }, { "code": "// C# program to illustrate the// String.Contains() Method using// ordinal comparison and case-// insensitive ordinal comparisonusing System; public static class StringExtensions { // defines a String extension method // which includes a StringComparison parameter public static bool Contains(this String str, String substr, StringComparison cmp) { if (substr == null) throw new ArgumentNullException(\"substring substring\", \" cannot be null.\"); else if (!Enum.IsDefined(typeof(StringComparison), cmp)) throw new ArgumentException(\"comp is not a member of\", \"StringComparison, comp\"); return str.IndexOf(substr, cmp) >= 0; }} // Driver Classclass Geeks { // Main Method public static void Main() { String str = \"GeeksforGeeks\"; String substr = \"FOR\"; // For Ordinal StringComparison comp = StringComparison.Ordinal; Console.WriteLine(\"For {0:G}: {1}\", comp, str.Contains(substr, comp)); // for OrdinalIgnoreCase comp = StringComparison.OrdinalIgnoreCase; Console.WriteLine(\"For {0:G}: {1}\", comp, str.Contains(substr, comp)); }}", "e": 27183, "s": 25821, "text": null }, { "code": null, "e": 27231, "s": 27183, "text": "For Ordinal: False\nFor OrdinalIgnoreCase: True\n" }, { "code": null, "e": 27407, "s": 27231, "text": "Program 3: The following example determines whether the string “Computer” is a substring of given string. If it is found in the string, it also displays its starting position." }, { "code": "// C# program to demonstrate the// String.Contains() Method// along with the starting positionusing System; class Example { public static void Main() { string sub1 = \"GeeksforGeeks is a Computer Science Portal\"; string sub2 = \"Computer\"; // Check if the substring is // present in the main string bool b = sub1.Contains(sub2); Console.WriteLine(\"'{0}' is in the string '{1}': {2}\", sub2, sub1, b); if (b) { int index = sub1.IndexOf(sub2); if (index >= 0) Console.WriteLine(\"{0} begins at character position {1}\", sub2, index + 1); } }}", "e": 28108, "s": 27407, "text": null }, { "code": null, "e": 28229, "s": 28108, "text": "'Computer' is in the string 'GeeksforGeeks is a Computer Science Portal': True\nComputer begins at character position 20\n" }, { "code": null, "e": 28304, "s": 28229, "text": "Reference: https://msdn.microsoft.com/en-us/library/system.string.contains" }, { "code": null, "e": 28317, "s": 28304, "text": "Akanksha_Rai" }, { "code": null, "e": 28331, "s": 28317, "text": "CSharp-method" }, { "code": null, "e": 28345, "s": 28331, "text": "CSharp-string" }, { "code": null, "e": 28348, "s": 28345, "text": "C#" }, { "code": null, "e": 28446, "s": 28348, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28455, "s": 28446, "text": "Comments" }, { "code": null, "e": 28468, "s": 28455, "text": "Old Comments" }, { "code": null, "e": 28490, "s": 28468, "text": "C# | Class and Object" }, { "code": null, "e": 28508, "s": 28490, "text": "C# | Constructors" }, { "code": null, "e": 28531, "s": 28508, "text": "Extension Method in C#" }, { "code": null, "e": 28562, "s": 28531, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28577, "s": 28562, "text": "C# | Delegates" }, { "code": null, "e": 28593, "s": 28577, "text": "C# | Data Types" }, { "code": null, "e": 28639, "s": 28593, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28667, "s": 28639, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28689, "s": 28667, "text": "C# | Replace() Method" } ]
Tryit Editor v3.7
Tryit: HSL Saturation
[]
Generate 10 random four-digit numbers in Java
To generated random integer, use the Random class with nextInt. At first, create a Random object − Random rand = new Random(); The Random above is a random number generator. Now, pick the random numbers one by one. We want 10 random four-digit numbers, therefore loop it until i = 1 to 10 − for (int i = 1; i<= 10; i++) { intresRandom = rand.nextInt((9999 - 100) + 1) + 10; System.out.println(resRandom); } The following is an example to generate 10 random four-digit numbers − Live Demo import java.util.Random; public class Demo { public static void main(String[] args) { Random rand = new Random(); System.out.println("Random numbers..."); for (int i = 1; i<= 10; i++) { int resRandom = rand.nextInt((9999 - 100) + 1) + 10; System.out.println(resRandom); } } } Random numbers... 6075 4943 2141 5701 4181 9534 3539 6793 3058 4766
[ { "code": null, "e": 1161, "s": 1062, "text": "To generated random integer, use the Random class with nextInt. At first, create a Random object −" }, { "code": null, "e": 1189, "s": 1161, "text": "Random rand = new Random();" }, { "code": null, "e": 1353, "s": 1189, "text": "The Random above is a random number generator. Now, pick the random numbers one by one. We want 10 random four-digit numbers, therefore loop it until i = 1 to 10 −" }, { "code": null, "e": 1475, "s": 1353, "text": "for (int i = 1; i<= 10; i++) {\n intresRandom = rand.nextInt((9999 - 100) + 1) + 10;\n System.out.println(resRandom);\n}" }, { "code": null, "e": 1546, "s": 1475, "text": "The following is an example to generate 10 random four-digit numbers −" }, { "code": null, "e": 1557, "s": 1546, "text": " Live Demo" }, { "code": null, "e": 1881, "s": 1557, "text": "import java.util.Random;\npublic class Demo {\n public static void main(String[] args) {\n Random rand = new Random();\n System.out.println(\"Random numbers...\");\n for (int i = 1; i<= 10; i++) {\n int resRandom = rand.nextInt((9999 - 100) + 1) + 10;\n System.out.println(resRandom);\n }\n }\n}" }, { "code": null, "e": 1949, "s": 1881, "text": "Random numbers...\n6075\n4943\n2141\n5701\n4181\n9534\n3539\n6793\n3058\n4766" } ]
Superperfect Number - GeeksforGeeks
28 Jan, 2022 Given an integer n. Check whether the number n is superperfect number or not. A superperfect number is a positive integer which satisfies σ2(n) = σ(σ(n)) = 2n, where σ is divisor summatory function. Input: n = 16 Output: yes Explanation: 16 is a superperfect number as σ(16) = 1 + 2 + 4 + 8 + 16 = 31, and σ(31) = 1 + 31 = 32, thus σ(σ(16)) = 32 = 2 × 16. Input: n = 8 Output: no Explanation: σ(8) = 1 + 2 + 4 + 8 = 15 and σ(15) = 1 + 3 + 5 + 15 = 24 thus ( σ(σ(8)) = 24 ) ≠ (2 * 8 = 26) The idea is simply straightforward. We just iterate from 1 to sqrt(n) and find sum of all divisors of n, lets we call this sum as n1. Now we again need to iterate from 1 to sqrt(n1) and find sum of all divisors. After that we just need to check whether the resulted sum is equal to 2*n or not. C++ Java Python3 C# PHP Javascript // C++ program to check whether number is// superperfect or not#include<bits/stdc++.h>using namespace std; // Function to calculate sum of all divisorsint divSum(int num){ // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i=1; i*i <= num; ++i) { // if 'i' is divisor of 'num' if (num%i == 0) { // if both divisors are same then add // it only once else add both if (i == (num/i)) result += i; else result += (i + num/i); } } return result;} // Returns true if n is Super Perfect else false.bool isSuperPerfect(int n){ // Find the sum of all divisors of number n int n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2*n == divSum(n1));} //Driver codeint main(){ int n = 16; cout << (isSuperPerfect(n) ? "Yes\n" : "No\n"); n = 6; cout << (isSuperPerfect(n) ? "Yes\n" : "No\n"); return 0;} // Java program to check whether number is// superperfect or not public class Divisors{ // Function to calculate sum of all divisors static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i=1; i*i <= num; ++i) { // if 'i' is divisor of 'num' if (num%i == 0) { // if both divisors are same then add // it only once else add both if (i == (num/i)) result += i; else result += (i + num/i); } } return result; } // Returns true if n is Super Perfect else false. static boolean isSuperPerfect(int n) { // Find the sum of all divisors of number n int n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2*n == divSum(n1)); } public static void main (String[] args) { int n = 16; System.out.printf((isSuperPerfect(n) ? "Yes\n" : "No\n")); n = 6; System.out.printf((isSuperPerfect(n) ? "Yes\n" : "No\n")); }} // This code is contributed by Saket Kumar # Python program to check whether number# is superperfect or notimport math # Function to calculate sum of all divisorsdef divSum(num): # Final result of summation of divisors result = 0 # find all divisors which divides 'num' sq = int(math.sqrt(num)) for i in range(1, sq+1): # if 'i' is divisor of 'num' if num %i == 0: # if both divisors are same then add # it only once else add both if i == (num//i): result += i else: result += (i + num//i) return result # Returns true if n is superperfect else falsedef isSuperPerfect(n): # Find the sum of all divisors of number n n1 = divSum(n) # Again find the sum of all divisors of n1 return divSum(n1) == 2*n #Driver coden = 16print ('Yes' if isSuperPerfect(n) else 'No') n = 6print ('Yes' if isSuperPerfect(n) else 'No') // C# program to check whether number is// superperfect or notusing System; class Divisors{ // Function to calculate sum of all divisors static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i = 1; i * i <= num; ++i) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num / i)) result += i; else result += (i + num / i); } } return result; } // Returns true if n is Super Perfect else false. static bool isSuperPerfect(int n) { // Find the sum of all divisors of number n int n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2 * n == divSum(n1)); } public static void Main () { int n = 16; Console.WriteLine((isSuperPerfect(n) ? "Yes" : "No")); n = 6; Console.WriteLine((isSuperPerfect(n) ? "Yes" : "No")); }} // This code is contributed by vt_m. <?php// PHP program to check whether// number is superperfect or not // Function to calculate// sum of all divisorsfunction divSum($num){ // Final result of // summation of divisors $result = 0; // find all divisors // which divides 'num' for ($i = 1; $i * $i <= $num; ++$i) { // if 'i' is divisor // of 'num' if ($num % $i == 0) { // if both divisors // are same then add // it only once else // add both if ($i == ($num / $i)) $result += $i; else $result += ($i + $num/$i); } } return $result;} // Returns true if n is// Super Perfect else false.function isSuperPerfect($n){ // Find the sum of all // divisors of number n $n1 = divSum($n); // Again find the sum // of all divisors of n1 // and check if sum is // equal to n1 return (2 * $n == divSum($n1));} // Driver code $n = 16; $hh = (isSuperPerfect($n) ? "Yes\n" : "No\n"); echo($hh); $n = 6; $hh=(isSuperPerfect($n) ? "Yes\n" : "No\n"); echo($hh); // This code is contributed by AJit?> <script> // JavaScript program for the above approach // Function to calculate sum of all divisors function divSum(num) { // Final result of summation of divisors let result = 0; // find all divisors which divides 'num' for (let i = 1; i * i <= num; ++i) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num/i)) result += i; else result += (i + num/i); } } return result; } // Returns true if n is Super Perfect else false. function isSuperPerfect(n) { // Find the sum of all divisors of number n let n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2*n == divSum(n1)); } // Driver Code let n = 16; document.write((isSuperPerfect(n) ? "Yes\n" : "No\n") + "<br />"); n = 6; document.write((isSuperPerfect(n) ? "Yes\n" : "No\n") + "<br />"); // This code is contributed by splevel62.</script> Output: Yes No Time complexity: O(sqrt(n + n1)) where n1 is sum of divisors of n. Auxiliary space: O(1)Facts about Supernumbers: If n is an even superperfect number, then n must be a power of 2 i.e., 2k such that 2k+1 – 1 is a Mersenne prime.It is not known whether there are any odd superperfect numbers. An odd superperfect number n would have to be a square number such that either n or σ(n) is divisible by at least three distinct primes. There are no odd superperfect numbers below 7×1024 If n is an even superperfect number, then n must be a power of 2 i.e., 2k such that 2k+1 – 1 is a Mersenne prime. It is not known whether there are any odd superperfect numbers. An odd superperfect number n would have to be a square number such that either n or σ(n) is divisible by at least three distinct primes. There are no odd superperfect numbers below 7×1024 Reference: https://en.wikipedia.org/wiki/Superperfect_numberThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t splevel62 amartyaghoshgfg series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Program for Decimal to Binary Conversion Program to find sum of elements in a given array The Knight's tour problem | Backtracking-1 Program for factorial of a number Find all factors of a natural number | Set 1 Operators in C / C++
[ { "code": null, "e": 24587, "s": 24559, "text": "\n28 Jan, 2022" }, { "code": null, "e": 24788, "s": 24587, "text": "Given an integer n. Check whether the number n is superperfect number or not. A superperfect number is a positive integer which satisfies σ2(n) = σ(σ(n)) = 2n, where σ is divisor summatory function. " }, { "code": null, "e": 25081, "s": 24788, "text": "Input: n = 16\nOutput: yes\nExplanation:\n16 is a superperfect number as σ(16) = 1 + 2 + 4 + 8 + 16 = 31,\nand σ(31) = 1 + 31 = 32, \nthus σ(σ(16)) = 32 = 2 × 16.\n\nInput: n = 8\nOutput: no \nExplanation:\nσ(8) = 1 + 2 + 4 + 8 = 15\nand σ(15) = 1 + 3 + 5 + 15 = 24\nthus ( σ(σ(8)) = 24 ) ≠ (2 * 8 = 26)" }, { "code": null, "e": 25379, "s": 25083, "text": "The idea is simply straightforward. We just iterate from 1 to sqrt(n) and find sum of all divisors of n, lets we call this sum as n1. Now we again need to iterate from 1 to sqrt(n1) and find sum of all divisors. After that we just need to check whether the resulted sum is equal to 2*n or not. " }, { "code": null, "e": 25383, "s": 25379, "text": "C++" }, { "code": null, "e": 25388, "s": 25383, "text": "Java" }, { "code": null, "e": 25396, "s": 25388, "text": "Python3" }, { "code": null, "e": 25399, "s": 25396, "text": "C#" }, { "code": null, "e": 25403, "s": 25399, "text": "PHP" }, { "code": null, "e": 25414, "s": 25403, "text": "Javascript" }, { "code": "// C++ program to check whether number is// superperfect or not#include<bits/stdc++.h>using namespace std; // Function to calculate sum of all divisorsint divSum(int num){ // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i=1; i*i <= num; ++i) { // if 'i' is divisor of 'num' if (num%i == 0) { // if both divisors are same then add // it only once else add both if (i == (num/i)) result += i; else result += (i + num/i); } } return result;} // Returns true if n is Super Perfect else false.bool isSuperPerfect(int n){ // Find the sum of all divisors of number n int n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2*n == divSum(n1));} //Driver codeint main(){ int n = 16; cout << (isSuperPerfect(n) ? \"Yes\\n\" : \"No\\n\"); n = 6; cout << (isSuperPerfect(n) ? \"Yes\\n\" : \"No\\n\"); return 0;}", "e": 26469, "s": 25414, "text": null }, { "code": "// Java program to check whether number is// superperfect or not public class Divisors{ // Function to calculate sum of all divisors static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i=1; i*i <= num; ++i) { // if 'i' is divisor of 'num' if (num%i == 0) { // if both divisors are same then add // it only once else add both if (i == (num/i)) result += i; else result += (i + num/i); } } return result; } // Returns true if n is Super Perfect else false. static boolean isSuperPerfect(int n) { // Find the sum of all divisors of number n int n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2*n == divSum(n1)); } public static void main (String[] args) { int n = 16; System.out.printf((isSuperPerfect(n) ? \"Yes\\n\" : \"No\\n\")); n = 6; System.out.printf((isSuperPerfect(n) ? \"Yes\\n\" : \"No\\n\")); }} // This code is contributed by Saket Kumar", "e": 27760, "s": 26469, "text": null }, { "code": "# Python program to check whether number# is superperfect or notimport math # Function to calculate sum of all divisorsdef divSum(num): # Final result of summation of divisors result = 0 # find all divisors which divides 'num' sq = int(math.sqrt(num)) for i in range(1, sq+1): # if 'i' is divisor of 'num' if num %i == 0: # if both divisors are same then add # it only once else add both if i == (num//i): result += i else: result += (i + num//i) return result # Returns true if n is superperfect else falsedef isSuperPerfect(n): # Find the sum of all divisors of number n n1 = divSum(n) # Again find the sum of all divisors of n1 return divSum(n1) == 2*n #Driver coden = 16print ('Yes' if isSuperPerfect(n) else 'No') n = 6print ('Yes' if isSuperPerfect(n) else 'No')", "e": 28657, "s": 27760, "text": null }, { "code": "// C# program to check whether number is// superperfect or notusing System; class Divisors{ // Function to calculate sum of all divisors static int divSum(int num) { // Final result of summation of divisors int result = 0; // find all divisors which divides 'num' for (int i = 1; i * i <= num; ++i) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num / i)) result += i; else result += (i + num / i); } } return result; } // Returns true if n is Super Perfect else false. static bool isSuperPerfect(int n) { // Find the sum of all divisors of number n int n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2 * n == divSum(n1)); } public static void Main () { int n = 16; Console.WriteLine((isSuperPerfect(n) ? \"Yes\" : \"No\")); n = 6; Console.WriteLine((isSuperPerfect(n) ? \"Yes\" : \"No\")); }} // This code is contributed by vt_m.", "e": 29934, "s": 28657, "text": null }, { "code": "<?php// PHP program to check whether// number is superperfect or not // Function to calculate// sum of all divisorsfunction divSum($num){ // Final result of // summation of divisors $result = 0; // find all divisors // which divides 'num' for ($i = 1; $i * $i <= $num; ++$i) { // if 'i' is divisor // of 'num' if ($num % $i == 0) { // if both divisors // are same then add // it only once else // add both if ($i == ($num / $i)) $result += $i; else $result += ($i + $num/$i); } } return $result;} // Returns true if n is// Super Perfect else false.function isSuperPerfect($n){ // Find the sum of all // divisors of number n $n1 = divSum($n); // Again find the sum // of all divisors of n1 // and check if sum is // equal to n1 return (2 * $n == divSum($n1));} // Driver code $n = 16; $hh = (isSuperPerfect($n) ? \"Yes\\n\" : \"No\\n\"); echo($hh); $n = 6; $hh=(isSuperPerfect($n) ? \"Yes\\n\" : \"No\\n\"); echo($hh); // This code is contributed by AJit?>", "e": 31126, "s": 29934, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to calculate sum of all divisors function divSum(num) { // Final result of summation of divisors let result = 0; // find all divisors which divides 'num' for (let i = 1; i * i <= num; ++i) { // if 'i' is divisor of 'num' if (num % i == 0) { // if both divisors are same then add // it only once else add both if (i == (num/i)) result += i; else result += (i + num/i); } } return result; } // Returns true if n is Super Perfect else false. function isSuperPerfect(n) { // Find the sum of all divisors of number n let n1 = divSum(n); // Again find the sum of all divisors of n1 // and check if sum is equal to n1 return (2*n == divSum(n1)); } // Driver Code let n = 16; document.write((isSuperPerfect(n) ? \"Yes\\n\" : \"No\\n\") + \"<br />\"); n = 6; document.write((isSuperPerfect(n) ? \"Yes\\n\" : \"No\\n\") + \"<br />\"); // This code is contributed by splevel62.</script>", "e": 32398, "s": 31126, "text": null }, { "code": null, "e": 32413, "s": 32398, "text": "Output:\nYes\nNo" }, { "code": null, "e": 32529, "s": 32413, "text": "Time complexity: O(sqrt(n + n1)) where n1 is sum of divisors of n. Auxiliary space: O(1)Facts about Supernumbers: " }, { "code": null, "e": 32894, "s": 32529, "text": "If n is an even superperfect number, then n must be a power of 2 i.e., 2k such that 2k+1 – 1 is a Mersenne prime.It is not known whether there are any odd superperfect numbers. An odd superperfect number n would have to be a square number such that either n or σ(n) is divisible by at least three distinct primes. There are no odd superperfect numbers below 7×1024" }, { "code": null, "e": 33008, "s": 32894, "text": "If n is an even superperfect number, then n must be a power of 2 i.e., 2k such that 2k+1 – 1 is a Mersenne prime." }, { "code": null, "e": 33260, "s": 33008, "text": "It is not known whether there are any odd superperfect numbers. An odd superperfect number n would have to be a square number such that either n or σ(n) is divisible by at least three distinct primes. There are no odd superperfect numbers below 7×1024" }, { "code": null, "e": 33743, "s": 33260, "text": "Reference: https://en.wikipedia.org/wiki/Superperfect_numberThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33749, "s": 33743, "text": "jit_t" }, { "code": null, "e": 33759, "s": 33749, "text": "splevel62" }, { "code": null, "e": 33775, "s": 33759, "text": "amartyaghoshgfg" }, { "code": null, "e": 33782, "s": 33775, "text": "series" }, { "code": null, "e": 33795, "s": 33782, "text": "Mathematical" }, { "code": null, "e": 33808, "s": 33795, "text": "Mathematical" }, { "code": null, "e": 33815, "s": 33808, "text": "series" }, { "code": null, "e": 33913, "s": 33815, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33922, "s": 33913, "text": "Comments" }, { "code": null, "e": 33935, "s": 33922, "text": "Old Comments" }, { "code": null, "e": 33959, "s": 33935, "text": "Merge two sorted arrays" }, { "code": null, "e": 34002, "s": 33959, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 34016, "s": 34002, "text": "Prime Numbers" }, { "code": null, "e": 34058, "s": 34016, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 34099, "s": 34058, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 34148, "s": 34099, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 34191, "s": 34148, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 34225, "s": 34191, "text": "Program for factorial of a number" }, { "code": null, "e": 34270, "s": 34225, "text": "Find all factors of a natural number | Set 1" } ]
How to determine the percentiles of a vector values in R?
Percentile helps us to determine the values that lie at a certain percent in a data set. For example, if we have a vector of size 100 with containing any values and suppose that the tenth-percentile of the vector is 25, which means there are ten percent values in the vector that are less than 25, or we can say, there are ninety percent values in the vector that are greater than 25. We can find percentiles of a vector values using quantile function in R. Live Demo > x1<-rpois(100,5) > x1 [1] 7 1 7 6 6 5 3 1 5 5 4 5 6 2 4 7 7 3 4 7 7 4 3 6 2 [26] 1 14 1 4 8 6 4 6 7 4 5 6 6 6 10 4 2 5 3 5 4 10 4 3 6 [51] 3 9 5 3 6 10 6 4 4 7 3 3 8 4 4 7 3 1 4 5 4 4 7 5 5 [76] 9 7 3 4 10 5 6 4 7 5 8 3 4 2 3 10 4 6 7 2 3 4 2 2 11 > quantile(x1,probs=seq(0,1,by=0.01)) 0% 1% 2% 3% 4% 5% 6% 7% 8% 9% 10% 11% 12% 1.00 1.00 1.00 1.00 1.00 1.95 2.00 2.00 2.00 2.00 2.00 2.00 2.88 13% 14% 15% 16% 17% 18% 19% 20% 21% 22% 23% 24% 25% 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 26% 27% 28% 29% 30% 31% 32% 33% 34% 35% 36% 37% 38% 3.74 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 39% 40% 41% 42% 43% 44% 45% 46% 47% 48% 49% 50% 51% 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.52 5.00 5.00 5.00 52% 53% 54% 55% 56% 57% 58% 59% 60% 61% 62% 63% 64% 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.39 6.00 6.00 6.00 65% 66% 67% 68% 69% 70% 71% 72% 73% 74% 75% 76% 77% 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.25 7.00 7.00 78% 79% 80% 81% 82% 83% 84% 85% 86% 87% 88% 89% 90% 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.12 8.00 8.00 91% 92% 93% 94% 95% 96% 97% 98% 99% 100% 8.09 9.00 9.07 10.00 10.00 10.00 10.00 10.02 11.03 14.00 > quantile(x1,probs=seq(0,1,by=0.02)) 0% 2% 4% 6% 8% 10% 12% 14% 16% 18% 20% 22% 24% 1.00 1.00 1.00 2.00 2.00 2.00 2.88 3.00 3.00 3.00 3.00 3.00 3.00 26% 28% 30% 32% 34% 36% 38% 40% 42% 44% 46% 48% 50% 3.74 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.52 5.00 52% 54% 56% 58% 60% 62% 64% 66% 68% 70% 72% 74% 76% 5.00 5.00 5.00 5.00 5.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 7.00 78% 80% 82% 84% 86% 88% 90% 92% 94% 96% 98% 100% 7.00 7.00 7.00 7.00 7.00 7.12 8.00 9.00 10.00 10.00 10.02 14.00 > quantile(x1,probs=seq(0,1,by=0.05)) 0% 5% 10% 15% 20% 25% 30% 35% 40% 45% 50% 55% 60% 1.00 1.95 2.00 3.00 3.00 3.00 4.00 4.00 4.00 4.00 5.00 5.00 5.00 65% 70% 75% 80% 85% 90% 95% 100% 6.00 6.00 6.25 7.00 7.00 8.00 10.00 14.00 > quantile(x1,probs=seq(0,1,by=0.10)) 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% 1 2 3 4 4 5 5 6 7 8 14 > quantile(x1,probs=seq(0,1,by=0.25)) 0% 25% 50% 75% 100% 1.00 3.00 5.00 6.25 14.00 Live Demo > x2<-sample(1:1000,100) > x2 [1] 315 259 494 865 760 289 48 331 100 108 301 10 170 280 348 402 209 468 [19] 827 649 309 395 991 8 626 261 541 306 326 74 282 585 267 887 262 736 [37] 204 723 219 696 352 667 119 452 856 924 579 622 936 646 36 55 490 240 [55] 891 632 862 304 989 665 422 612 105 793 388 463 180 278 373 241 24 679 [73] 559 703 37 686 566 303 719 912 19 712 671 378 549 615 244 994 188 464 [91] 393 139 299 371 670 189 311 905 418 569 > quantile(x2,probs=seq(0,1,by=0.01)) 0% 1% 2% 3% 4% 5% 6% 7% 8% 9% 10% 8.00 9.98 18.82 23.85 35.52 36.95 47.34 54.51 72.48 97.66 104.50 11% 12% 13% 14% 15% 16% 17% 18% 19% 20% 21% 107.67 117.68 136.40 165.66 178.50 186.72 188.83 201.30 208.05 217.00 235.59 22% 23% 24% 25% 26% 27% 28% 29% 30% 31% 32% 240.78 243.31 255.40 260.50 261.74 265.65 274.92 279.42 281.40 286.83 295.80 33% 34% 35% 36% 37% 38% 39% 40% 41% 42% 43% 300.34 302.32 303.65 305.28 307.89 310.24 313.44 321.60 328.95 340.86 350.28 44% 45% 46% 47% 48% 49% 50% 51% 52% 53% 54% 362.64 372.10 375.70 383.30 390.60 394.02 398.50 409.84 419.92 436.10 457.06 55% 56% 57% 58% 59% 60% 61% 62% 63% 64% 65% 463.45 465.76 477.46 491.68 513.27 544.20 552.90 561.66 567.11 572.60 581.10 66% 67% 68% 69% 70% 71% 72% 73% 74% 75% 76% 594.18 612.99 617.24 623.24 627.80 636.06 646.84 653.32 665.52 667.75 670.24 77% 78% 79% 80% 81% 82% 83% 84% 85% 86% 87% 672.84 680.54 688.10 697.40 704.71 713.26 719.68 725.08 739.60 764.62 797.42 88% 89% 90% 91% 92% 93% 94% 95% 96% 97% 98% 830.48 856.66 862.30 866.98 887.32 891.98 905.42 912.60 924.48 937.59 989.04 99% 100% 991.03 994.00 > quantile(x2,probs=seq(0,1,by=0.05)) 0% 5% 10% 15% 20% 25% 30% 35% 40% 45% 50% 8.00 36.95 104.50 178.50 217.00 260.50 281.40 303.65 321.60 372.10 398.50 55% 60% 65% 70% 75% 80% 85% 90% 95% 100% 463.45 544.20 581.10 627.80 667.75 697.40 739.60 862.30 912.60 994.00 > quantile(x2,probs=seq(0,1,by=0.25)) 0% 25% 50% 75% 100% 8.00 260.50 398.50 667.75 994.00
[ { "code": null, "e": 1520, "s": 1062, "text": "Percentile helps us to determine the values that lie at a certain percent in a data set. For example, if we have a vector of size 100 with containing any values and suppose that the tenth-percentile of the vector is 25, which means there are ten percent values in the vector that are less than 25, or we can say, there are ninety percent values in the vector that are greater than 25. We can find percentiles of a vector values using quantile function in R." }, { "code": null, "e": 1531, "s": 1520, "text": " Live Demo" }, { "code": null, "e": 1555, "s": 1531, "text": "> x1<-rpois(100,5)\n> x1" }, { "code": null, "e": 1781, "s": 1555, "text": "[1] 7 1 7 6 6 5 3 1 5 5 4 5 6 2 4 7 7 3 4 7 7 4 3 6 2\n[26] 1 14 1 4 8 6 4 6 7 4 5 6 6 6 10 4 2 5 3 5 4 10 4 3 6\n[51] 3 9 5 3 6 10 6 4 4 7 3 3 8 4 4 7 3 1 4 5 4 4 7 5 5\n[76] 9 7 3 4 10 5 6 4 7 5 8 3 4 2 3 10 4 6 7 2 3 4 2 2 11" }, { "code": null, "e": 1819, "s": 1781, "text": "> quantile(x1,probs=seq(0,1,by=0.01))" }, { "code": null, "e": 2726, "s": 1819, "text": "0% 1% 2% 3% 4% 5% 6% 7% 8% 9% 10% 11% 12%\n1.00 1.00 1.00 1.00 1.00 1.95 2.00 2.00 2.00 2.00 2.00 2.00 2.88\n13% 14% 15% 16% 17% 18% 19% 20% 21% 22% 23% 24% 25%\n3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00 3.00\n26% 27% 28% 29% 30% 31% 32% 33% 34% 35% 36% 37% 38%\n3.74 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00\n39% 40% 41% 42% 43% 44% 45% 46% 47% 48% 49% 50% 51%\n4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.52 5.00 5.00 5.00\n52% 53% 54% 55% 56% 57% 58% 59% 60% 61% 62% 63% 64%\n5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.00 5.39 6.00 6.00 6.00\n65% 66% 67% 68% 69% 70% 71% 72% 73% 74% 75% 76% 77%\n6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 6.25 7.00 7.00\n78% 79% 80% 81% 82% 83% 84% 85% 86% 87% 88% 89% 90%\n7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.00 7.12 8.00 8.00\n91% 92% 93% 94% 95% 96% 97% 98% 99% 100%\n8.09 9.00 9.07 10.00 10.00 10.00 10.00 10.02 11.03 14.00" }, { "code": null, "e": 2764, "s": 2726, "text": "> quantile(x1,probs=seq(0,1,by=0.02))" }, { "code": null, "e": 3223, "s": 2764, "text": "0% 2% 4% 6% 8% 10% 12% 14% 16% 18% 20% 22% 24%\n1.00 1.00 1.00 2.00 2.00 2.00 2.88 3.00 3.00 3.00 3.00 3.00 3.00\n26% 28% 30% 32% 34% 36% 38% 40% 42% 44% 46% 48% 50%\n3.74 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.00 4.52 5.00\n52% 54% 56% 58% 60% 62% 64% 66% 68% 70% 72% 74% 76%\n5.00 5.00 5.00 5.00 5.00 6.00 6.00 6.00 6.00 6.00 6.00 6.00 7.00\n78% 80% 82% 84% 86% 88% 90% 92% 94% 96% 98% 100%\n7.00 7.00 7.00 7.00 7.00 7.12 8.00 9.00 10.00 10.00 10.02 14.00" }, { "code": null, "e": 3261, "s": 3223, "text": "> quantile(x1,probs=seq(0,1,by=0.05))" }, { "code": null, "e": 3451, "s": 3261, "text": "0% 5% 10% 15% 20% 25% 30% 35% 40% 45% 50% 55% 60%\n1.00 1.95 2.00 3.00 3.00 3.00 4.00 4.00 4.00 4.00 5.00 5.00 5.00\n65% 70% 75% 80% 85% 90% 95% 100%\n6.00 6.00 6.25 7.00 7.00 8.00 10.00 14.00" }, { "code": null, "e": 3489, "s": 3451, "text": "> quantile(x1,probs=seq(0,1,by=0.10))" }, { "code": null, "e": 3556, "s": 3489, "text": "0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%\n1 2 3 4 4 5 5 6 7 8 14" }, { "code": null, "e": 3594, "s": 3556, "text": "> quantile(x1,probs=seq(0,1,by=0.25))" }, { "code": null, "e": 3640, "s": 3594, "text": "0% 25% 50% 75% 100%\n1.00 3.00 5.00 6.25 14.00" }, { "code": null, "e": 3651, "s": 3640, "text": " Live Demo" }, { "code": null, "e": 3681, "s": 3651, "text": "> x2<-sample(1:1000,100)\n> x2" }, { "code": null, "e": 4100, "s": 3681, "text": "[1] 315 259 494 865 760 289 48 331 100 108 301 10 170 280 348 402 209 468\n[19] 827 649 309 395 991 8 626 261 541 306 326 74 282 585 267 887 262 736\n[37] 204 723 219 696 352 667 119 452 856 924 579 622 936 646 36 55 490 240\n[55] 891 632 862 304 989 665 422 612 105 793 388 463 180 278 373 241 24 679\n[73] 559 703 37 686 566 303 719 912 19 712 671 378 549 615 244 994 188 464\n[91] 393 139 299 371 670 189 311 905 418 569" }, { "code": null, "e": 4138, "s": 4100, "text": "> quantile(x2,probs=seq(0,1,by=0.01))" }, { "code": null, "e": 5228, "s": 4138, "text": "0% 1% 2% 3% 4% 5% 6% 7% 8% 9% 10%\n8.00 9.98 18.82 23.85 35.52 36.95 47.34 54.51 72.48 97.66 104.50\n11% 12% 13% 14% 15% 16% 17% 18% 19% 20% 21%\n107.67 117.68 136.40 165.66 178.50 186.72 188.83 201.30 208.05 217.00 235.59\n22% 23% 24% 25% 26% 27% 28% 29% 30% 31% 32%\n240.78 243.31 255.40 260.50 261.74 265.65 274.92 279.42 281.40 286.83 295.80\n33% 34% 35% 36% 37% 38% 39% 40% 41% 42% 43%\n300.34 302.32 303.65 305.28 307.89 310.24 313.44 321.60 328.95 340.86 350.28\n44% 45% 46% 47% 48% 49% 50% 51% 52% 53% 54%\n362.64 372.10 375.70 383.30 390.60 394.02 398.50 409.84 419.92 436.10 457.06\n55% 56% 57% 58% 59% 60% 61% 62% 63% 64% 65%\n463.45 465.76 477.46 491.68 513.27 544.20 552.90 561.66 567.11 572.60 581.10\n66% 67% 68% 69% 70% 71% 72% 73% 74% 75% 76%\n594.18 612.99 617.24 623.24 627.80 636.06 646.84 653.32 665.52 667.75 670.24\n77% 78% 79% 80% 81% 82% 83% 84% 85% 86% 87%\n672.84 680.54 688.10 697.40 704.71 713.26 719.68 725.08 739.60 764.62 797.42\n88% 89% 90% 91% 92% 93% 94% 95% 96% 97% 98%\n830.48 856.66 862.30 866.98 887.32 891.98 905.42 912.60 924.48 937.59 989.04\n99% 100%\n991.03 994.00" }, { "code": null, "e": 5266, "s": 5228, "text": "> quantile(x2,probs=seq(0,1,by=0.05))" }, { "code": null, "e": 5493, "s": 5266, "text": "0% 5% 10% 15% 20% 25% 30% 35% 40% 45% 50%\n8.00 36.95 104.50 178.50 217.00 260.50 281.40 303.65 321.60 372.10 398.50\n55% 60% 65% 70% 75% 80% 85% 90% 95% 100%\n463.45 544.20 581.10 627.80 667.75 697.40 739.60 862.30 912.60 994.00" }, { "code": null, "e": 5531, "s": 5493, "text": "> quantile(x2,probs=seq(0,1,by=0.25))" }, { "code": null, "e": 5584, "s": 5531, "text": "0% 25% 50% 75% 100%\n8.00 260.50 398.50 667.75 994.00" } ]
C# Decimal ("D") Format Specifier
The "D" (or decimal) format specifier works for integer type. It converts a number to a string of decimal digits (0-9). Let’say the following is our number. int val = 467; Now to return the result as 0467, use the following decimal format specifier. val.ToString("D4") Let us see another example. Live Demo using System; using System.Globalization; class Demo { static void Main() { int val; val = 877; Console.WriteLine(val.ToString("D")); Console.WriteLine(val.ToString("D4")); Console.WriteLine(val.ToString("D8")); } } 877 0877 00000877
[ { "code": null, "e": 1182, "s": 1062, "text": "The \"D\" (or decimal) format specifier works for integer type. It converts a number to a string of decimal digits (0-9)." }, { "code": null, "e": 1219, "s": 1182, "text": "Let’say the following is our number." }, { "code": null, "e": 1234, "s": 1219, "text": "int val = 467;" }, { "code": null, "e": 1312, "s": 1234, "text": "Now to return the result as 0467, use the following decimal format specifier." }, { "code": null, "e": 1331, "s": 1312, "text": "val.ToString(\"D4\")" }, { "code": null, "e": 1359, "s": 1331, "text": "Let us see another example." }, { "code": null, "e": 1370, "s": 1359, "text": " Live Demo" }, { "code": null, "e": 1622, "s": 1370, "text": "using System;\nusing System.Globalization;\nclass Demo {\n static void Main() {\n int val;\n val = 877;\n Console.WriteLine(val.ToString(\"D\"));\n Console.WriteLine(val.ToString(\"D4\"));\n Console.WriteLine(val.ToString(\"D8\"));\n }\n}" }, { "code": null, "e": 1640, "s": 1622, "text": "877\n0877\n00000877" } ]
Python 3 - Number seed() Method
The seed() method initializes the basic random number generator. Call this function before calling any other random module function. Following is the syntax for seed() method: seed ([x], [y]) Note − This function initializes the basic random number generator. x − This is the seed for the next random number. If omitted, then it takes system time to generate the next random number. If x is an int, it is used directly. y − This is version number (default is 2). str, byte or byte array object gets converted in int. Version 1 used hash() of x. This method does not return any value. The following example shows the usage of seed() method. #!/usr/bin/python3 import random random.seed() print ("random number with default seed", random.random()) random.seed(10) print ("random number with int seed", random.random()) random.seed("hello",2) print ("random number with string seed", random.random()) When we run above program, it produces the following result − random number with default seed 0.2524977842762465 random number with int seed 0.5714025946899135 random number with string seed 0.3537754404730722 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": 2473, "s": 2340, "text": "The seed() method initializes the basic random number generator. Call this function before calling any other random module function." }, { "code": null, "e": 2516, "s": 2473, "text": "Following is the syntax for seed() method:" }, { "code": null, "e": 2533, "s": 2516, "text": "seed ([x], [y])\n" }, { "code": null, "e": 2601, "s": 2533, "text": "Note − This function initializes the basic random number generator." }, { "code": null, "e": 2761, "s": 2601, "text": "x − This is the seed for the next random number. If omitted, then it takes system time to generate the next random number. If x is an int, it is used directly." }, { "code": null, "e": 2886, "s": 2761, "text": "y − This is version number (default is 2). str, byte or byte array object gets converted in int. Version 1 used hash() of x." }, { "code": null, "e": 2925, "s": 2886, "text": "This method does not return any value." }, { "code": null, "e": 2981, "s": 2925, "text": "The following example shows the usage of seed() method." }, { "code": null, "e": 3242, "s": 2981, "text": "#!/usr/bin/python3\nimport random\n\nrandom.seed()\nprint (\"random number with default seed\", random.random())\n\nrandom.seed(10)\nprint (\"random number with int seed\", random.random())\n\nrandom.seed(\"hello\",2)\nprint (\"random number with string seed\", random.random())" }, { "code": null, "e": 3304, "s": 3242, "text": "When we run above program, it produces the following result −" }, { "code": null, "e": 3453, "s": 3304, "text": "random number with default seed 0.2524977842762465\nrandom number with int seed 0.5714025946899135\nrandom number with string seed 0.3537754404730722\n" }, { "code": null, "e": 3490, "s": 3453, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3506, "s": 3490, "text": " Malhar Lathkar" }, { "code": null, "e": 3539, "s": 3506, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3558, "s": 3539, "text": " Arnab Chakraborty" }, { "code": null, "e": 3593, "s": 3558, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3615, "s": 3593, "text": " In28Minutes Official" }, { "code": null, "e": 3649, "s": 3615, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3677, "s": 3649, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3712, "s": 3677, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3726, "s": 3712, "text": " Lets Kode It" }, { "code": null, "e": 3759, "s": 3726, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3776, "s": 3759, "text": " Abhilash Nelson" }, { "code": null, "e": 3783, "s": 3776, "text": " Print" }, { "code": null, "e": 3794, "s": 3783, "text": " Add Notes" } ]
SAP HANA - SQL Stored Procedures
A procedure allows you to group the SQL statement into a single block. Stored Procedures are used to achieve certain result across applications. The set of SQL statements and the logic that is used to perform some specific task are stored in SQL Stored Procedures. These stored procedures are executed by applications to perform that task. Stored Procedures can return data in the form of output parameters (integer or character) or a cursor variable. It can also result in set of Select statements, which are used by other Stored Procedures. Stored Procedures are also used for performance optimization as it contains series of SQL statements and results from one set of statement determines next set of statements to be executed. Stored procedures prevent users to see the complexity and details of tables in a database. As Stored procedures contain certain business logic, so users need to execute or call the procedure name. No need to keep reissuing the individual statements but can refer to the database procedure. Create procedure prc_name (in inp integer, out opt "EFASION"."ARTICLE_LOOKUP") as begin opt = select * from "EFASION"."ARTICLE_LOOKUP" where article_id = :inp ; end; 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 3447, "s": 3107, "text": "A procedure allows you to group the SQL statement into a single block. Stored Procedures are used to achieve certain result across applications. The set of SQL statements and the logic that is used to perform some specific task are stored in SQL Stored Procedures. These stored procedures are executed by applications to perform that task." }, { "code": null, "e": 3650, "s": 3447, "text": "Stored Procedures can return data in the form of output parameters (integer or character) or a cursor variable. It can also result in set of Select statements, which are used by other Stored Procedures." }, { "code": null, "e": 4036, "s": 3650, "text": "Stored Procedures are also used for performance optimization as it contains series of SQL statements and results from one set of statement determines next set of statements to be executed. Stored procedures prevent users to see the complexity and details of tables in a database. As Stored procedures contain certain business logic, so users need to execute or call the procedure name." }, { "code": null, "e": 4129, "s": 4036, "text": "No need to keep reissuing the individual statements but can refer to the database procedure." }, { "code": null, "e": 4295, "s": 4129, "text": "Create procedure prc_name (in inp integer, out opt \"EFASION\".\"ARTICLE_LOOKUP\")\nas\nbegin\nopt = select * from \"EFASION\".\"ARTICLE_LOOKUP\" where article_id = :inp ;\nend;" }, { "code": null, "e": 4328, "s": 4295, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 4342, "s": 4328, "text": " Sanjo Thomas" }, { "code": null, "e": 4375, "s": 4342, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 4387, "s": 4375, "text": " Neha Gupta" }, { "code": null, "e": 4422, "s": 4387, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4437, "s": 4422, "text": " Sumit Agarwal" }, { "code": null, "e": 4470, "s": 4437, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 4485, "s": 4470, "text": " Sumit Agarwal" }, { "code": null, "e": 4520, "s": 4485, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4532, "s": 4520, "text": " Neha Malik" }, { "code": null, "e": 4567, "s": 4532, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4579, "s": 4567, "text": " Neha Malik" }, { "code": null, "e": 4586, "s": 4579, "text": " Print" }, { "code": null, "e": 4597, "s": 4586, "text": " Add Notes" } ]
How do I begin auto increment from a specific point in MySQL?
To begin auto increment from a specific point, use ALTER command. The syntax is as follows − ALTER TABLE yourTableName auto_increment = anySpecificPoint; To understand the above concept, let us create a table. The query to create a table is as follows − mysql> create table AutoIncrementSpecificPoint −> ( −> BookId int auto_increment not null, −> Primary key(BookId) −> ); Query OK, 0 rows affected (0.56 sec) Now you can insert records using insert command. The query is as follows − mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.17 sec) mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.17 sec) mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.09 sec) mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.10 sec) The above insert command begins the value from 1 and adds 1 to the next value. Now you can check all records from table using select statement. The query is as follows − mysql> select *from AutoIncrementSpecificPoint; The following is the output − +--------+ | BookId | +--------+ | 1 | | 2 | | 3 | | 4 | +--------+ 4 rows in set (0.00 sec) Look at the above sample output, the auto_increment starts from 1. Now to change the auto_increment to begin from a specific point, you can use ALTER command. The query is as follows − mysql> alter table AutoIncrementSpecificPoint auto_increment = 100; Query OK, 0 rows affected (0.25 sec) Records: 0 Duplicates: 0 Warnings: 0 In the above query I have set the auto increment to 100. Let us now insert records once again in the table using insert command. The query is as follows − mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.25 sec) mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.18 sec) mysql> insert into AutoIncrementSpecificPoint values(); Query OK, 1 row affected (0.14 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from AutoIncrementSpecificPoint; The following is the output displaying the other values set for auto increment i.e. beginning from 100 − +--------+ | BookId | +--------+ | 1 | | 2 | | 3 | | 4 | | 100 | | 101 | | 102 | +--------+ 7 rows in set (0.00 sec)
[ { "code": null, "e": 1155, "s": 1062, "text": "To begin auto increment from a specific point, use ALTER command. The syntax is as follows −" }, { "code": null, "e": 1216, "s": 1155, "text": "ALTER TABLE yourTableName auto_increment = anySpecificPoint;" }, { "code": null, "e": 1316, "s": 1216, "text": "To understand the above concept, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1485, "s": 1316, "text": "mysql> create table AutoIncrementSpecificPoint\n −> (\n −> BookId int auto_increment not null,\n −> Primary key(BookId)\n −> );\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1534, "s": 1485, "text": "Now you can insert records using insert command." }, { "code": null, "e": 1560, "s": 1534, "text": "The query is as follows −" }, { "code": null, "e": 1931, "s": 1560, "text": "mysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.10 sec)" }, { "code": null, "e": 2075, "s": 1931, "text": "The above insert command begins the value from 1 and adds 1 to the next value. Now you can check all records from table using select statement." }, { "code": null, "e": 2101, "s": 2075, "text": "The query is as follows −" }, { "code": null, "e": 2149, "s": 2101, "text": "mysql> select *from AutoIncrementSpecificPoint;" }, { "code": null, "e": 2179, "s": 2149, "text": "The following is the output −" }, { "code": null, "e": 2292, "s": 2179, "text": "+--------+\n| BookId |\n+--------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+--------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2359, "s": 2292, "text": "Look at the above sample output, the auto_increment starts from 1." }, { "code": null, "e": 2477, "s": 2359, "text": "Now to change the auto_increment to begin from a specific point, you can use ALTER command. The query is as follows −" }, { "code": null, "e": 2619, "s": 2477, "text": "mysql> alter table AutoIncrementSpecificPoint auto_increment = 100;\nQuery OK, 0 rows affected (0.25 sec)\nRecords: 0 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2774, "s": 2619, "text": "In the above query I have set the auto increment to 100. Let us now insert records once again in the table using insert command. The query is as follows −" }, { "code": null, "e": 3052, "s": 2774, "text": "mysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into AutoIncrementSpecificPoint values();\nQuery OK, 1 row affected (0.14 sec)" }, { "code": null, "e": 3137, "s": 3052, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 3185, "s": 3137, "text": "mysql> select *from AutoIncrementSpecificPoint;" }, { "code": null, "e": 3290, "s": 3185, "text": "The following is the output displaying the other values set for auto increment i.e. beginning from 100 −" }, { "code": null, "e": 3436, "s": 3290, "text": "+--------+\n| BookId |\n+--------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 100 |\n| 101 |\n| 102 |\n+--------+\n7 rows in set (0.00 sec)" } ]
How can I dynamically update my Matplotlib figure as the data file changes?
To update a Matplotlib figure as the data file changes, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Initialize variables m and n, to get a set of subplots. Create a list of colors, to plot color dynamically. Plot dynamic data points using plot() method with random data points. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt import random plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True m = 2 n = 4 fix, axes = plt.subplots(nrows=m, ncols=n) hexadecimal_alphabets = '0123456789ABCDEF' color = ["#" + ''.join([random.choice(hexadecimal_alphabets) for j in range(6)]) for i in range(m*n)] for i in range(m): for j in range(n): axes[i][j].clear() axes[i][j].plot(np.random.rand(10), np.random.rand(10), color=color[100 % np.random.randint(1, len(color))]) plt.pause(0.1) plt.show()
[ { "code": null, "e": 1152, "s": 1062, "text": "To update a Matplotlib figure as the data file changes, we can take the following steps −" }, { "code": null, "e": 1228, "s": 1152, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1284, "s": 1228, "text": "Initialize variables m and n, to get a set of subplots." }, { "code": null, "e": 1336, "s": 1284, "text": "Create a list of colors, to plot color dynamically." }, { "code": null, "e": 1406, "s": 1336, "text": "Plot dynamic data points using plot() method with random data points." }, { "code": null, "e": 1448, "s": 1406, "text": "To display the figure, use show() method." }, { "code": null, "e": 2064, "s": 1448, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nimport random\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nm = 2\nn = 4\n\nfix, axes = plt.subplots(nrows=m, ncols=n)\nhexadecimal_alphabets = '0123456789ABCDEF'\n\ncolor = [\"#\" + ''.join([random.choice(hexadecimal_alphabets)\n for j in range(6)]) for i in range(m*n)]\n\nfor i in range(m):\n for j in range(n):\n axes[i][j].clear()\n axes[i][j].plot(np.random.rand(10), np.random.rand(10),\n color=color[100 % np.random.randint(1, len(color))])\n plt.pause(0.1)\n\nplt.show()" } ]
Combinations with repetitions - GeeksforGeeks
23 Jan, 2022 Suppose we have a string of length- n and we want to generate all combinations/permutations taken r at a time with/without repetitions. There are four fundamental concepts in Combinatorics1) Combinations without repetitions/replacements. 2) Combinations with repetitions/replacements. 3) Permutations without repetitions/replacements. 4) Permutations with repetitions/replacements.Below is a summary table depicting the fundamental concepts in Combinatorics Theory. Summary Table This article is about the third case(Order Not important and Repetitions allowed).The idea is to recur for all the possibilities of the string, even if the characters are repeating.The base case of the recursion is when there is a total of ‘r’ characters and the combination is ready to be printed. For clarity, see the recursion tree for the string- “ 1 2 3 4” and r=2 Below is the implementation. C++ C Java Python3 C# Javascript // C++ program to print all combination of size r in an array// of size n with repetitions allowed#include <bits/stdc++.h>using namespace std; /* arr[] ---> Input Array chosen[] ---> Temporary array to store indices of current combination start & end ---> Starting and Ending indexes in arr[] r ---> Size of a combination to be printed */void CombinationRepetitionUtil(int chosen[], int arr[], int index, int r, int start, int end){ // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) cout<<" "<< arr[chosen[i]]; cout<<"\n"; return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return;} // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()void CombinationRepetition(int arr[], int n, int r){ // Allocate memory int chosen[r+1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); int r = 2; CombinationRepetition(arr, n, r); return 0;}// this code is contributed by shivanisinghss2110 // C program to print all combination of size r in an array// of size n with repetitions allowed#include <stdio.h> /* arr[] ---> Input Array chosen[] ---> Temporary array to store indices of current combination start & end ---> Starting and Ending indexes in arr[] r ---> Size of a combination to be printed */void CombinationRepetitionUtil(int chosen[], int arr[], int index, int r, int start, int end){ // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) printf("%d ", arr[chosen[i]]); printf("\n"); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return;} // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()void CombinationRepetition(int arr[], int n, int r){ // Allocate memory int chosen[r+1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); int r = 2; CombinationRepetition(arr, n, r); return 0;} // Java program to print all combination of size r in an array// of size n with repetitions allowed class GFG { /* arr[] ---> Input Arraychosen[] ---> Temporary array to store indices of current combinationstart & end ---> Starting and Ending indexes in arr[]r ---> Size of a combination to be printed */ static void CombinationRepetitionUtil(int chosen[], int arr[], int index, int r, int start, int end) { // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) { System.out.printf("%d ", arr[chosen[i]]); } System.out.printf("\n"); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return; } // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil() static void CombinationRepetition(int arr[], int n, int r) { // Allocate memory int chosen[] = new int[r + 1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1); } // Driver program to test above functions public static void main(String[] args) { int arr[] = {1, 2, 3, 4}; int n = arr.length; int r = 2; CombinationRepetition(arr, n, r); }} /* This Java code is contributed by PrinciRaj1992*/ # Python3 program to print all combination# of size r in an array of size n ''' arr[] ---> Input Array chosen[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] r---> Size of a combination to be printed '''def CombinationRepetitionUtil(chosen, arr, index, r, start, end): # Current combination is ready, # print it if index == r: for j in range(r): print(chosen[j], end = " ") print() return # When no more elements are # there to put in chosen[] if start > n: return # Current is included, put # next at next location chosen[index] = arr[start] # Current is excluded, replace it # with next (Note that i+1 is passed, # but index is not changed) CombinationRepetitionUtil(chosen, arr, index + 1, r, start, end) CombinationRepetitionUtil(chosen, arr, index, r, start + 1, end) # The main function that prints all# combinations of size r in arr[] of# size n. This function mainly uses# CombinationRepetitionUtil()def CombinationRepetition(arr, n, r): # A temporary array to store # all combination one by one chosen = [0] * r # Print all combination using # temporary array 'chosen[]' CombinationRepetitionUtil(chosen, arr, 0, r, 0, n) # Driver codearr = [ 1, 2, 3, 4 ]r = 2n = len(arr) - 1 CombinationRepetition(arr, n, r) # This code is contributed by Vaibhav Kumar 12. // C# program to print all combination of size r in an array// of size n with repetitions allowed using System;public class GFG{ /* arr[] ---> Input Arraychosen[] ---> Temporary array to store indices of current combinationstart & end ---> Starting and Ending indexes in arr[]r ---> Size of a combination to be printed */ static void CombinationRepetitionUtil(int []chosen, int []arr, int index, int r, int start, int end) { // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) { Console.Write(arr[chosen[i]]+" "); } Console.WriteLine(); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return; } // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil() static void CombinationRepetition(int []arr, int n, int r) { // Allocate memory int []chosen = new int[r + 1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1); } // Driver program to test above functions public static void Main() { int []arr = {1, 2, 3, 4}; int n = arr.Length; int r = 2; CombinationRepetition(arr, n, r); }} // This code is contributed by PrinciRaj1992 <script>// javascript program to print all combination of size r in an array// of size n with repetitions allowed /* arr ---> Input Arraychosen ---> Temporary array to store indices of current combinationstart & end ---> Starting and Ending indexes in arrr ---> Size of a combination to be printed */ function CombinationRepetitionUtil(chosen , arr, index , r , start , end) { // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (var i = 0; i < r; i++) { document.write(arr[chosen[i]]+" "); } document.write("<br>"); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (var i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return; } // The main function that prints all combinations of size r// in arr of size n with repetitions. This function mainly// uses CombinationRepetitionUtil() function CombinationRepetition(arr , n , r) { // Allocate memory var chosen = Array.from({length: (r + 1)}, (_, i) => 0); // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1); } // Driver program to test above functionsvar arr = [1, 2, 3, 4];var n = arr.length;var r = 2;CombinationRepetition(arr, n, r); // This code is contributed by shikhasingrajput</script> Output : 1 1 1 2 1 3 1 4 2 2 2 3 2 4 3 3 3 4 4 4 Time Complexity: For a string of length- n and combinations taken r at a time with repetitions, it takes a total of O(n+r-1Cr) time.References– https://en.wikipedia.org/wiki/CombinationThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above princiraj1992 Vaibhav Kumar 12 simmytarika5 shivanisinghss2110 khushboogoyal499 surindertarika1234 shikhasingrajput simranarora5sos Combinatorial Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Largest number by rearranging digits of a given positive or negative number Ways to sum to N using Natural Numbers up to K with repetitions allowed Given number of matches played, find number of teams in tournament Generate all possible combinations of at most X characters from a given array Number of Simple Graph with N Vertices and M Edges Largest substring with same Characters Minimum cost to convert 1 to N by multiplying X or right rotation of digits Print all Strong numbers less than or equal to N Print all permutations with repetition of characters Combinations from n arrays picking one element from each array
[ { "code": null, "e": 25398, "s": 25370, "text": "\n23 Jan, 2022" }, { "code": null, "e": 25867, "s": 25398, "text": "Suppose we have a string of length- n and we want to generate all combinations/permutations taken r at a time with/without repetitions. There are four fundamental concepts in Combinatorics1) Combinations without repetitions/replacements. 2) Combinations with repetitions/replacements. 3) Permutations without repetitions/replacements. 4) Permutations with repetitions/replacements.Below is a summary table depicting the fundamental concepts in Combinatorics Theory. " }, { "code": null, "e": 25881, "s": 25867, "text": "Summary Table" }, { "code": null, "e": 26252, "s": 25881, "text": "This article is about the third case(Order Not important and Repetitions allowed).The idea is to recur for all the possibilities of the string, even if the characters are repeating.The base case of the recursion is when there is a total of ‘r’ characters and the combination is ready to be printed. For clarity, see the recursion tree for the string- “ 1 2 3 4” and r=2 " }, { "code": null, "e": 26282, "s": 26252, "text": "Below is the implementation. " }, { "code": null, "e": 26286, "s": 26282, "text": "C++" }, { "code": null, "e": 26288, "s": 26286, "text": "C" }, { "code": null, "e": 26293, "s": 26288, "text": "Java" }, { "code": null, "e": 26301, "s": 26293, "text": "Python3" }, { "code": null, "e": 26304, "s": 26301, "text": "C#" }, { "code": null, "e": 26315, "s": 26304, "text": "Javascript" }, { "code": "// C++ program to print all combination of size r in an array// of size n with repetitions allowed#include <bits/stdc++.h>using namespace std; /* arr[] ---> Input Array chosen[] ---> Temporary array to store indices of current combination start & end ---> Starting and Ending indexes in arr[] r ---> Size of a combination to be printed */void CombinationRepetitionUtil(int chosen[], int arr[], int index, int r, int start, int end){ // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) cout<<\" \"<< arr[chosen[i]]; cout<<\"\\n\"; return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return;} // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()void CombinationRepetition(int arr[], int n, int r){ // Allocate memory int chosen[r+1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); int r = 2; CombinationRepetition(arr, n, r); return 0;}// this code is contributed by shivanisinghss2110", "e": 27926, "s": 26315, "text": null }, { "code": "// C program to print all combination of size r in an array// of size n with repetitions allowed#include <stdio.h> /* arr[] ---> Input Array chosen[] ---> Temporary array to store indices of current combination start & end ---> Starting and Ending indexes in arr[] r ---> Size of a combination to be printed */void CombinationRepetitionUtil(int chosen[], int arr[], int index, int r, int start, int end){ // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) printf(\"%d \", arr[chosen[i]]); printf(\"\\n\"); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return;} // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil()void CombinationRepetition(int arr[], int n, int r){ // Allocate memory int chosen[r+1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n-1);} // Driver program to test above functionsint main(){ int arr[] = {1, 2, 3, 4}; int n = sizeof(arr)/sizeof(arr[0]); int r = 2; CombinationRepetition(arr, n, r); return 0;}", "e": 29465, "s": 27926, "text": null }, { "code": "// Java program to print all combination of size r in an array// of size n with repetitions allowed class GFG { /* arr[] ---> Input Arraychosen[] ---> Temporary array to store indices of current combinationstart & end ---> Starting and Ending indexes in arr[]r ---> Size of a combination to be printed */ static void CombinationRepetitionUtil(int chosen[], int arr[], int index, int r, int start, int end) { // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) { System.out.printf(\"%d \", arr[chosen[i]]); } System.out.printf(\"\\n\"); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return; } // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil() static void CombinationRepetition(int arr[], int n, int r) { // Allocate memory int chosen[] = new int[r + 1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1); } // Driver program to test above functions public static void main(String[] args) { int arr[] = {1, 2, 3, 4}; int n = arr.length; int r = 2; CombinationRepetition(arr, n, r); }} /* This Java code is contributed by PrinciRaj1992*/", "e": 31194, "s": 29465, "text": null }, { "code": "# Python3 program to print all combination# of size r in an array of size n ''' arr[] ---> Input Array chosen[] ---> Temporary array to store current combination start & end ---> Starting and Ending indexes in arr[] r---> Size of a combination to be printed '''def CombinationRepetitionUtil(chosen, arr, index, r, start, end): # Current combination is ready, # print it if index == r: for j in range(r): print(chosen[j], end = \" \") print() return # When no more elements are # there to put in chosen[] if start > n: return # Current is included, put # next at next location chosen[index] = arr[start] # Current is excluded, replace it # with next (Note that i+1 is passed, # but index is not changed) CombinationRepetitionUtil(chosen, arr, index + 1, r, start, end) CombinationRepetitionUtil(chosen, arr, index, r, start + 1, end) # The main function that prints all# combinations of size r in arr[] of# size n. This function mainly uses# CombinationRepetitionUtil()def CombinationRepetition(arr, n, r): # A temporary array to store # all combination one by one chosen = [0] * r # Print all combination using # temporary array 'chosen[]' CombinationRepetitionUtil(chosen, arr, 0, r, 0, n) # Driver codearr = [ 1, 2, 3, 4 ]r = 2n = len(arr) - 1 CombinationRepetition(arr, n, r) # This code is contributed by Vaibhav Kumar 12.", "e": 32809, "s": 31194, "text": null }, { "code": "// C# program to print all combination of size r in an array// of size n with repetitions allowed using System;public class GFG{ /* arr[] ---> Input Arraychosen[] ---> Temporary array to store indices of current combinationstart & end ---> Starting and Ending indexes in arr[]r ---> Size of a combination to be printed */ static void CombinationRepetitionUtil(int []chosen, int []arr, int index, int r, int start, int end) { // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (int i = 0; i < r; i++) { Console.Write(arr[chosen[i]]+\" \"); } Console.WriteLine(); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (int i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return; } // The main function that prints all combinations of size r// in arr[] of size n with repetitions. This function mainly// uses CombinationRepetitionUtil() static void CombinationRepetition(int []arr, int n, int r) { // Allocate memory int []chosen = new int[r + 1]; // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1); } // Driver program to test above functions public static void Main() { int []arr = {1, 2, 3, 4}; int n = arr.Length; int r = 2; CombinationRepetition(arr, n, r); }} // This code is contributed by PrinciRaj1992", "e": 34525, "s": 32809, "text": null }, { "code": "<script>// javascript program to print all combination of size r in an array// of size n with repetitions allowed /* arr ---> Input Arraychosen ---> Temporary array to store indices of current combinationstart & end ---> Starting and Ending indexes in arrr ---> Size of a combination to be printed */ function CombinationRepetitionUtil(chosen , arr, index , r , start , end) { // Since index has become r, current combination is // ready to be printed, print if (index == r) { for (var i = 0; i < r; i++) { document.write(arr[chosen[i]]+\" \"); } document.write(\"<br>\"); return; } // One by one choose all elements (without considering // the fact whether element is already chosen or not) // and recur for (var i = start; i <= end; i++) { chosen[index] = i; CombinationRepetitionUtil(chosen, arr, index + 1, r, i, end); } return; } // The main function that prints all combinations of size r// in arr of size n with repetitions. This function mainly// uses CombinationRepetitionUtil() function CombinationRepetition(arr , n , r) { // Allocate memory var chosen = Array.from({length: (r + 1)}, (_, i) => 0); // Call the recursive function CombinationRepetitionUtil(chosen, arr, 0, r, 0, n - 1); } // Driver program to test above functionsvar arr = [1, 2, 3, 4];var n = arr.length;var r = 2;CombinationRepetition(arr, n, r); // This code is contributed by shikhasingrajput</script>", "e": 36160, "s": 34525, "text": null }, { "code": null, "e": 36170, "s": 36160, "text": "Output : " }, { "code": null, "e": 36219, "s": 36170, "text": "1 1 \n1 2 \n1 3 \n1 4 \n2 2 \n2 3 \n2 4 \n3 3 \n3 4 \n4 4" }, { "code": null, "e": 36800, "s": 36219, "text": "Time Complexity: For a string of length- n and combinations taken r at a time with repetitions, it takes a total of O(n+r-1Cr) time.References– https://en.wikipedia.org/wiki/CombinationThis article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 36814, "s": 36800, "text": "princiraj1992" }, { "code": null, "e": 36831, "s": 36814, "text": "Vaibhav Kumar 12" }, { "code": null, "e": 36844, "s": 36831, "text": "simmytarika5" }, { "code": null, "e": 36863, "s": 36844, "text": "shivanisinghss2110" }, { "code": null, "e": 36880, "s": 36863, "text": "khushboogoyal499" }, { "code": null, "e": 36899, "s": 36880, "text": "surindertarika1234" }, { "code": null, "e": 36916, "s": 36899, "text": "shikhasingrajput" }, { "code": null, "e": 36932, "s": 36916, "text": "simranarora5sos" }, { "code": null, "e": 36946, "s": 36932, "text": "Combinatorial" }, { "code": null, "e": 36960, "s": 36946, "text": "Combinatorial" }, { "code": null, "e": 37058, "s": 36960, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37067, "s": 37058, "text": "Comments" }, { "code": null, "e": 37080, "s": 37067, "text": "Old Comments" }, { "code": null, "e": 37156, "s": 37080, "text": "Largest number by rearranging digits of a given positive or negative number" }, { "code": null, "e": 37228, "s": 37156, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 37295, "s": 37228, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 37373, "s": 37295, "text": "Generate all possible combinations of at most X characters from a given array" }, { "code": null, "e": 37424, "s": 37373, "text": "Number of Simple Graph with N Vertices and M Edges" }, { "code": null, "e": 37463, "s": 37424, "text": "Largest substring with same Characters" }, { "code": null, "e": 37539, "s": 37463, "text": "Minimum cost to convert 1 to N by multiplying X or right rotation of digits" }, { "code": null, "e": 37588, "s": 37539, "text": "Print all Strong numbers less than or equal to N" }, { "code": null, "e": 37641, "s": 37588, "text": "Print all permutations with repetition of characters" } ]
How to Add Text in the GroupBox in C#? - GeeksforGeeks
02 Aug, 2019 In Windows Forms, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can add text in the GroupBox in the form using Text Property. You can set this property in two different ways: 1. Design-Time: It is the easiest way to add text in the GroupBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the GroupBox control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the GroupBox and add text in the GroupBox as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can add text in the GroupBox control programmatically with the help of given syntax: public override string Text { get; set; } The following steps show how to add text in the GroupBox dynamically: Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox GroupBox gbox = new GroupBox(); // Creating a GroupBox GroupBox gbox = new GroupBox(); Step 2: After creating GroupBox, set the Text property of the GroupBox provided by the GroupBox class.// Adding text gbox.Text = "Select Gender"; // Adding text gbox.Text = "Select Gender"; Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control to the GroupBox gbox.Controls.Add(c2); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; gbox.Font = new Font("Colonna MT", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output: // Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control to the GroupBox gbox.Controls.Add(c2); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; gbox.Font = new Font("Colonna MT", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# Dictionary with examples C# | Delegates C# | Method Overriding C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | String.IndexOf( ) Method | Set - 1 C# | Constructors
[ { "code": null, "e": 25449, "s": 25421, "text": "\n02 Aug, 2019" }, { "code": null, "e": 25877, "s": 25449, "text": "In Windows Forms, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can add text in the GroupBox in the form using Text Property. You can set this property in two different ways:" }, { "code": null, "e": 25976, "s": 25877, "text": "1. Design-Time: It is the easiest way to add text in the GroupBox as shown in the following steps:" }, { "code": null, "e": 26092, "s": 25976, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 26199, "s": 26092, "text": "Step 2: Next, drag and drop the GroupBox control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 26338, "s": 26199, "text": "Step 3: After drag and drop you will go to the properties of the GroupBox and add text in the GroupBox as shown in the below image:Output:" }, { "code": null, "e": 26346, "s": 26338, "text": "Output:" }, { "code": null, "e": 26515, "s": 26346, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can add text in the GroupBox control programmatically with the help of given syntax:" }, { "code": null, "e": 26557, "s": 26515, "text": "public override string Text { get; set; }" }, { "code": null, "e": 26627, "s": 26557, "text": "The following steps show how to add text in the GroupBox dynamically:" }, { "code": null, "e": 26777, "s": 26627, "text": "Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n" }, { "code": null, "e": 26834, "s": 26777, "text": "// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n" }, { "code": null, "e": 26981, "s": 26834, "text": "Step 2: After creating GroupBox, set the Text property of the GroupBox provided by the GroupBox class.// Adding text\ngbox.Text = \"Select Gender\";\n" }, { "code": null, "e": 27026, "s": 26981, "text": "// Adding text\ngbox.Text = \"Select Gender\";\n" }, { "code": null, "e": 28741, "s": 27026, "text": "Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control to the GroupBox\ngbox.Controls.Add(c2);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; gbox.Font = new Font(\"Colonna MT\", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output:" }, { "code": null, "e": 28867, "s": 28741, "text": "// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control to the GroupBox\ngbox.Controls.Add(c2);\n" }, { "code": null, "e": 28876, "s": 28867, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting properties // of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; gbox.Font = new Font(\"Colonna MT\", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}", "e": 30321, "s": 28876, "text": null }, { "code": null, "e": 30329, "s": 30321, "text": "Output:" }, { "code": null, "e": 30360, "s": 30329, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 30363, "s": 30360, "text": "C#" }, { "code": null, "e": 30461, "s": 30363, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30489, "s": 30461, "text": "C# Dictionary with examples" }, { "code": null, "e": 30504, "s": 30489, "text": "C# | Delegates" }, { "code": null, "e": 30527, "s": 30504, "text": "C# | Method Overriding" }, { "code": null, "e": 30549, "s": 30527, "text": "C# | Abstract Classes" }, { "code": null, "e": 30595, "s": 30549, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30618, "s": 30595, "text": "Extension Method in C#" }, { "code": null, "e": 30640, "s": 30618, "text": "C# | Class and Object" }, { "code": null, "e": 30662, "s": 30640, "text": "C# | Replace() Method" }, { "code": null, "e": 30702, "s": 30662, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
How to dynamically allocate a 3D array in C++ - GeeksforGeeks
24 Mar, 2021 Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays: Syntax of a Multidimensional Array: data_type array_name[size1][size2]....[sizeN]; data_type: Type of data to be stored in the array. Here data_type is valid C/C++ data typearray_name: Name of the arraysize1, size2, ..., sizeN: Sizes of the dimensions 3-D arrays are an array of Double dimensional arrays: Syntax of a 3D array: data_type array_name[x][y][z];data_type: Type of data to be stored. Valid C/C++ data type. For more details on multidimensional and, 3D arrays, please refer to the Multidimensional Arrays in C++ article. Problem: Given a 3D array, the task is to dynamically allocate memory for a 3D array using new in C++. Solution: In the following methods, the approach used is to make two 2-D arrays and each 2-D array is having 3 rows and 4 columns with the following values. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 X = No of 2D arrays.Y = No of rows of each 2D array.Z = No of columns of each 2D array. Method 1: using single pointer – In this method, a memory block of size x*y*z is allocated and then the memory blocks are accessed using pointer arithmetic. Below is the program for the same: C++ // C++ program to dynamically allocate// the memory for 3D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the 3D array int x = 2, y = 3, z = 4; int count = 0; // Allocate memory blocks // of size x*y*z int* a = new int[x * y * z]; // Traverse the 3D array for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Assign values to the // memory blocks created *(a + i * y * z + j * z + k) = ++count; } } } // Traverse the 3D array again for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Print values of the // memory blocks created cout << *(a + i * y * z + j * z + k) << " "; } cout << endl; } cout << endl; } // Deallocate memory delete[] a; return 0;} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 Method 2: using triple pointer – Below is the diagram to illustrate the concept: Below is the program for the same: C++ // C++ program to dynamically allocate// the memory for 3D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the 3D array int x = 2, y = 3, z = 4; int count = 0; // Allocate memory blocks of size // x i.e., no of 2D Arrays int*** a = new int**[x]; for (int i = 0; i < x; i++) { // Allocate memory blocks for // rows of each 2D array a[i] = new int*[y]; for (int j = 0; j < y; j++) { // Allocate memory blocks for // columns of each 2D array a[i][j] = new int[z]; } } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Assign values to the // memory blocks created a[i][j][k] = ++count; } } } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Print values of the // memory blocks created cout << a[i][j][k] << " "; } cout << endl; } cout << endl; } // Deallocate memory for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { delete[] a[i][j]; } delete[] a[i]; } delete[] a; return 0;} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ANIKET1996 cpp-pointer Pointers Technical Scripter 2020 Arrays C++ Data Structures Technical Scripter Data Structures Arrays Pointers CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) std::sort() in C++ STL
[ { "code": null, "e": 26067, "s": 26039, "text": "\n24 Mar, 2021" }, { "code": null, "e": 26308, "s": 26067, "text": "Prerequisite: Array BasicsIn C/C++, multidimensional arrays in simple words as an array of arrays. Data in multidimensional arrays are stored in tabular form (in row major order). Below is the general form of declaring N-dimensional arrays:" }, { "code": null, "e": 26344, "s": 26308, "text": "Syntax of a Multidimensional Array:" }, { "code": null, "e": 26392, "s": 26344, "text": "data_type array_name[size1][size2]....[sizeN];" }, { "code": null, "e": 26561, "s": 26392, "text": "data_type: Type of data to be stored in the array. Here data_type is valid C/C++ data typearray_name: Name of the arraysize1, size2, ..., sizeN: Sizes of the dimensions" }, { "code": null, "e": 26615, "s": 26561, "text": "3-D arrays are an array of Double dimensional arrays:" }, { "code": null, "e": 26637, "s": 26615, "text": "Syntax of a 3D array:" }, { "code": null, "e": 26728, "s": 26637, "text": "data_type array_name[x][y][z];data_type: Type of data to be stored. Valid C/C++ data type." }, { "code": null, "e": 26841, "s": 26728, "text": "For more details on multidimensional and, 3D arrays, please refer to the Multidimensional Arrays in C++ article." }, { "code": null, "e": 26944, "s": 26841, "text": "Problem: Given a 3D array, the task is to dynamically allocate memory for a 3D array using new in C++." }, { "code": null, "e": 27101, "s": 26944, "text": "Solution: In the following methods, the approach used is to make two 2-D arrays and each 2-D array is having 3 rows and 4 columns with the following values." }, { "code": null, "e": 27165, "s": 27101, "text": "1 2 3 4\n5 6 7 8\n9 10 11 12\n\n13 14 15 16\n17 18 19 20\n21 22 23 24" }, { "code": null, "e": 27253, "s": 27165, "text": "X = No of 2D arrays.Y = No of rows of each 2D array.Z = No of columns of each 2D array." }, { "code": null, "e": 27445, "s": 27253, "text": "Method 1: using single pointer – In this method, a memory block of size x*y*z is allocated and then the memory blocks are accessed using pointer arithmetic. Below is the program for the same:" }, { "code": null, "e": 27449, "s": 27445, "text": "C++" }, { "code": "// C++ program to dynamically allocate// the memory for 3D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the 3D array int x = 2, y = 3, z = 4; int count = 0; // Allocate memory blocks // of size x*y*z int* a = new int[x * y * z]; // Traverse the 3D array for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Assign values to the // memory blocks created *(a + i * y * z + j * z + k) = ++count; } } } // Traverse the 3D array again for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Print values of the // memory blocks created cout << *(a + i * y * z + j * z + k) << \" \"; } cout << endl; } cout << endl; } // Deallocate memory delete[] a; return 0;}", "e": 28483, "s": 27449, "text": null }, { "code": null, "e": 28552, "s": 28483, "text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n\n13 14 15 16 \n17 18 19 20 \n21 22 23 24" }, { "code": null, "e": 28636, "s": 28554, "text": "Method 2: using triple pointer – Below is the diagram to illustrate the concept: " }, { "code": null, "e": 28672, "s": 28636, "text": "Below is the program for the same: " }, { "code": null, "e": 28676, "s": 28672, "text": "C++" }, { "code": "// C++ program to dynamically allocate// the memory for 3D array in C++// using new operator#include <iostream>using namespace std; // Driver Codeint main(){ // Dimensions of the 3D array int x = 2, y = 3, z = 4; int count = 0; // Allocate memory blocks of size // x i.e., no of 2D Arrays int*** a = new int**[x]; for (int i = 0; i < x; i++) { // Allocate memory blocks for // rows of each 2D array a[i] = new int*[y]; for (int j = 0; j < y; j++) { // Allocate memory blocks for // columns of each 2D array a[i][j] = new int[z]; } } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Assign values to the // memory blocks created a[i][j][k] = ++count; } } } for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { for (int k = 0; k < z; k++) { // Print values of the // memory blocks created cout << a[i][j][k] << \" \"; } cout << endl; } cout << endl; } // Deallocate memory for (int i = 0; i < x; i++) { for (int j = 0; j < y; j++) { delete[] a[i][j]; } delete[] a[i]; } delete[] a; return 0;}", "e": 30063, "s": 28676, "text": null }, { "code": null, "e": 30132, "s": 30063, "text": "1 2 3 4 \n5 6 7 8 \n9 10 11 12 \n\n13 14 15 16 \n17 18 19 20 \n21 22 23 24" }, { "code": null, "e": 30145, "s": 30134, "text": "ANIKET1996" }, { "code": null, "e": 30157, "s": 30145, "text": "cpp-pointer" }, { "code": null, "e": 30166, "s": 30157, "text": "Pointers" }, { "code": null, "e": 30190, "s": 30166, "text": "Technical Scripter 2020" }, { "code": null, "e": 30197, "s": 30190, "text": "Arrays" }, { "code": null, "e": 30201, "s": 30197, "text": "C++" }, { "code": null, "e": 30217, "s": 30201, "text": "Data Structures" }, { "code": null, "e": 30236, "s": 30217, "text": "Technical Scripter" }, { "code": null, "e": 30252, "s": 30236, "text": "Data Structures" }, { "code": null, "e": 30259, "s": 30252, "text": "Arrays" }, { "code": null, "e": 30268, "s": 30259, "text": "Pointers" }, { "code": null, "e": 30272, "s": 30268, "text": "CPP" }, { "code": null, "e": 30370, "s": 30272, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30401, "s": 30370, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 30426, "s": 30401, "text": "Window Sliding Technique" }, { "code": null, "e": 30464, "s": 30426, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 30485, "s": 30464, "text": "Next Greater Element" }, { "code": null, "e": 30543, "s": 30485, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 30561, "s": 30543, "text": "Vector in C++ STL" }, { "code": null, "e": 30580, "s": 30561, "text": "Inheritance in C++" }, { "code": null, "e": 30626, "s": 30580, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30669, "s": 30626, "text": "Map in C++ Standard Template Library (STL)" } ]
Pandas melt and pivot: Shape tables like JELLY | Towards Data Science
I am not ashamed to admit. melt() and pivot() were the hardest of pandas to learn for me. It took me more than 3-4 months to wrap my head around. When I first saw them, I tried and tried but could not understand how or when they are used. So, I gave up, moved on, and met them again. Tried, failed, moved on, and met again. Repeated many times. What I found baffling was that in this age of millions of video and blog tutorials, I could not find a simple good source that could explain these functions better. My favorite blog for pandas, Practical Business Python, which covers many hard functions of pandas, kindly left them out 😔😔. And, their documentations only make sense after you completely know the functions and some websites (which always rank high if you google these functions) just copy out the documentation😶😶. So, just like I have been writing about hard functions of pandas recently (which are performing really well), the time has come for melt() and pivot(). I hope this post will be useful for people who faced similar difficulties. ∘ Introduction ∘ Setup ∘ Pandas melt() ∘ Pandas melt() on real-world data ∘ Pandas pivot() You can download the notebook and the sample data from this GitHub repo. I also hyperlinked each function’s documentation at their first appearance. Let’s start with a very stupid example. I will create a 1x1 dataframe that holds a city name and a temperature for a single day. Then, I will call melt() on it to see what effect it has: >>> df.melt() So, without any parameters melt() takes a column and turns it into a row with two new columns (excluding the index). Let's add two more cities as columns: If you notice, this type of format for dataframes are not easy to work with and it is not clean. What would be ideal is to take the columns and turn them into rows with their temperature values on the right side: df.melt() Let’s add more temperatures for the cities: What do you think will happen if we call melt() on this version of the dataframe? Watch: df_larger.melt() Just like expected, it converts each column value into a row. For example, let’s take a key-value pair. New York’s temperatures are [25, 27, 23, 25, 29]. This means there are 5 key-value pairs and when we use melt(), pandas takes each of those pairs and displays them as a single row with two columns. After pandas is done with New York, it moves on to other columns. When melt() displays each key-value pair in two columns, it gives the columns default names which are variable and value. It is possible to change them to something that makes more sense: var_name and value_name can be used to change the labels of the melted dataframe's columns. If we keep adding columns, melt() will always convert each value into a row with two columns that contain the previous column's name and its value. Now, let’s get a little serious. Say we have this dataframe: This time, we already have the cities as a column. But still, this type of format for tables are not useful to work with. This dataset holds temperature information for 5 cities for 5 days. We can’t even perform simple computations like mean on this type of data. Let’s try melting the dataframe: >>> temperatures.melt() This is not what we want, melt() turned the city names into rows too. What would be ideal is if we kept the cities as columns and append the remaining columns as rows. melt() has a parameter called id_vars to do just that. If we want to turn only some of the columns into rows, pass the columns to keep as a list (even if it is a single value) to id_vars . id_vars stands for identity variables. temperatures.melt(id_vars=['city']) After using id_vars, the city column stayed as a column. But it has become longer. The reason is that for each city there were 5 days of observations. When we take those observations from columns and display them as rows, pandas automatically adds new rows to fit the new values. Even though we have the table in better shape, the column names are not exactly what we want. Instead of changing them manually after melting the table, we can directly do it with melt(): The same dataframe with different column labels. Now, it is time we work on a real-world dataset to bring the point home. I will load in the NYC stocks dataset which can be downloaded from Kaggle using this link. It contains stocks information for the year 2016 for more than 501 companies: I will subset it for only one month because there are observations for each day: Now, so that I can show you how to use melt() on a real world-data, I will perform an operation using pivot() which I will teach you later in the article. The data now is in this format: It has got 500 rows for all companies and 22 columns for 22 days in February. Each cell contains the close prices of stocks on a given day. Why did I choose this format? Because often real-world data comes in this shape. For example, when recording this dataset, let’s say they wanted to add a new value for a new day. There are 500 companies and if you don’t add the new day as a new column, you would have to write out 500 companies once again adding 500 more rows to the dataset. Adding new observations as new columns is very handy for people who are recording this data. So, now we want to turn back this stocks_small dataset into its original format using melt() so that it is easier to work with. If you look at the data once again, we want to turn all the date columns into two columns which contain (date, close price) key-value pairs preserving the symbol column. Just like we did in the previous examples, if we pass symbol to id_vars, it stays a column and the other dates will become rows: Number of rows in melted table: 10500 Comparing it with the original data: In a nutshell, melt() takes wide dataframes and makes them longer and thinner. pivot() is the complete opposite of melt(). Sometimes, there will be cases where you want to turn your clean, long formatted data into wide. Let's see how I turned that subset stocks into a wide format. Here is the data to remind you: stocks_small.head() Now, I will pivot the table: >>> pivoted.shape(500, 42) When you use pivot(), keep these in mind: pandas will take the variable you pass for index parameter and displays its unique values as indexes.pandas will take the variable you pass for columns and display its unique values as separate columns. pandas will take the variable you pass for index parameter and displays its unique values as indexes. pandas will take the variable you pass for columns and display its unique values as separate columns. If you noticed, the above dataframe is not the one we used with melt(). That's because it also contains the open prices of stocks not just close. In pivot(), there is a parameter called values which if not specified tells pandasto include all of the remaining columns to the pivoted dataframe. Let's choose only the close prices this time: >>> pivoted2.shape(500, 21) That’s pretty much it for pivot(). Surprisingly, it is one of the hardest functions in pandas and yet it only has 3 parameters, not even an extra parameter to fill missing values. For pivot(), just remember that it takes two categorical variables and displays their unique values as index and columns. This resulting table will be a grid of those two variables. If the values parameter is not specified, all the remaining columns are given as cell values which will make the table even wider. Read more articles related to the topic:
[ { "code": null, "e": 517, "s": 172, "text": "I am not ashamed to admit. melt() and pivot() were the hardest of pandas to learn for me. It took me more than 3-4 months to wrap my head around. When I first saw them, I tried and tried but could not understand how or when they are used. So, I gave up, moved on, and met them again. Tried, failed, moved on, and met again. Repeated many times." }, { "code": null, "e": 997, "s": 517, "text": "What I found baffling was that in this age of millions of video and blog tutorials, I could not find a simple good source that could explain these functions better. My favorite blog for pandas, Practical Business Python, which covers many hard functions of pandas, kindly left them out 😔😔. And, their documentations only make sense after you completely know the functions and some websites (which always rank high if you google these functions) just copy out the documentation😶😶." }, { "code": null, "e": 1224, "s": 997, "text": "So, just like I have been writing about hard functions of pandas recently (which are performing really well), the time has come for melt() and pivot(). I hope this post will be useful for people who faced similar difficulties." }, { "code": null, "e": 1315, "s": 1224, "text": "∘ Introduction ∘ Setup ∘ Pandas melt() ∘ Pandas melt() on real-world data ∘ Pandas pivot()" }, { "code": null, "e": 1464, "s": 1315, "text": "You can download the notebook and the sample data from this GitHub repo. I also hyperlinked each function’s documentation at their first appearance." }, { "code": null, "e": 1651, "s": 1464, "text": "Let’s start with a very stupid example. I will create a 1x1 dataframe that holds a city name and a temperature for a single day. Then, I will call melt() on it to see what effect it has:" }, { "code": null, "e": 1665, "s": 1651, "text": ">>> df.melt()" }, { "code": null, "e": 1820, "s": 1665, "text": "So, without any parameters melt() takes a column and turns it into a row with two new columns (excluding the index). Let's add two more cities as columns:" }, { "code": null, "e": 2033, "s": 1820, "text": "If you notice, this type of format for dataframes are not easy to work with and it is not clean. What would be ideal is to take the columns and turn them into rows with their temperature values on the right side:" }, { "code": null, "e": 2043, "s": 2033, "text": "df.melt()" }, { "code": null, "e": 2087, "s": 2043, "text": "Let’s add more temperatures for the cities:" }, { "code": null, "e": 2176, "s": 2087, "text": "What do you think will happen if we call melt() on this version of the dataframe? Watch:" }, { "code": null, "e": 2193, "s": 2176, "text": "df_larger.melt()" }, { "code": null, "e": 2561, "s": 2193, "text": "Just like expected, it converts each column value into a row. For example, let’s take a key-value pair. New York’s temperatures are [25, 27, 23, 25, 29]. This means there are 5 key-value pairs and when we use melt(), pandas takes each of those pairs and displays them as a single row with two columns. After pandas is done with New York, it moves on to other columns." }, { "code": null, "e": 2749, "s": 2561, "text": "When melt() displays each key-value pair in two columns, it gives the columns default names which are variable and value. It is possible to change them to something that makes more sense:" }, { "code": null, "e": 2841, "s": 2749, "text": "var_name and value_name can be used to change the labels of the melted dataframe's columns." }, { "code": null, "e": 2989, "s": 2841, "text": "If we keep adding columns, melt() will always convert each value into a row with two columns that contain the previous column's name and its value." }, { "code": null, "e": 3050, "s": 2989, "text": "Now, let’s get a little serious. Say we have this dataframe:" }, { "code": null, "e": 3347, "s": 3050, "text": "This time, we already have the cities as a column. But still, this type of format for tables are not useful to work with. This dataset holds temperature information for 5 cities for 5 days. We can’t even perform simple computations like mean on this type of data. Let’s try melting the dataframe:" }, { "code": null, "e": 3371, "s": 3347, "text": ">>> temperatures.melt()" }, { "code": null, "e": 3594, "s": 3371, "text": "This is not what we want, melt() turned the city names into rows too. What would be ideal is if we kept the cities as columns and append the remaining columns as rows. melt() has a parameter called id_vars to do just that." }, { "code": null, "e": 3767, "s": 3594, "text": "If we want to turn only some of the columns into rows, pass the columns to keep as a list (even if it is a single value) to id_vars . id_vars stands for identity variables." }, { "code": null, "e": 3803, "s": 3767, "text": "temperatures.melt(id_vars=['city'])" }, { "code": null, "e": 4083, "s": 3803, "text": "After using id_vars, the city column stayed as a column. But it has become longer. The reason is that for each city there were 5 days of observations. When we take those observations from columns and display them as rows, pandas automatically adds new rows to fit the new values." }, { "code": null, "e": 4271, "s": 4083, "text": "Even though we have the table in better shape, the column names are not exactly what we want. Instead of changing them manually after melting the table, we can directly do it with melt():" }, { "code": null, "e": 4320, "s": 4271, "text": "The same dataframe with different column labels." }, { "code": null, "e": 4562, "s": 4320, "text": "Now, it is time we work on a real-world dataset to bring the point home. I will load in the NYC stocks dataset which can be downloaded from Kaggle using this link. It contains stocks information for the year 2016 for more than 501 companies:" }, { "code": null, "e": 4643, "s": 4562, "text": "I will subset it for only one month because there are observations for each day:" }, { "code": null, "e": 4798, "s": 4643, "text": "Now, so that I can show you how to use melt() on a real world-data, I will perform an operation using pivot() which I will teach you later in the article." }, { "code": null, "e": 4830, "s": 4798, "text": "The data now is in this format:" }, { "code": null, "e": 5051, "s": 4830, "text": "It has got 500 rows for all companies and 22 columns for 22 days in February. Each cell contains the close prices of stocks on a given day. Why did I choose this format? Because often real-world data comes in this shape." }, { "code": null, "e": 5406, "s": 5051, "text": "For example, when recording this dataset, let’s say they wanted to add a new value for a new day. There are 500 companies and if you don’t add the new day as a new column, you would have to write out 500 companies once again adding 500 more rows to the dataset. Adding new observations as new columns is very handy for people who are recording this data." }, { "code": null, "e": 5833, "s": 5406, "text": "So, now we want to turn back this stocks_small dataset into its original format using melt() so that it is easier to work with. If you look at the data once again, we want to turn all the date columns into two columns which contain (date, close price) key-value pairs preserving the symbol column. Just like we did in the previous examples, if we pass symbol to id_vars, it stays a column and the other dates will become rows:" }, { "code": null, "e": 5871, "s": 5833, "text": "Number of rows in melted table: 10500" }, { "code": null, "e": 5908, "s": 5871, "text": "Comparing it with the original data:" }, { "code": null, "e": 5987, "s": 5908, "text": "In a nutshell, melt() takes wide dataframes and makes them longer and thinner." }, { "code": null, "e": 6222, "s": 5987, "text": "pivot() is the complete opposite of melt(). Sometimes, there will be cases where you want to turn your clean, long formatted data into wide. Let's see how I turned that subset stocks into a wide format. Here is the data to remind you:" }, { "code": null, "e": 6242, "s": 6222, "text": "stocks_small.head()" }, { "code": null, "e": 6271, "s": 6242, "text": "Now, I will pivot the table:" }, { "code": null, "e": 6298, "s": 6271, "text": ">>> pivoted.shape(500, 42)" }, { "code": null, "e": 6340, "s": 6298, "text": "When you use pivot(), keep these in mind:" }, { "code": null, "e": 6543, "s": 6340, "text": "pandas will take the variable you pass for index parameter and displays its unique values as indexes.pandas will take the variable you pass for columns and display its unique values as separate columns." }, { "code": null, "e": 6645, "s": 6543, "text": "pandas will take the variable you pass for index parameter and displays its unique values as indexes." }, { "code": null, "e": 6747, "s": 6645, "text": "pandas will take the variable you pass for columns and display its unique values as separate columns." }, { "code": null, "e": 7087, "s": 6747, "text": "If you noticed, the above dataframe is not the one we used with melt(). That's because it also contains the open prices of stocks not just close. In pivot(), there is a parameter called values which if not specified tells pandasto include all of the remaining columns to the pivoted dataframe. Let's choose only the close prices this time:" }, { "code": null, "e": 7115, "s": 7087, "text": ">>> pivoted2.shape(500, 21)" }, { "code": null, "e": 7295, "s": 7115, "text": "That’s pretty much it for pivot(). Surprisingly, it is one of the hardest functions in pandas and yet it only has 3 parameters, not even an extra parameter to fill missing values." }, { "code": null, "e": 7608, "s": 7295, "text": "For pivot(), just remember that it takes two categorical variables and displays their unique values as index and columns. This resulting table will be a grid of those two variables. If the values parameter is not specified, all the remaining columns are given as cell values which will make the table even wider." } ]
How I built a Face Mask Detector for COVID-19 using PyTorch Lightning (updated PL V.1.3.5) | by Jad Haddad | Towards Data Science
A couple of days before the end of quarantine in France, I was reading the news, and I stumbled upon an article: France is using AI to check whether people are wearing masks on public transport. French startup DatakaLab, which created the program, says the goal is not to identify or punish individuals who don’t wear masks, but to generate anonymous statistical data that will help authorities anticipate future outbreaks of COVID-19 So I decided to give it a try, and build my own face mask detector to detect whether someone is wearing a mask or not. To train a deep learning model to classify whether a person is wearing a mask or not, we need to find a good dataset with a fair amount of images for both classes: wearing a mask not wearing a mask Real World Masked Face Dataset (RMFD) provides just what we need! This dataset was created for facial recognition purposes. However, we’re going to use it for face mask detection. The rest of this post is organized in the following way: 2.1. Data extraction2.2. Building the Dataset class2.3. Building our face mask detector model2.4. Training our model2.5. Testing our model on real data2.6. Results Without further ado, let’s jump right into it! Content Unavailable Sorry, this content is not available in your location. The RMFD provides 2 datasets: Real-world masked face recognition dataset: it contains 5,000 masked faces of 525 people and 90,000 normal faces.Simulated masked face recognition datasets. Real-world masked face recognition dataset: it contains 5,000 masked faces of 525 people and 90,000 normal faces. Simulated masked face recognition datasets. In this experiment, we are going to use the first dataset. After downloading and unzipping the dataset, its structure looks as follows: self-built-masked-face-recognition-dataset├AFDB_masked_face_dataset│ ├subject-id│ │ ├image-id.jpg│ │ └...│ └...└AFDB_face_dataset ├subject-id │ ├image-id.jpg │ └... └... We create our pandas DataFrame by iterating over the images and assigning to each image a label of 0 if the face is not masked, and 1 if the face is masked. The images of this dataset are already cropped around the face, so we won’t need to extract the face from each image.The following code illustrates the data extraction process: Now that we have our pandas DataFrame ready, it is time to build the Dataset class, which will be used for querying samples by batches in a way interpretable by PyTorch. Our model is going to take 100x100 images as input, so we transform each sample image when querying it, by resizing it to 100x100 and then convert it to a Tensor , which is the base data type that PyTorch can manipulate: Now for the fun part! Content Unavailable Sorry, this content is not available in your location. We’re going to be using PyTorch Lightning, which is a thin wrapper around PyTorch. PyTorch Lightning structures your code efficiently in a single class containing everything we need to define and train a model, and you can overwrite any method provided to your needs, making it easy to scale up while avoiding spaghetti code. PyTorch Lightning exposes many methods for the training/validation loop. However, we are going to be using some of them for our needs. The following are the methods we’re going to override, and are going to be called in the following order internally: 1. Setup: __init__() prepare_data() configure_optimizer() train_dataloader() val_dataloader() 2. Training loop: training_step() training_epoch_end() 3. Validation loop: validation_step() validation_epoch_end() To define our model, we subclass the LightningModule of PyTorch Lightning, and define our model architecture along with the forward pass. We also use the Accuracy class provided by TorchMetricspackage, which will take care of computing the train/validation accuracies for us. We’re going to keep it simple and use 4 convolution layers followed by 2 linear layers. We’re going to use ReLU as activation function, and the MaxPool2das the pooling layer. We then initialize the weights of these layers with xavier_uniform as this will make the network train better: Our dataset is imbalanced (5,000 masked faces VS 90,000 non-masked faces). Therefore, when splitting the dataset into train/validation, we need to keep the same proportions of the samples in train/validation as the whole dataset. We do that by using the train_test_split function of sklearn and we pass the dataset’s labels to its stratisfy parameter, and it will do the rest for us. We’re going to use 70% of the dataset for training and 30% for validation: When dealing with unbalanced data, we need to pass this information to the loss function to avoid unproportioned step sizes of the optimizer. We do this by assigning a weight to each class, according to its representability in the dataset. We assign more weight to classes with a small number of samples so that the network will be penalized more if it makes mistakes predicting the label of these classes. While classes with large numbers of samples, we assign to them a smaller weight. This makes our network training agnostic to the proportion of classes. A good rule of thumb for choosing the weight for each class is by using this formula: This translates to the following code: We’re going to define our data loaders that are going to be used for training and validation. We train our model using a batch of size 32. We shuffle our training batch samples each time so our model can train better by receiving data in a non-repetitive fashion. To reduce the time of loading the batch samples, which can be a bottleneck in the training loop, we set the number of workers to 4, this will perform multi-process data loading: We define our optimizer by overriding the configure_optimizers() method and returning the desired optimizer. We are going to use Adam for the purpose of this post, and we fix the learning rate to 0.00001 : In the training step, we receive a batch of samples, pass them through our model via the forward pass, and compute the loss of that batch. We can also log the loss, and PyTorch Lightning takes care of creating the log files for TensorBoard automatically for us: In the training_epoch_end() we compute the training accuracy and log it so we can visualize it in TensorBoard later on. We then reset the training accuracy variable so that in the next epoch, the accuracy doesn’t carry values from previous epochs: At the end of each training epoch, the validation_step() is called on each batch of the validation data, we compute the accuracy and the loss, and return the loss in a dictionary. The returned values will be used in the next section: In the validation_epoch_end() we receive all the data returned from validation_step() (from the previous section). We calculate the average accuracy and loss and log them so we can visualize them in TensorBoard later on: To train our model we simply initialize our MaskDetector object and pass it to the fit() method of the Trainer class provided by PyTorch Lightning. We also define a model checkpointing callback and a TensorBoard logger, we want to save the model with the best accuracy and the lowest loss. We are going to train our model for 10 epochs: We can see that the validation loss is decreasing across epochs: And the validation accuracy of our model reaches its highest peak on epoch 8, yielding an accuracy of 99%. After epoch 8 (where the red arrow is pointing) our model starts overfitting. Thus, the validation accuracy starts to degrade. So we’re gonna take the saved model of epoch 8 and use it for testing on real data! To test our model on real data, we need to use a face detection model that is robust against occlusions of the face. Fortunately, OpenCV has a deep learning face detection model that we can use. This deep learning model is a more accurate alternative to the Haar-Cascade model, and its detection frame is a rectangle and not a square. Therefore, the face frame can fit the entirety of the face without capturing parts of the background, which can interfere with our face mask model predictions. A good tutorial on how to use OpenCV’s deep learning face detection is the following: www.pyimagesearch.com To run inferences on a video, we’re going to use our saved model from the previous section, and process each frame: Extract the faces Pass them to our face mask detector model Draw a bounding box around the detected faces, along with the predictions computed by our model. The following is an extract of the processing video code: I asked a couple of friends to film themselves put a mask on, and then take it off. These are the results! It looks like our model is working great even with a custom made mask! Our model’s weights file size is around 8 Mb, and the inferences on a CPU are near-realtime!!👌 The full code is available on GitHub 😃 Note from the editors: Towards Data Science is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click here.
[ { "code": null, "e": 367, "s": 172, "text": "A couple of days before the end of quarantine in France, I was reading the news, and I stumbled upon an article: France is using AI to check whether people are wearing masks on public transport." }, { "code": null, "e": 607, "s": 367, "text": "French startup DatakaLab, which created the program, says the goal is not to identify or punish individuals who don’t wear masks, but to generate anonymous statistical data that will help authorities anticipate future outbreaks of COVID-19" }, { "code": null, "e": 726, "s": 607, "text": "So I decided to give it a try, and build my own face mask detector to detect whether someone is wearing a mask or not." }, { "code": null, "e": 890, "s": 726, "text": "To train a deep learning model to classify whether a person is wearing a mask or not, we need to find a good dataset with a fair amount of images for both classes:" }, { "code": null, "e": 905, "s": 890, "text": "wearing a mask" }, { "code": null, "e": 924, "s": 905, "text": "not wearing a mask" }, { "code": null, "e": 1104, "s": 924, "text": "Real World Masked Face Dataset (RMFD) provides just what we need! This dataset was created for facial recognition purposes. However, we’re going to use it for face mask detection." }, { "code": null, "e": 1161, "s": 1104, "text": "The rest of this post is organized in the following way:" }, { "code": null, "e": 1325, "s": 1161, "text": "2.1. Data extraction2.2. Building the Dataset class2.3. Building our face mask detector model2.4. Training our model2.5. Testing our model on real data2.6. Results" }, { "code": null, "e": 1372, "s": 1325, "text": "Without further ado, let’s jump right into it!" }, { "code": null, "e": 1392, "s": 1372, "text": "Content Unavailable" }, { "code": null, "e": 1447, "s": 1392, "text": "Sorry, this content is not available in your location." }, { "code": null, "e": 1477, "s": 1447, "text": "The RMFD provides 2 datasets:" }, { "code": null, "e": 1634, "s": 1477, "text": "Real-world masked face recognition dataset: it contains 5,000 masked faces of 525 people and 90,000 normal faces.Simulated masked face recognition datasets." }, { "code": null, "e": 1748, "s": 1634, "text": "Real-world masked face recognition dataset: it contains 5,000 masked faces of 525 people and 90,000 normal faces." }, { "code": null, "e": 1792, "s": 1748, "text": "Simulated masked face recognition datasets." }, { "code": null, "e": 1928, "s": 1792, "text": "In this experiment, we are going to use the first dataset. After downloading and unzipping the dataset, its structure looks as follows:" }, { "code": null, "e": 2102, "s": 1928, "text": "self-built-masked-face-recognition-dataset├AFDB_masked_face_dataset│ ├subject-id│ │ ├image-id.jpg│ │ └...│ └...└AFDB_face_dataset ├subject-id │ ├image-id.jpg │ └... └..." }, { "code": null, "e": 2436, "s": 2102, "text": "We create our pandas DataFrame by iterating over the images and assigning to each image a label of 0 if the face is not masked, and 1 if the face is masked. The images of this dataset are already cropped around the face, so we won’t need to extract the face from each image.The following code illustrates the data extraction process:" }, { "code": null, "e": 2827, "s": 2436, "text": "Now that we have our pandas DataFrame ready, it is time to build the Dataset class, which will be used for querying samples by batches in a way interpretable by PyTorch. Our model is going to take 100x100 images as input, so we transform each sample image when querying it, by resizing it to 100x100 and then convert it to a Tensor , which is the base data type that PyTorch can manipulate:" }, { "code": null, "e": 2849, "s": 2827, "text": "Now for the fun part!" }, { "code": null, "e": 2869, "s": 2849, "text": "Content Unavailable" }, { "code": null, "e": 2924, "s": 2869, "text": "Sorry, this content is not available in your location." }, { "code": null, "e": 3250, "s": 2924, "text": "We’re going to be using PyTorch Lightning, which is a thin wrapper around PyTorch. PyTorch Lightning structures your code efficiently in a single class containing everything we need to define and train a model, and you can overwrite any method provided to your needs, making it easy to scale up while avoiding spaghetti code." }, { "code": null, "e": 3502, "s": 3250, "text": "PyTorch Lightning exposes many methods for the training/validation loop. However, we are going to be using some of them for our needs. The following are the methods we’re going to override, and are going to be called in the following order internally:" }, { "code": null, "e": 3512, "s": 3502, "text": "1. Setup:" }, { "code": null, "e": 3523, "s": 3512, "text": "__init__()" }, { "code": null, "e": 3538, "s": 3523, "text": "prepare_data()" }, { "code": null, "e": 3560, "s": 3538, "text": "configure_optimizer()" }, { "code": null, "e": 3579, "s": 3560, "text": "train_dataloader()" }, { "code": null, "e": 3596, "s": 3579, "text": "val_dataloader()" }, { "code": null, "e": 3614, "s": 3596, "text": "2. Training loop:" }, { "code": null, "e": 3630, "s": 3614, "text": "training_step()" }, { "code": null, "e": 3651, "s": 3630, "text": "training_epoch_end()" }, { "code": null, "e": 3671, "s": 3651, "text": "3. Validation loop:" }, { "code": null, "e": 3689, "s": 3671, "text": "validation_step()" }, { "code": null, "e": 3712, "s": 3689, "text": "validation_epoch_end()" }, { "code": null, "e": 4274, "s": 3712, "text": "To define our model, we subclass the LightningModule of PyTorch Lightning, and define our model architecture along with the forward pass. We also use the Accuracy class provided by TorchMetricspackage, which will take care of computing the train/validation accuracies for us. We’re going to keep it simple and use 4 convolution layers followed by 2 linear layers. We’re going to use ReLU as activation function, and the MaxPool2das the pooling layer. We then initialize the weights of these layers with xavier_uniform as this will make the network train better:" }, { "code": null, "e": 4733, "s": 4274, "text": "Our dataset is imbalanced (5,000 masked faces VS 90,000 non-masked faces). Therefore, when splitting the dataset into train/validation, we need to keep the same proportions of the samples in train/validation as the whole dataset. We do that by using the train_test_split function of sklearn and we pass the dataset’s labels to its stratisfy parameter, and it will do the rest for us. We’re going to use 70% of the dataset for training and 30% for validation:" }, { "code": null, "e": 4973, "s": 4733, "text": "When dealing with unbalanced data, we need to pass this information to the loss function to avoid unproportioned step sizes of the optimizer. We do this by assigning a weight to each class, according to its representability in the dataset." }, { "code": null, "e": 5378, "s": 4973, "text": "We assign more weight to classes with a small number of samples so that the network will be penalized more if it makes mistakes predicting the label of these classes. While classes with large numbers of samples, we assign to them a smaller weight. This makes our network training agnostic to the proportion of classes. A good rule of thumb for choosing the weight for each class is by using this formula:" }, { "code": null, "e": 5417, "s": 5378, "text": "This translates to the following code:" }, { "code": null, "e": 5859, "s": 5417, "text": "We’re going to define our data loaders that are going to be used for training and validation. We train our model using a batch of size 32. We shuffle our training batch samples each time so our model can train better by receiving data in a non-repetitive fashion. To reduce the time of loading the batch samples, which can be a bottleneck in the training loop, we set the number of workers to 4, this will perform multi-process data loading:" }, { "code": null, "e": 6065, "s": 5859, "text": "We define our optimizer by overriding the configure_optimizers() method and returning the desired optimizer. We are going to use Adam for the purpose of this post, and we fix the learning rate to 0.00001 :" }, { "code": null, "e": 6327, "s": 6065, "text": "In the training step, we receive a batch of samples, pass them through our model via the forward pass, and compute the loss of that batch. We can also log the loss, and PyTorch Lightning takes care of creating the log files for TensorBoard automatically for us:" }, { "code": null, "e": 6575, "s": 6327, "text": "In the training_epoch_end() we compute the training accuracy and log it so we can visualize it in TensorBoard later on. We then reset the training accuracy variable so that in the next epoch, the accuracy doesn’t carry values from previous epochs:" }, { "code": null, "e": 6809, "s": 6575, "text": "At the end of each training epoch, the validation_step() is called on each batch of the validation data, we compute the accuracy and the loss, and return the loss in a dictionary. The returned values will be used in the next section:" }, { "code": null, "e": 7030, "s": 6809, "text": "In the validation_epoch_end() we receive all the data returned from validation_step() (from the previous section). We calculate the average accuracy and loss and log them so we can visualize them in TensorBoard later on:" }, { "code": null, "e": 7367, "s": 7030, "text": "To train our model we simply initialize our MaskDetector object and pass it to the fit() method of the Trainer class provided by PyTorch Lightning. We also define a model checkpointing callback and a TensorBoard logger, we want to save the model with the best accuracy and the lowest loss. We are going to train our model for 10 epochs:" }, { "code": null, "e": 7432, "s": 7367, "text": "We can see that the validation loss is decreasing across epochs:" }, { "code": null, "e": 7539, "s": 7432, "text": "And the validation accuracy of our model reaches its highest peak on epoch 8, yielding an accuracy of 99%." }, { "code": null, "e": 7750, "s": 7539, "text": "After epoch 8 (where the red arrow is pointing) our model starts overfitting. Thus, the validation accuracy starts to degrade. So we’re gonna take the saved model of epoch 8 and use it for testing on real data!" }, { "code": null, "e": 8245, "s": 7750, "text": "To test our model on real data, we need to use a face detection model that is robust against occlusions of the face. Fortunately, OpenCV has a deep learning face detection model that we can use. This deep learning model is a more accurate alternative to the Haar-Cascade model, and its detection frame is a rectangle and not a square. Therefore, the face frame can fit the entirety of the face without capturing parts of the background, which can interfere with our face mask model predictions." }, { "code": null, "e": 8331, "s": 8245, "text": "A good tutorial on how to use OpenCV’s deep learning face detection is the following:" }, { "code": null, "e": 8353, "s": 8331, "text": "www.pyimagesearch.com" }, { "code": null, "e": 8469, "s": 8353, "text": "To run inferences on a video, we’re going to use our saved model from the previous section, and process each frame:" }, { "code": null, "e": 8487, "s": 8469, "text": "Extract the faces" }, { "code": null, "e": 8529, "s": 8487, "text": "Pass them to our face mask detector model" }, { "code": null, "e": 8626, "s": 8529, "text": "Draw a bounding box around the detected faces, along with the predictions computed by our model." }, { "code": null, "e": 8684, "s": 8626, "text": "The following is an extract of the processing video code:" }, { "code": null, "e": 8957, "s": 8684, "text": "I asked a couple of friends to film themselves put a mask on, and then take it off. These are the results! It looks like our model is working great even with a custom made mask! Our model’s weights file size is around 8 Mb, and the inferences on a CPU are near-realtime!!👌" }, { "code": null, "e": 8996, "s": 8957, "text": "The full code is available on GitHub 😃" } ]
Course 2 — Data structure — Part 1: The Basic data structures | by Phat Le | Towards Data Science
A famous quote: Program = Algorithms + Data Structures. In last series, we talked about 3 algorithms greedy, divide and conquer, dynamic programming to approach a problem. In next series, we will take a look at data structures to help us solve more complex problems. Let get started with the most fundamental data structures: Array, List(linked-list). And see how queues, stacks can build upon these data structures. What is tree? how to calculate height of a tree without recursive. Array is contiguous area of memory consisting of equal-size elements indexed by contiguous integers. In memory, we just save the pointer address to the array, because all elements are equal-size and continuously in memory, so to get address of element i-th, we just calculate: pointer_address + element_size * i. Base on this definition, we can easy to see the cost of operations on array: Singly-linked list has many nodes, each node contains key(data) and pointer to the next element. The first node called head, the last node called tail. Base on this definition, we can implement singly-linked list easily: def push_front(key): node <- new node node.key <- key node.next = head head <- node if tail == nil: tail <- headdef pop_front(): if head == nil: ERROR: empty list head <- head.next if head = nil: tail <- nildef push_back(key): node <- new node node.key <- key node.next = nil if tail = nil: head <- tail <- node else: tail.next <- node tail <- nodedef pop_back(): if head == nil: ERROR: empty list if head == tail: head <- tail <- nil else: p <- head while p.next.next != nil: p <- p.next p.next <- nil; tail <- pdef add_after(node, key): node2 <- new node node2.key <- key node2.next = node.next node.next = node2 if tail == node: tail <- node2 In singly-linked list, we have only one node to point to next element and operations like PopBack and AddBefore take O(n) to run. With double-linked list, we can run these operations with O(1). We have 2 nodes to point to next element and previous element. def push_back(key): node <- new node node.key <- key; node.next = nil if tail = nil: head <- tail <- node node.prev <- nil else: tail.next <- node node.prev <- tail tail <- nodedef pop_back(): if head = nil: ERROR: empty list if head = tail: head <- tail <- nil else: tail <- tail.prev tail.next <- nildef add_after(node, key): node2 <- new node node2.key <- key node2.next <- node.next node2.prev <- node node.next < node2 if node2.next != nil: node2.next.prev <- node2 if tail = node: tail <- node2def add_before(node, key): node2 <- new node node2.key <- key node2.next <- node node2.prev <- node.prev node.prev <- node2 if node2.prev != nill: node2.prev.next <- node2 if head = node: head <- node2 Stack is abstract data-type with following operations. Push(Key): adds key to collection. Top(): returns most recently-added key. Pop(): removes and returns most recently-added key Empty(): are there any elements? Stack, also know as LIFO queues, can be implemented with either an array or linked-list and has O(1) for Push, Pop, Top, Empty operations. Let say, we want to a checker for a text editor. We want to check the text input is balanced brackets following: Balanced: ([]) [] () ((([([])]))()) Unbalanced: ([]]() ][ With Stack data structure, we can solve this problem easily: def is_balanced(str): Stack stack for char in str: if char in [ '(', '[' ]: stack.push(char) else: if stack.empty(): return False top <- stack.pop() if (top = '[' and char != ']') or (top = '(' and char != ')'): return False return stack.empty() Queue is abstract data type with the following operations: Enqueue(key): adds key to collection. Dequeue(): removes and returns least recently-added key. Empty(): are there any elements? Queue, also know as FIFO(First In First Out), can be implemented with either a linked list (with tail pointer) or an array and has O(1) for Enqueue, Dequeue, Empty operations. See these visualizations: array-based stack, list-based stack, array-based queue, list-based queue. Tree has a root node and many other nodes, each node contains: key, children, parent(optional). For binary tree, a node contains: key, left, right, parent(optional). This is an example of a binary tree, we have Les as root and many other nodes, each node has left and right like: Cathy(left), Sam(right) for root node. To calculate height of tree, we can use recursive: def height(tree): if tree = nil: return 0 return 1 + Max(height(tree.left), height(tree.right)) We have 2 ways to visit the nodes of a tree in a particular order: Depth-first: We completely traverse on sub-tree before exploring a sibling sub-tree. def post_order_traversal(tree): if tree = nil: return post_order_traversal(tree.left) post_order_traversal(tree.right) print(tree.key) Breadth-first: We traverse all node at one level before progressing to the next level. def level_traversal(tree): if tree = nil: return Queue q q.Enqueue(tree) while not q.empty(): node <- q.dequeue() print(node) if node.left != nil: q.enqueue(node.left) if node.left != nil: q.enqueue(node.right) In this problem you will implement a feature for a text editor to find errors in the usage of brackets in the code. Problem Description Task. Your friend is making a text editor for programmers. He is currently working on a feature that will find errors in the usage of different types of brackets. Code can contain any brackets from the set []{}(), where the opening brackets are [,{, and ( and the closing brackets corresponding to them are ],}, and ). For convenience, the text editor should not only inform the user that there is an error in the usage of brackets, but also point to the exact place in the code with the problematic bracket. First priority is to find the first unmatched closing bracket which either doesn’t have an opening bracket before it, like ] in ](), or closes the wrong opening bracket, like } in ()[}. If there are no such mistakes, then it should find the first unmatched opening bracket without the corresponding closing bracket after it, like ( in {}([]. If there are no mistakes, text editor should inform the user that the usage of brackets is correct. Apart from the brackets, code can contain big and small latin letters, digits and punctuation marks. More formally, all brackets in the code should be divided into pairs of matching brackets, such that in each pair the opening bracket goes before the closing bracket, and for any two pairs of brackets either one of them is nested inside another one as in (foo[bar]) or they are separate as in f(a,b)-g[c]. The bracket [ corresponds to the bracket ], { corresponds to }, and ( corresponds to ). Input Format. Input contains one string S which consists of big and small latin letters, digits, punctuation marks and brackets from the set []{}(). Output Format. If the code in S uses brackets correctly, output “Success” (without the quotes). Otherwise, output the 1-based index of the first unmatched closing bracket, and if there are no unmatched closing brackets, output the 1-based index of the first unmatched opening bracket. Sample 1. Input: {}[] Output: Success Explanation: The brackets are used correctly: there are two pairs of brackets — first pair of { and }, and second pair of [ and ] — and these pairs do not intersect. Sample 2. Input: { Output: 1 Explanation: The code { doesn’t use brackets correctly, because brackets cannot be divided into pairs (there is just one bracket). There are no closing brackets, and the first unmatched opening bracket is {, and its position is 1, so we output 1. Sample 3. Input: {[} Output: 3 Explanation: The bracket } is unmatched, because the last unmatched opening bracket before it is [ and not {. It is the first unmatched closing bracket, and our first priority is to output the first unmatched closing bracket, and its position is 3, so we output 3. Sample 3. Input: foo(bar[i); Output: 10 Explanation: ) doesn’t match [, so ) is the first unmatched closing bracket, so we output its position, which is 10. To solve this problem, you can slightly modify the IsBalanced algorithm from the lectures to account not only for the brackets, but also for other characters in the code, and return not just whether the code uses brackets correctly, but also what is the first position where the code becomes broken. In the lectures, the IsBalanced pseudocode gave us the solution for brackets: “ () [] “. We only need to check “ {} “ and track position for each bracket we push to stack. Trees are used to manipulate hierarchical data such as hierarchy of categories of a retailer or the directory structure on your computer. They are also used in data analysis and machine learning both for hierarchical clustering and building complex predictive models, including some of the best-performing in practice algorithms like Gradient Boosting over Decision Trees and Random Forests. In the later modules of this course, we will introduce balanced binary search trees (BST) — a special kind of trees that allows to very efficiently store, manipulate and retrieve data. Balanced BSTs are thus used in databases for efficient storage and actually in virtually any non-trivial programs, typically via built-in data structures of the programming language at hand. In this problem, your goal is to get used to trees. You will need to read a description of a tree from the input, implement the tree data structure, store the tree and compute its height. Problem Description Task. You are given a description of a rooted tree. Your task is to compute and output its height. Recall that the height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a leaf to the root. You are given an arbitrary tree, not necessarily a binary tree. Input Format. The first line contains the number of nodes n. The second line contains n integer numbers from −1 to n − 1 — parents of nodes. If the i-th one of them (0 ≤ i ≤ n − 1) is −1, node i is the root, otherwise it’s 0-based index of the parent of i-th node. It is guaranteed that there is exactly one root. It is guaranteed that the input represents a tree. Output Format. Output the height of the tree. Sample 1. Input: 5 4 -1 4 1 1 Output: 3 Explanation: The input means that there are 5 nodes with numbers from 0 to 4, node 0 is a child of node 4, node 1 is the root, node 2 is a child of node 4, node 3 is a child of node 1 and node 4 is a child of node 1. To see this, let us write numbers of nodes from 0 to 4 in one line and the numbers given in the input in the second line underneath: 0 1 2 3 44 -1 4 1 1 Now we can see that the node number 1 is the root, because −1 corresponds to it in the second line. Also, we know that the nodes number 3 and number 4 are children of the root node 1. Also, we know that the nodes number 0 and number 2 are children of the node 4. The height of this tree is 3, because the number of vertices on the path from root 1 to leaf 2 is 3. Sample 2. Input: 5 -1 0 4 0 3 Output: 4 Explanation: The input means that there are 5 nodes with numbers from 0 to 4, node 0 is the root, node 1 is a child of node 0, node 2 is a child of node 4, node 3 is a child of node 0 and node 4 is a child of node 3. The height of this tree is 4, because the number of nodes on the path from root 0 to leaf 2 is 4. To solve this problem, change the height function described in the lectures with an implementation which will work for an arbitrary tree. Note that the tree can be very deep in this problem, so you should be careful to avoid stack overflow problems if you’re using recursion, and definitely test your solution on a tree with the maximum possible height. Suggestion: Take advantage of the fact that the labels for each tree node are integers in the range 0..n−1: you can store each node in an array whose index is the label of the node. By storing the nodes in an array, you have O(1) access to any node given its label. Create an array of n nodes: allocate nodes[n] for i ← 0 to n − 1: nodes[i] =new Node Then, read each parent index: for child_index ← 0 to n − 1: read parent_index if parent_index == −1: root ← child_index else: nodes[parent_index].addChild(nodes[child_index]) Once you’ve built the tree, you’ll then need to compute its height. If you don’t use recursion, you needn’t worry about stack overflow problems. Without recursion, you’ll need some auxiliary data structure to keep track of the current state (in the breadth-first seach code in lecture, for example, we used a queue). After we built the tree, we can use queue to calculate the height of the tree. To do that, we will use Breadth-First travel, for each level, we increase height 1 more. In this problem you will implement a program to simulate the processing of network packets Problem Description Task. You are given a series of incoming network packets, and your task is to simulate their processing. Packets arrive in some order. For each packet number i, you know the time when it arrived Ai and the time it takes the processor to process it Pi (both in milliseconds). There is only one processor, and it processes the incoming packets in the order of their arrival. If the processor started to process some packet, it doesn’t interrupt or stop until it finishes the processing of this packet, and the processing of packet i takes exactly Pi milliseconds. The computer processing the packets has a network buffer of fixed size S. When packets arrive, they are stored in the buffer before being processed. However, if the buffer is full when a packet arrives (there are S packets which have arrived before this packet, and the computer hasn’t finished processing any of them), it is dropped and won’t be processed at all. If several packets arrive at the same time, they are first all stored in the buffer (some of them may be dropped because of that — those which are described later in the input). The computer processes the packets in the order of their arrival, and it starts processing the next available packet from the buffer as soon as it finishes processing the previous one. If at some point the computer is not busy, and there are no packets in the buffer, the computer just waits for the next packet to arrive. Note that a packet leaves the buffer and frees the space in the buffer as soon as the computer finishes processing it. Input Format. The first line of the input contains the size S of the buffer and the number n of incoming network packets. Each of the next n lines contains two numbers. i-th line contains the time of arrival Ai and the processing time Pi (both in milliseconds) of the i-th packet. It is guaranteed that the sequence of arrival times is non-decreasing (however, it can contain the exact same times of arrival in milliseconds — in this case the packet which is earlier in the input is considered to have arrived earlier). Output Format. For each packet output either the moment of time (in milliseconds) when the processor began processing it or −1 if the packet was dropped (output the answers for the packets in the same order as the packets are given in the input). Sample 1. Input: 1 1 0 0 Output: 0 Explanation: The only packet arrived at time 0, and computer started processing it immediately. Sample 3. Input: 1 2 0 1 0 1 Output: 0 -1 Explanation: The first packet arrived at time 0, the second packet also arrived at time 0, but was dropped, because the network buffer has size 1 and it was full with the first packet already. The first packet started processing at time 0, and the second packet was not processed at all. Sample 4. Input: 1 2 0 1 1 1 Output: 0 1 Explanation: The first packet arrived at time 0, the computer started processing it immediately and finished at time 1. The second packet arrived at time 1, and the computer started processing it immediately. To solve this problem, you can use a list or a queue (in this case the queue should allow accessing its last element, and such queue is usually called a deque). You can use the corresponding built-in data structure in your language of choice. One possible solution is to store in the list or queue finish_time the times when the computer will finish processing the packets which are currently stored in the network buffer, in increasing order. When a new packet arrives, you will first need to pop from the front of finish_time all the packets which are already processed by the time new packet arrives. Then you try to add the finish time for the new packet in finish_time. If the buffer is full (there are already S finish times in finish_time), the packet is dropped. Otherwise, its processing finish time is added to finish_time. If finish_time is empty when a new packet arrives, computer will start processing the new packet immediately as soon as it arrives. Otherwise, computer will start processing the new packet as soon as it finishes to process the last of the packets currently in finish_time (here is when you need to access the last element of finish_time to determine when the computer will start to process the new packet). You will also need to compute the processing finish time by adding Pi to the processing start time and push it to the back of finish_time. You need to remember to output the processing start time for each packet instead of the processing finish time which you store in finish_time. To solve this problem, we need to notice at some points: We just need to keep track of finishing time. The current time processing is the time each request comes in. At each time request arrived, we should remove all request has done in finish_time queue. Always queue new request when finish_time is empty. See the chapter 10.2 [CLRS] — Array, Linked-List See the chapter 10.1 [CLRS] — Stack and Queue See the chapter 10.4 [CLRS] — Tree [CLRS] Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein. Introduction to Algorithms (3rd Edition). MIT Press and McGraw-Hill. 2009.
[ { "code": null, "e": 656, "s": 172, "text": "A famous quote: Program = Algorithms + Data Structures. In last series, we talked about 3 algorithms greedy, divide and conquer, dynamic programming to approach a problem. In next series, we will take a look at data structures to help us solve more complex problems. Let get started with the most fundamental data structures: Array, List(linked-list). And see how queues, stacks can build upon these data structures. What is tree? how to calculate height of a tree without recursive." }, { "code": null, "e": 757, "s": 656, "text": "Array is contiguous area of memory consisting of equal-size elements indexed by contiguous integers." }, { "code": null, "e": 969, "s": 757, "text": "In memory, we just save the pointer address to the array, because all elements are equal-size and continuously in memory, so to get address of element i-th, we just calculate: pointer_address + element_size * i." }, { "code": null, "e": 1046, "s": 969, "text": "Base on this definition, we can easy to see the cost of operations on array:" }, { "code": null, "e": 1267, "s": 1046, "text": "Singly-linked list has many nodes, each node contains key(data) and pointer to the next element. The first node called head, the last node called tail. Base on this definition, we can implement singly-linked list easily:" }, { "code": null, "e": 2065, "s": 1267, "text": "def push_front(key): node <- new node node.key <- key node.next = head head <- node if tail == nil: tail <- headdef pop_front(): if head == nil: ERROR: empty list head <- head.next if head = nil: tail <- nildef push_back(key): node <- new node node.key <- key node.next = nil if tail = nil: head <- tail <- node else: tail.next <- node tail <- nodedef pop_back(): if head == nil: ERROR: empty list if head == tail: head <- tail <- nil else: p <- head while p.next.next != nil: p <- p.next p.next <- nil; tail <- pdef add_after(node, key): node2 <- new node node2.key <- key node2.next = node.next node.next = node2 if tail == node: tail <- node2" }, { "code": null, "e": 2322, "s": 2065, "text": "In singly-linked list, we have only one node to point to next element and operations like PopBack and AddBefore take O(n) to run. With double-linked list, we can run these operations with O(1). We have 2 nodes to point to next element and previous element." }, { "code": null, "e": 3171, "s": 2322, "text": "def push_back(key): node <- new node node.key <- key; node.next = nil if tail = nil: head <- tail <- node node.prev <- nil else: tail.next <- node node.prev <- tail tail <- nodedef pop_back(): if head = nil: ERROR: empty list if head = tail: head <- tail <- nil else: tail <- tail.prev tail.next <- nildef add_after(node, key): node2 <- new node node2.key <- key node2.next <- node.next node2.prev <- node node.next < node2 if node2.next != nil: node2.next.prev <- node2 if tail = node: tail <- node2def add_before(node, key): node2 <- new node node2.key <- key node2.next <- node node2.prev <- node.prev node.prev <- node2 if node2.prev != nill: node2.prev.next <- node2 if head = node: head <- node2" }, { "code": null, "e": 3226, "s": 3171, "text": "Stack is abstract data-type with following operations." }, { "code": null, "e": 3261, "s": 3226, "text": "Push(Key): adds key to collection." }, { "code": null, "e": 3301, "s": 3261, "text": "Top(): returns most recently-added key." }, { "code": null, "e": 3352, "s": 3301, "text": "Pop(): removes and returns most recently-added key" }, { "code": null, "e": 3385, "s": 3352, "text": "Empty(): are there any elements?" }, { "code": null, "e": 3524, "s": 3385, "text": "Stack, also know as LIFO queues, can be implemented with either an array or linked-list and has O(1) for Push, Pop, Top, Empty operations." }, { "code": null, "e": 3637, "s": 3524, "text": "Let say, we want to a checker for a text editor. We want to check the text input is balanced brackets following:" }, { "code": null, "e": 3647, "s": 3637, "text": "Balanced:" }, { "code": null, "e": 3658, "s": 3647, "text": "([]) [] ()" }, { "code": null, "e": 3673, "s": 3658, "text": "((([([])]))())" }, { "code": null, "e": 3685, "s": 3673, "text": "Unbalanced:" }, { "code": null, "e": 3692, "s": 3685, "text": "([]]()" }, { "code": null, "e": 3695, "s": 3692, "text": "][" }, { "code": null, "e": 3756, "s": 3695, "text": "With Stack data structure, we can solve this problem easily:" }, { "code": null, "e": 4103, "s": 3756, "text": "def is_balanced(str): Stack stack for char in str: if char in [ '(', '[' ]: stack.push(char) else: if stack.empty(): return False top <- stack.pop() if (top = '[' and char != ']') or (top = '(' and char != ')'): return False return stack.empty()" }, { "code": null, "e": 4162, "s": 4103, "text": "Queue is abstract data type with the following operations:" }, { "code": null, "e": 4200, "s": 4162, "text": "Enqueue(key): adds key to collection." }, { "code": null, "e": 4257, "s": 4200, "text": "Dequeue(): removes and returns least recently-added key." }, { "code": null, "e": 4290, "s": 4257, "text": "Empty(): are there any elements?" }, { "code": null, "e": 4466, "s": 4290, "text": "Queue, also know as FIFO(First In First Out), can be implemented with either a linked list (with tail pointer) or an array and has O(1) for Enqueue, Dequeue, Empty operations." }, { "code": null, "e": 4566, "s": 4466, "text": "See these visualizations: array-based stack, list-based stack, array-based queue, list-based queue." }, { "code": null, "e": 4732, "s": 4566, "text": "Tree has a root node and many other nodes, each node contains: key, children, parent(optional). For binary tree, a node contains: key, left, right, parent(optional)." }, { "code": null, "e": 4885, "s": 4732, "text": "This is an example of a binary tree, we have Les as root and many other nodes, each node has left and right like: Cathy(left), Sam(right) for root node." }, { "code": null, "e": 4936, "s": 4885, "text": "To calculate height of tree, we can use recursive:" }, { "code": null, "e": 5037, "s": 4936, "text": "def height(tree): if tree = nil: return 0 return 1 + Max(height(tree.left), height(tree.right))" }, { "code": null, "e": 5104, "s": 5037, "text": "We have 2 ways to visit the nodes of a tree in a particular order:" }, { "code": null, "e": 5189, "s": 5104, "text": "Depth-first: We completely traverse on sub-tree before exploring a sibling sub-tree." }, { "code": null, "e": 5331, "s": 5189, "text": "def post_order_traversal(tree): if tree = nil: return post_order_traversal(tree.left) post_order_traversal(tree.right) print(tree.key)" }, { "code": null, "e": 5418, "s": 5331, "text": "Breadth-first: We traverse all node at one level before progressing to the next level." }, { "code": null, "e": 5655, "s": 5418, "text": "def level_traversal(tree): if tree = nil: return Queue q q.Enqueue(tree) while not q.empty(): node <- q.dequeue() print(node) if node.left != nil: q.enqueue(node.left) if node.left != nil: q.enqueue(node.right)" }, { "code": null, "e": 5771, "s": 5655, "text": "In this problem you will implement a feature for a text editor to find errors in the usage of brackets in the code." }, { "code": null, "e": 5791, "s": 5771, "text": "Problem Description" }, { "code": null, "e": 6110, "s": 5791, "text": "Task. Your friend is making a text editor for programmers. He is currently working on a feature that will find errors in the usage of different types of brackets. Code can contain any brackets from the set []{}(), where the opening brackets are [,{, and ( and the closing brackets corresponding to them are ],}, and )." }, { "code": null, "e": 6742, "s": 6110, "text": "For convenience, the text editor should not only inform the user that there is an error in the usage of brackets, but also point to the exact place in the code with the problematic bracket. First priority is to find the first unmatched closing bracket which either doesn’t have an opening bracket before it, like ] in ](), or closes the wrong opening bracket, like } in ()[}. If there are no such mistakes, then it should find the first unmatched opening bracket without the corresponding closing bracket after it, like ( in {}([]. If there are no mistakes, text editor should inform the user that the usage of brackets is correct." }, { "code": null, "e": 7237, "s": 6742, "text": "Apart from the brackets, code can contain big and small latin letters, digits and punctuation marks. More formally, all brackets in the code should be divided into pairs of matching brackets, such that in each pair the opening bracket goes before the closing bracket, and for any two pairs of brackets either one of them is nested inside another one as in (foo[bar]) or they are separate as in f(a,b)-g[c]. The bracket [ corresponds to the bracket ], { corresponds to }, and ( corresponds to )." }, { "code": null, "e": 7386, "s": 7237, "text": "Input Format. Input contains one string S which consists of big and small latin letters, digits, punctuation marks and brackets from the set []{}()." }, { "code": null, "e": 7671, "s": 7386, "text": "Output Format. If the code in S uses brackets correctly, output “Success” (without the quotes). Otherwise, output the 1-based index of the first unmatched closing bracket, and if there are no unmatched closing brackets, output the 1-based index of the first unmatched opening bracket." }, { "code": null, "e": 7681, "s": 7671, "text": "Sample 1." }, { "code": null, "e": 7688, "s": 7681, "text": "Input:" }, { "code": null, "e": 7694, "s": 7688, "text": "{}[] " }, { "code": null, "e": 7702, "s": 7694, "text": "Output:" }, { "code": null, "e": 7710, "s": 7702, "text": "Success" }, { "code": null, "e": 7876, "s": 7710, "text": "Explanation: The brackets are used correctly: there are two pairs of brackets — first pair of { and }, and second pair of [ and ] — and these pairs do not intersect." }, { "code": null, "e": 7886, "s": 7876, "text": "Sample 2." }, { "code": null, "e": 7893, "s": 7886, "text": "Input:" }, { "code": null, "e": 7896, "s": 7893, "text": "{ " }, { "code": null, "e": 7904, "s": 7896, "text": "Output:" }, { "code": null, "e": 7907, "s": 7904, "text": "1 " }, { "code": null, "e": 8154, "s": 7907, "text": "Explanation: The code { doesn’t use brackets correctly, because brackets cannot be divided into pairs (there is just one bracket). There are no closing brackets, and the first unmatched opening bracket is {, and its position is 1, so we output 1." }, { "code": null, "e": 8164, "s": 8154, "text": "Sample 3." }, { "code": null, "e": 8171, "s": 8164, "text": "Input:" }, { "code": null, "e": 8176, "s": 8171, "text": "{[} " }, { "code": null, "e": 8184, "s": 8176, "text": "Output:" }, { "code": null, "e": 8187, "s": 8184, "text": "3 " }, { "code": null, "e": 8452, "s": 8187, "text": "Explanation: The bracket } is unmatched, because the last unmatched opening bracket before it is [ and not {. It is the first unmatched closing bracket, and our first priority is to output the first unmatched closing bracket, and its position is 3, so we output 3." }, { "code": null, "e": 8462, "s": 8452, "text": "Sample 3." }, { "code": null, "e": 8469, "s": 8462, "text": "Input:" }, { "code": null, "e": 8482, "s": 8469, "text": "foo(bar[i); " }, { "code": null, "e": 8490, "s": 8482, "text": "Output:" }, { "code": null, "e": 8494, "s": 8490, "text": "10 " }, { "code": null, "e": 8611, "s": 8494, "text": "Explanation: ) doesn’t match [, so ) is the first unmatched closing bracket, so we output its position, which is 10." }, { "code": null, "e": 8911, "s": 8611, "text": "To solve this problem, you can slightly modify the IsBalanced algorithm from the lectures to account not only for the brackets, but also for other characters in the code, and return not just whether the code uses brackets correctly, but also what is the first position where the code becomes broken." }, { "code": null, "e": 9083, "s": 8911, "text": "In the lectures, the IsBalanced pseudocode gave us the solution for brackets: “ () [] “. We only need to check “ {} “ and track position for each bracket we push to stack." }, { "code": null, "e": 10039, "s": 9083, "text": "Trees are used to manipulate hierarchical data such as hierarchy of categories of a retailer or the directory structure on your computer. They are also used in data analysis and machine learning both for hierarchical clustering and building complex predictive models, including some of the best-performing in practice algorithms like Gradient Boosting over Decision Trees and Random Forests. In the later modules of this course, we will introduce balanced binary search trees (BST) — a special kind of trees that allows to very efficiently store, manipulate and retrieve data. Balanced BSTs are thus used in databases for efficient storage and actually in virtually any non-trivial programs, typically via built-in data structures of the programming language at hand. In this problem, your goal is to get used to trees. You will need to read a description of a tree from the input, implement the tree data structure, store the tree and compute its height." }, { "code": null, "e": 10059, "s": 10039, "text": "Problem Description" }, { "code": null, "e": 10345, "s": 10059, "text": "Task. You are given a description of a rooted tree. Your task is to compute and output its height. Recall that the height of a (rooted) tree is the maximum depth of a node, or the maximum distance from a leaf to the root. You are given an arbitrary tree, not necessarily a binary tree." }, { "code": null, "e": 10710, "s": 10345, "text": "Input Format. The first line contains the number of nodes n. The second line contains n integer numbers from −1 to n − 1 — parents of nodes. If the i-th one of them (0 ≤ i ≤ n − 1) is −1, node i is the root, otherwise it’s 0-based index of the parent of i-th node. It is guaranteed that there is exactly one root. It is guaranteed that the input represents a tree." }, { "code": null, "e": 10756, "s": 10710, "text": "Output Format. Output the height of the tree." }, { "code": null, "e": 10766, "s": 10756, "text": "Sample 1." }, { "code": null, "e": 10773, "s": 10766, "text": "Input:" }, { "code": null, "e": 10787, "s": 10773, "text": "5 4 -1 4 1 1 " }, { "code": null, "e": 10795, "s": 10787, "text": "Output:" }, { "code": null, "e": 10797, "s": 10795, "text": "3" }, { "code": null, "e": 11147, "s": 10797, "text": "Explanation: The input means that there are 5 nodes with numbers from 0 to 4, node 0 is a child of node 4, node 1 is the root, node 2 is a child of node 4, node 3 is a child of node 1 and node 4 is a child of node 1. To see this, let us write numbers of nodes from 0 to 4 in one line and the numbers given in the input in the second line underneath:" }, { "code": null, "e": 11167, "s": 11147, "text": "0 1 2 3 44 -1 4 1 1" }, { "code": null, "e": 11430, "s": 11167, "text": "Now we can see that the node number 1 is the root, because −1 corresponds to it in the second line. Also, we know that the nodes number 3 and number 4 are children of the root node 1. Also, we know that the nodes number 0 and number 2 are children of the node 4." }, { "code": null, "e": 11531, "s": 11430, "text": "The height of this tree is 3, because the number of vertices on the path from root 1 to leaf 2 is 3." }, { "code": null, "e": 11541, "s": 11531, "text": "Sample 2." }, { "code": null, "e": 11548, "s": 11541, "text": "Input:" }, { "code": null, "e": 11562, "s": 11548, "text": "5 -1 0 4 0 3 " }, { "code": null, "e": 11570, "s": 11562, "text": "Output:" }, { "code": null, "e": 11573, "s": 11570, "text": "4 " }, { "code": null, "e": 11586, "s": 11573, "text": "Explanation:" }, { "code": null, "e": 11888, "s": 11586, "text": "The input means that there are 5 nodes with numbers from 0 to 4, node 0 is the root, node 1 is a child of node 0, node 2 is a child of node 4, node 3 is a child of node 0 and node 4 is a child of node 3. The height of this tree is 4, because the number of nodes on the path from root 0 to leaf 2 is 4." }, { "code": null, "e": 12242, "s": 11888, "text": "To solve this problem, change the height function described in the lectures with an implementation which will work for an arbitrary tree. Note that the tree can be very deep in this problem, so you should be careful to avoid stack overflow problems if you’re using recursion, and definitely test your solution on a tree with the maximum possible height." }, { "code": null, "e": 12536, "s": 12242, "text": "Suggestion: Take advantage of the fact that the labels for each tree node are integers in the range 0..n−1: you can store each node in an array whose index is the label of the node. By storing the nodes in an array, you have O(1) access to any node given its label. Create an array of n nodes:" }, { "code": null, "e": 12595, "s": 12536, "text": "allocate nodes[n] for i ← 0 to n − 1: nodes[i] =new Node" }, { "code": null, "e": 12625, "s": 12595, "text": "Then, read each parent index:" }, { "code": null, "e": 12784, "s": 12625, "text": "for child_index ← 0 to n − 1: read parent_index if parent_index == −1: root ← child_index else: nodes[parent_index].addChild(nodes[child_index])" }, { "code": null, "e": 13101, "s": 12784, "text": "Once you’ve built the tree, you’ll then need to compute its height. If you don’t use recursion, you needn’t worry about stack overflow problems. Without recursion, you’ll need some auxiliary data structure to keep track of the current state (in the breadth-first seach code in lecture, for example, we used a queue)." }, { "code": null, "e": 13269, "s": 13101, "text": "After we built the tree, we can use queue to calculate the height of the tree. To do that, we will use Breadth-First travel, for each level, we increase height 1 more." }, { "code": null, "e": 13360, "s": 13269, "text": "In this problem you will implement a program to simulate the processing of network packets" }, { "code": null, "e": 13380, "s": 13360, "text": "Problem Description" }, { "code": null, "e": 13942, "s": 13380, "text": "Task. You are given a series of incoming network packets, and your task is to simulate their processing. Packets arrive in some order. For each packet number i, you know the time when it arrived Ai and the time it takes the processor to process it Pi (both in milliseconds). There is only one processor, and it processes the incoming packets in the order of their arrival. If the processor started to process some packet, it doesn’t interrupt or stop until it finishes the processing of this packet, and the processing of packet i takes exactly Pi milliseconds." }, { "code": null, "e": 14927, "s": 13942, "text": "The computer processing the packets has a network buffer of fixed size S. When packets arrive, they are stored in the buffer before being processed. However, if the buffer is full when a packet arrives (there are S packets which have arrived before this packet, and the computer hasn’t finished processing any of them), it is dropped and won’t be processed at all. If several packets arrive at the same time, they are first all stored in the buffer (some of them may be dropped because of that — those which are described later in the input). The computer processes the packets in the order of their arrival, and it starts processing the next available packet from the buffer as soon as it finishes processing the previous one. If at some point the computer is not busy, and there are no packets in the buffer, the computer just waits for the next packet to arrive. Note that a packet leaves the buffer and frees the space in the buffer as soon as the computer finishes processing it." }, { "code": null, "e": 15447, "s": 14927, "text": "Input Format. The first line of the input contains the size S of the buffer and the number n of incoming network packets. Each of the next n lines contains two numbers. i-th line contains the time of arrival Ai and the processing time Pi (both in milliseconds) of the i-th packet. It is guaranteed that the sequence of arrival times is non-decreasing (however, it can contain the exact same times of arrival in milliseconds — in this case the packet which is earlier in the input is considered to have arrived earlier)." }, { "code": null, "e": 15694, "s": 15447, "text": "Output Format. For each packet output either the moment of time (in milliseconds) when the processor began processing it or −1 if the packet was dropped (output the answers for the packets in the same order as the packets are given in the input)." }, { "code": null, "e": 15704, "s": 15694, "text": "Sample 1." }, { "code": null, "e": 15711, "s": 15704, "text": "Input:" }, { "code": null, "e": 15720, "s": 15711, "text": "1 1 0 0 " }, { "code": null, "e": 15728, "s": 15720, "text": "Output:" }, { "code": null, "e": 15731, "s": 15728, "text": "0 " }, { "code": null, "e": 15827, "s": 15731, "text": "Explanation: The only packet arrived at time 0, and computer started processing it immediately." }, { "code": null, "e": 15837, "s": 15827, "text": "Sample 3." }, { "code": null, "e": 15844, "s": 15837, "text": "Input:" }, { "code": null, "e": 15857, "s": 15844, "text": "1 2 0 1 0 1 " }, { "code": null, "e": 15865, "s": 15857, "text": "Output:" }, { "code": null, "e": 15871, "s": 15865, "text": "0 -1 " }, { "code": null, "e": 16159, "s": 15871, "text": "Explanation: The first packet arrived at time 0, the second packet also arrived at time 0, but was dropped, because the network buffer has size 1 and it was full with the first packet already. The first packet started processing at time 0, and the second packet was not processed at all." }, { "code": null, "e": 16169, "s": 16159, "text": "Sample 4." }, { "code": null, "e": 16176, "s": 16169, "text": "Input:" }, { "code": null, "e": 16188, "s": 16176, "text": "1 2 0 1 1 1" }, { "code": null, "e": 16196, "s": 16188, "text": "Output:" }, { "code": null, "e": 16200, "s": 16196, "text": "0 1" }, { "code": null, "e": 16409, "s": 16200, "text": "Explanation: The first packet arrived at time 0, the computer started processing it immediately and finished at time 1. The second packet arrived at time 1, and the computer started processing it immediately." }, { "code": null, "e": 16652, "s": 16409, "text": "To solve this problem, you can use a list or a queue (in this case the queue should allow accessing its last element, and such queue is usually called a deque). You can use the corresponding built-in data structure in your language of choice." }, { "code": null, "e": 17243, "s": 16652, "text": "One possible solution is to store in the list or queue finish_time the times when the computer will finish processing the packets which are currently stored in the network buffer, in increasing order. When a new packet arrives, you will first need to pop from the front of finish_time all the packets which are already processed by the time new packet arrives. Then you try to add the finish time for the new packet in finish_time. If the buffer is full (there are already S finish times in finish_time), the packet is dropped. Otherwise, its processing finish time is added to finish_time." }, { "code": null, "e": 17789, "s": 17243, "text": "If finish_time is empty when a new packet arrives, computer will start processing the new packet immediately as soon as it arrives. Otherwise, computer will start processing the new packet as soon as it finishes to process the last of the packets currently in finish_time (here is when you need to access the last element of finish_time to determine when the computer will start to process the new packet). You will also need to compute the processing finish time by adding Pi to the processing start time and push it to the back of finish_time." }, { "code": null, "e": 17932, "s": 17789, "text": "You need to remember to output the processing start time for each packet instead of the processing finish time which you store in finish_time." }, { "code": null, "e": 17989, "s": 17932, "text": "To solve this problem, we need to notice at some points:" }, { "code": null, "e": 18035, "s": 17989, "text": "We just need to keep track of finishing time." }, { "code": null, "e": 18188, "s": 18035, "text": "The current time processing is the time each request comes in. At each time request arrived, we should remove all request has done in finish_time queue." }, { "code": null, "e": 18240, "s": 18188, "text": "Always queue new request when finish_time is empty." }, { "code": null, "e": 18289, "s": 18240, "text": "See the chapter 10.2 [CLRS] — Array, Linked-List" }, { "code": null, "e": 18335, "s": 18289, "text": "See the chapter 10.1 [CLRS] — Stack and Queue" }, { "code": null, "e": 18370, "s": 18335, "text": "See the chapter 10.4 [CLRS] — Tree" } ]
How to count total number of documents in MongoDB Collection using Node.js ? - GeeksforGeeks
12 Feb, 2021 MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. Installing module: You can install mongodb module using the following command. node install mongodb Project Structure: Running the server on Local IP: Data is the directory where the MongoDB server is present. mongod --dbpath=data --bind_ip 127.0.0.1 MongoDB Database: Database:GFG Collection:aayush Following is the sample data stored in your database for this example. Filename: index.js Java // Requiring moduleconst MongoClient = require("mongodb"); // Connection URLconst url = 'mongodb://localhost:27017/'; // Database nameconst databasename = "GFG"; MongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect.collection("aayush"); // Count the total documents collection.countDocuments().then((count_documents) => { console.log(count_documents); }).catch((err) => { console.log(err.Message); }) }).catch((err) => { // Printing the error message console.log(err.Message);})</div> Run index.js file using the following command: node index.js Output: mridulmanochagfg MongoDB-method Node.js-Misc Technical Scripter 2020 MongoDB Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB - sort() Method Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.writeFile() Method Node.js fs.readFile() Method
[ { "code": null, "e": 25889, "s": 25861, "text": "\n12 Feb, 2021" }, { "code": null, "e": 26185, "s": 25889, "text": "MongoDB, the most popular NoSQL database, we can count the number of documents in MongoDB Collection using the MongoDB collection.countDocuments() function. The mongodb module is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. " }, { "code": null, "e": 26264, "s": 26185, "text": "Installing module: You can install mongodb module using the following command." }, { "code": null, "e": 26285, "s": 26264, "text": "node install mongodb" }, { "code": null, "e": 26304, "s": 26285, "text": "Project Structure:" }, { "code": null, "e": 26395, "s": 26304, "text": "Running the server on Local IP: Data is the directory where the MongoDB server is present." }, { "code": null, "e": 26436, "s": 26395, "text": "mongod --dbpath=data --bind_ip 127.0.0.1" }, { "code": null, "e": 26454, "s": 26436, "text": "MongoDB Database:" }, { "code": null, "e": 26485, "s": 26454, "text": "Database:GFG\nCollection:aayush" }, { "code": null, "e": 26556, "s": 26485, "text": "Following is the sample data stored in your database for this example." }, { "code": null, "e": 26575, "s": 26556, "text": "Filename: index.js" }, { "code": null, "e": 26580, "s": 26575, "text": "Java" }, { "code": "// Requiring moduleconst MongoClient = require(\"mongodb\"); // Connection URLconst url = 'mongodb://localhost:27017/'; // Database nameconst databasename = \"GFG\"; MongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect.collection(\"aayush\"); // Count the total documents collection.countDocuments().then((count_documents) => { console.log(count_documents); }).catch((err) => { console.log(err.Message); }) }).catch((err) => { // Printing the error message console.log(err.Message);})</div>", "e": 27172, "s": 26580, "text": null }, { "code": null, "e": 27219, "s": 27172, "text": "Run index.js file using the following command:" }, { "code": null, "e": 27233, "s": 27219, "text": "node index.js" }, { "code": null, "e": 27241, "s": 27233, "text": "Output:" }, { "code": null, "e": 27258, "s": 27241, "text": "mridulmanochagfg" }, { "code": null, "e": 27273, "s": 27258, "text": "MongoDB-method" }, { "code": null, "e": 27286, "s": 27273, "text": "Node.js-Misc" }, { "code": null, "e": 27310, "s": 27286, "text": "Technical Scripter 2020" }, { "code": null, "e": 27318, "s": 27310, "text": "MongoDB" }, { "code": null, "e": 27326, "s": 27318, "text": "Node.js" }, { "code": null, "e": 27345, "s": 27326, "text": "Technical Scripter" }, { "code": null, "e": 27362, "s": 27345, "text": "Web Technologies" }, { "code": null, "e": 27460, "s": 27362, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27498, "s": 27460, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 27523, "s": 27498, "text": "MongoDB - limit() Method" }, { "code": null, "e": 27550, "s": 27523, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 27586, "s": 27550, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 27610, "s": 27586, "text": "MongoDB - sort() Method" }, { "code": null, "e": 27643, "s": 27610, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27691, "s": 27643, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27724, "s": 27691, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 27754, "s": 27724, "text": "Node.js fs.writeFile() Method" } ]
How I built a bot to beat T-Rex run! | by Rajat Keshri | Towards Data Science
This article will explain the step by step procedure of building your own bot from scratch, which would play T-Rex run game by Google indefinitely. T-Rex run game is a game which I am sure every human with a phone or a laptop with Google Chrome and no internet connection has played. For those of you who do not know, just turn off your internet connection on your phone or laptop and open any website using Google Chrome and you’ll be able to play T-Rex run! The basic objective of the game is to jump or duck and dodge the obstacles and keep your Dino alive. However, being humans we might get bored or might get distracted and probably loose the game. In order to beat this game to the fullest, we require someone with extreme concentration and someone who cannot get distracted with anything in this world, someone like a BOT! Here, I will teach you how to build simple bot which would play the T-Rex run game for you while you sit and watch it play peacefully (Although this defeats the whole purpose of any game, but it is just for fun). I will be building this bot in python using image processing libraries. To start with, you will be required to install Python 3.6 or above on your PC or laptop. Here are the list of libraries you’ll be required to install — pyautogui — This is a library which has functions to interact with the T-Rex run GUIPIL — PIL Library is used for taking screenshots of the screen and applying image processing on itTime — Used for giving different delays between jumps pyautogui — This is a library which has functions to interact with the T-Rex run GUI PIL — PIL Library is used for taking screenshots of the screen and applying image processing on it Time — Used for giving different delays between jumps These libraries can be installed using the command “pip install <libary name>”. Loads of documentation is available on w3schools on using pip and other commands and basics of working with python. Here is a link to it — https://www.w3schools.com/python/python_pip.asp We then load our prerequisites into our code by the following snippet — import pyautoguifrom time import sleepfrom PIL import ImageGrab,ImageOps Now, coming to the main part of the article. So the basic logic what we will be following here in building the bot is to mimic how a human plays the game. A human sees the obstacle and tries to time the jump of the Dino to avoid the obstacle. For our bot, we will be doing the same. Basically, here we take a screenshot of the T-Rex game screen and check the position of a tree or a bird obstacle in that image and if the obstacle is close enough to the Dino (defined using a threshold defined in the code), we ask the Dino to jump I am using this website which I found randomly which is the same T-Rex game, but on the internet — http://www.trex-game.skipser.com/. The first step is to take the screen shot of the web page with the game and locate the the exact pixel values of the Dino. We find the top and bottom corner pixel values of the Dino. This can be done by importing the image into paint.net and finding the pixel values. Also, if you notice, the position of the Dino is constant and only the obstacles are moving towards it. Hence we take this approach of creating an action on the Dino based on its static position with respect to the obstacles moving forward towards it. The below figure shows how we can get the pixel positions of the Dino figure, using the rulers and the grid view. Usually the sum of all pixel values in an image adds upto a number, and if the image does not change, the sum always remains constant. We keep this in mind and ill explain why this is important in the next few paragraphs. Similarly, we take a screenshot of the game when a tree is present, a bird is present and replay button is present and note down its pixel locations. This is not much required as of now, but in the future can be helpful. There are 5 different objects in this game — Dino, tree 1, tree 2, bird and replay button if you crash. You can use the pixel location values which I have used for each of these characters. I have used a class definition hold onto these values for making it simple. This is how to looks — class coordinates(): replay=(353,388) tree1=(195,416) tree2=(245,433) bird=(155,379) dino=(170,391) The next step is to actually write a logic for this code. We create different functions for different processes or objectives. First we create a function which would capture every frame or take screen shot of every frame on the game in order to process it. Think it like how humans see the game while playing it, the bot also needs to see the game using screenshots. This is shown in the following snippet. def imagegrab(): box= (coordinates.dino[0]+20,coordinates.dino[1],coordinates.dino[0]+100, coordinates.dino[1]+30) image = ImageGrab.grab(box) grayimage = ImageOps.grayscale(image) a = array(grayimage.getcolors()) return a.sum() In the above function imagegrab(), we get the coordinates of the Dino and create a box around it. Basically the box is a rectangle with 4 pixel location values of each corner, with the Dino inside the box. The box has some open space on right side of the Dino. We then take a screen shot of the box and the box acts like our logic for creating a jump or duck action. The basic logic here is that if a tree or a bird comes inside the box, the Dino is asked to jump or duck respectively. But bots actually cannot see whats happening in the screenshot or precisely inside the box. Bots can only see and read pixel. Hence, here as hinted in the previous section, we calculate the sum of all pixels within the box. As the image of the Dino and the box is constant and Dino is not moving, the sum of pixels in the box always returns a constant. But if a tree or bird enters the box, the sum value actually increases or decreases based on the pixel values, and that is when the bot gets a hint to either jump or duck. The below image displace the screenshot or how the box would look. Once we have the image of the Dino and the box, we convert the box into gray scale to increase up our processing as color is not an important factor here as we are just bothered with calculating the sum of the pixel values in the box. The next function we write is the jump function, which is basically asks the bot to jump when a tree appears. Puautogui library is used to simulate keyboard controls which enables the bot to interact with the game. Similarly a duck function is written. You can read more about pyautogui here — https://pyautogui.readthedocs.io/en/latest/keyboard.html def jump(): pyautogui.keyDown('space') sleep(0.05) pyautogui.keyUp('space') sleep(0.05)def duck(): pyautogui.keyDown('down') sleep(0.05) pyautogui.keyUp('down') sleep(0.05) The next function we write is to restart the game. If by chance the bot fails (very low chance), it should automatically restart without human aid. We use the replay button coordinates and simulate a click on that location. Here is the code snippet for it. def restart(): pyautogui.click(coordinates.replay) Once done with all our functions, we are ready to write our main function and run it. The below snippet shows the main function. def main(): restart() while True: imagegrab() if(imagegrab()!=2646): jump() sleep(0.001)If __name__=="__main__": main() This is how the bot runs indefinitely and thus this is how we beat the T-Rex run game. This logic can be utilized in many different games too, that is the logic of using the summation of pixel values. We should always take into consideration that the bots only see pixels and nothing else. For future scope we can actually calculate and find the values of the locations of the tree and birds dynamically using OpenCV and other image processing techniques (which i am planning to cover in my next Blog). Thank you for your time, hope it was informative.
[ { "code": null, "e": 320, "s": 172, "text": "This article will explain the step by step procedure of building your own bot from scratch, which would play T-Rex run game by Google indefinitely." }, { "code": null, "e": 1003, "s": 320, "text": "T-Rex run game is a game which I am sure every human with a phone or a laptop with Google Chrome and no internet connection has played. For those of you who do not know, just turn off your internet connection on your phone or laptop and open any website using Google Chrome and you’ll be able to play T-Rex run! The basic objective of the game is to jump or duck and dodge the obstacles and keep your Dino alive. However, being humans we might get bored or might get distracted and probably loose the game. In order to beat this game to the fullest, we require someone with extreme concentration and someone who cannot get distracted with anything in this world, someone like a BOT!" }, { "code": null, "e": 1216, "s": 1003, "text": "Here, I will teach you how to build simple bot which would play the T-Rex run game for you while you sit and watch it play peacefully (Although this defeats the whole purpose of any game, but it is just for fun)." }, { "code": null, "e": 1440, "s": 1216, "text": "I will be building this bot in python using image processing libraries. To start with, you will be required to install Python 3.6 or above on your PC or laptop. Here are the list of libraries you’ll be required to install —" }, { "code": null, "e": 1676, "s": 1440, "text": "pyautogui — This is a library which has functions to interact with the T-Rex run GUIPIL — PIL Library is used for taking screenshots of the screen and applying image processing on itTime — Used for giving different delays between jumps" }, { "code": null, "e": 1761, "s": 1676, "text": "pyautogui — This is a library which has functions to interact with the T-Rex run GUI" }, { "code": null, "e": 1860, "s": 1761, "text": "PIL — PIL Library is used for taking screenshots of the screen and applying image processing on it" }, { "code": null, "e": 1914, "s": 1860, "text": "Time — Used for giving different delays between jumps" }, { "code": null, "e": 2181, "s": 1914, "text": "These libraries can be installed using the command “pip install <libary name>”. Loads of documentation is available on w3schools on using pip and other commands and basics of working with python. Here is a link to it — https://www.w3schools.com/python/python_pip.asp" }, { "code": null, "e": 2253, "s": 2181, "text": "We then load our prerequisites into our code by the following snippet —" }, { "code": null, "e": 2326, "s": 2253, "text": "import pyautoguifrom time import sleepfrom PIL import ImageGrab,ImageOps" }, { "code": null, "e": 2858, "s": 2326, "text": "Now, coming to the main part of the article. So the basic logic what we will be following here in building the bot is to mimic how a human plays the game. A human sees the obstacle and tries to time the jump of the Dino to avoid the obstacle. For our bot, we will be doing the same. Basically, here we take a screenshot of the T-Rex game screen and check the position of a tree or a bird obstacle in that image and if the obstacle is close enough to the Dino (defined using a threshold defined in the code), we ask the Dino to jump" }, { "code": null, "e": 2992, "s": 2858, "text": "I am using this website which I found randomly which is the same T-Rex game, but on the internet — http://www.trex-game.skipser.com/." }, { "code": null, "e": 3848, "s": 2992, "text": "The first step is to take the screen shot of the web page with the game and locate the the exact pixel values of the Dino. We find the top and bottom corner pixel values of the Dino. This can be done by importing the image into paint.net and finding the pixel values. Also, if you notice, the position of the Dino is constant and only the obstacles are moving towards it. Hence we take this approach of creating an action on the Dino based on its static position with respect to the obstacles moving forward towards it. The below figure shows how we can get the pixel positions of the Dino figure, using the rulers and the grid view. Usually the sum of all pixel values in an image adds upto a number, and if the image does not change, the sum always remains constant. We keep this in mind and ill explain why this is important in the next few paragraphs." }, { "code": null, "e": 4069, "s": 3848, "text": "Similarly, we take a screenshot of the game when a tree is present, a bird is present and replay button is present and note down its pixel locations. This is not much required as of now, but in the future can be helpful." }, { "code": null, "e": 4358, "s": 4069, "text": "There are 5 different objects in this game — Dino, tree 1, tree 2, bird and replay button if you crash. You can use the pixel location values which I have used for each of these characters. I have used a class definition hold onto these values for making it simple. This is how to looks —" }, { "code": null, "e": 4475, "s": 4358, "text": "class coordinates(): replay=(353,388) tree1=(195,416) tree2=(245,433) bird=(155,379) dino=(170,391)" }, { "code": null, "e": 4602, "s": 4475, "text": "The next step is to actually write a logic for this code. We create different functions for different processes or objectives." }, { "code": null, "e": 4882, "s": 4602, "text": "First we create a function which would capture every frame or take screen shot of every frame on the game in order to process it. Think it like how humans see the game while playing it, the bot also needs to see the game using screenshots. This is shown in the following snippet." }, { "code": null, "e": 5131, "s": 4882, "text": "def imagegrab(): box= (coordinates.dino[0]+20,coordinates.dino[1],coordinates.dino[0]+100, coordinates.dino[1]+30) image = ImageGrab.grab(box) grayimage = ImageOps.grayscale(image) a = array(grayimage.getcolors()) return a.sum()" }, { "code": null, "e": 5617, "s": 5131, "text": "In the above function imagegrab(), we get the coordinates of the Dino and create a box around it. Basically the box is a rectangle with 4 pixel location values of each corner, with the Dino inside the box. The box has some open space on right side of the Dino. We then take a screen shot of the box and the box acts like our logic for creating a jump or duck action. The basic logic here is that if a tree or a bird comes inside the box, the Dino is asked to jump or duck respectively." }, { "code": null, "e": 6209, "s": 5617, "text": "But bots actually cannot see whats happening in the screenshot or precisely inside the box. Bots can only see and read pixel. Hence, here as hinted in the previous section, we calculate the sum of all pixels within the box. As the image of the Dino and the box is constant and Dino is not moving, the sum of pixels in the box always returns a constant. But if a tree or bird enters the box, the sum value actually increases or decreases based on the pixel values, and that is when the bot gets a hint to either jump or duck. The below image displace the screenshot or how the box would look." }, { "code": null, "e": 6444, "s": 6209, "text": "Once we have the image of the Dino and the box, we convert the box into gray scale to increase up our processing as color is not an important factor here as we are just bothered with calculating the sum of the pixel values in the box." }, { "code": null, "e": 6659, "s": 6444, "text": "The next function we write is the jump function, which is basically asks the bot to jump when a tree appears. Puautogui library is used to simulate keyboard controls which enables the bot to interact with the game." }, { "code": null, "e": 6795, "s": 6659, "text": "Similarly a duck function is written. You can read more about pyautogui here — https://pyautogui.readthedocs.io/en/latest/keyboard.html" }, { "code": null, "e": 6992, "s": 6795, "text": "def jump(): pyautogui.keyDown('space') sleep(0.05) pyautogui.keyUp('space') sleep(0.05)def duck(): pyautogui.keyDown('down') sleep(0.05) pyautogui.keyUp('down') sleep(0.05)" }, { "code": null, "e": 7249, "s": 6992, "text": "The next function we write is to restart the game. If by chance the bot fails (very low chance), it should automatically restart without human aid. We use the replay button coordinates and simulate a click on that location. Here is the code snippet for it." }, { "code": null, "e": 7303, "s": 7249, "text": "def restart(): pyautogui.click(coordinates.replay)" }, { "code": null, "e": 7432, "s": 7303, "text": "Once done with all our functions, we are ready to write our main function and run it. The below snippet shows the main function." }, { "code": null, "e": 7610, "s": 7432, "text": "def main(): restart() while True: imagegrab() if(imagegrab()!=2646): jump() sleep(0.001)If __name__==\"__main__\": main()" }, { "code": null, "e": 8113, "s": 7610, "text": "This is how the bot runs indefinitely and thus this is how we beat the T-Rex run game. This logic can be utilized in many different games too, that is the logic of using the summation of pixel values. We should always take into consideration that the bots only see pixels and nothing else. For future scope we can actually calculate and find the values of the locations of the tree and birds dynamically using OpenCV and other image processing techniques (which i am planning to cover in my next Blog)." } ]
Implementing Point Pillars in TensorFlow | by Anjul Tyagi | Towards Data Science
If you want to get started on 3D Object Detection and more specifically on Point Pillars, I have a series of posts written on it just for that purpose. Here’s the link. Also, going through the Point Pillars paper directly will be really helpful to understand this post better, however, it’s not a prerequisite. Github Repo for this tutorial: https://github.com/tyagi-iiitv/PointPillars. Thanks to Francesco Ferroni for the initial code. Defining Initial Configurations Building Point Pillars Network Loss functions Data Readers for Kitti Dataset Training Inference We define initial configurations that include the limits for x,y,z dimensions. These limits define the region of interest in which we will be predicting the bounding boxes. Since the range of LiDARs is generally very high, we focus on a smaller region in this space which is defined by these limits. Other configurations include the maximum number of Pillars, maximum points per pillar, etc. These configurations are generally used to transfer the point cloud from 3D coordinates to Pillar coordinates in the Point Pillars detection pipeline as discussed in the next section. For now, just remember that all the configurations are defined in this file. The overall architecture of Point Pillars contains three components: A pillar feature net, A Backbone 2D CNN, and a Detection Head. We will discuss these three components individually. pillars/input (Input Layer) (4,12000,100,7) refers to — Batch Size (4), Maximum Number of Pillars (12000), Maximum number of Points per Pillar (100), 7 dim vector: [x,y,z,intensity,Xc,Yc,Zc]. X,y,z are the 3D coordinates of a point inside a point cloud and its intensity as measured by the LiDAR device is stored inside “intensity”, Xc, Yc, Zc stores the distance of that point from the Pillar Center in each dimension. This input is now transformed from 7 dimensions to a 64-dimensional vector with features extracted using a CNN. pillars/indices (InputLayer) (4,12000,3) refers to — Batch Size, Maximum number of Pillars, and the center of each pillar, i.e. the x,y and z coordinates. This layer contains the center of each pillar, which is used to map the features learned for each pillar back to the x-y grid in pillars/scatter_nd (Lambda) layer. pillars/scatter_nd (Lambda) — Using the x,y coordinates from the above layer, the point cloud space is divided into (504 X 504) x-y grid with each grid cell containing the 64 features of the corresponding pillar. This is a practically simple layer with input being the pillar features encoded in an x-y grid, as described in the previous section. This grid is treated as an image and is transformed into different scales with features extracted at those scales and finally concatenated. We are trying to capture features from different scales of the point cloud and concatenate them into a single tensor. In this part, we are predicting the regression targets for the anchor boxes as described below. All of these predictions are for each grid cell in the x-y coordinates (252 X 252). The bounding boxes are not directly predicted in this case, but the initial anchor boxes are resized to generate the predicted bounding box. The initial anchor boxes are provided inside the config.py file. Occupancy — Whether the predicted label contains an element. 1 — Yes and No Otherwise. So we only need to check other predictions (loc, size, angle, heading, and clf) only when occupancy is 1. Loc — Contains the delta x,y,z for the corresponding anchor box. Size — Contains delta length, width, and height for the corresponding anchor box. Angle — Contains the delta yaw value. Heading — Contains if Angle is > 90 to check the heading angle of the object. Clf — Contains the classification id and the confidence score for each prediction. Note that the Detection head predicts 4 bounding boxes per grid cell, and each bounding box has the properties listed above. Once we have decided on the network architecture, we create the loss functions to complete the training process definitions. As you can see in the loss.py file, we are calculating the loss values for each of our regression targets and adding them with weights assigned to each error. So, the final loss value will be a weighted sum of each loss value. focal_weight*focal_loss + loc_weight*loc_loss + size_weight*size_loss + angle_weight*angle_loss + ... We have designed a class to read the files in the Kitti Dataset and extract the 3D bounding box dimensions from the label (txt) files. Every row in the labels file contain the following information: Type of object (Car, Truck, etc.)Truncated Float, 0 means truncated and 1 means non-truncatedOcclusion State, 0=Fully Visible, 1=Partly Occluded, 2=Largely Occluded, 3=UnknownAlpha Observation angle4 2D bounding box parameters (center, length, width)3D object dimensions (height, width, length)3D object location (x,y,z) in camera coordinatesYaw angle Type of object (Car, Truck, etc.) Truncated Float, 0 means truncated and 1 means non-truncated Occlusion State, 0=Fully Visible, 1=Partly Occluded, 2=Largely Occluded, 3=Unknown Alpha Observation angle 4 2D bounding box parameters (center, length, width) 3D object dimensions (height, width, length) 3D object location (x,y,z) in camera coordinates Yaw angle After defining loss functions, configurations, and data generators for each data point in the Kitti dataset, the SimpleDataGenerator in the processor.py file, generates the training examples. The main steps in this process are: Generate Pillars and Pillar Ids (DataProcessor.make_point_pillars inside processor.py file) Generate the regression targets (discussed above) from the label files and given anchor boxes in the config.py file. (DataProcessor.make_ground_truth inside processor.py file) The helper functions for these two tasks are provided inside the src/point_pillars.cpp file which is included with the current python code using Pybind. createPillars (src/point_pillars.cpp) — Generates the maximum number of pillars and assign pillar centers to each pillar. Use zero-padding if the number of points inside a pillar is less than the maximum points and random sampling otherwise. Each pillar will have 100 points and 7 values for each point (x, y, z, intensity, Xc, Yc, Zc). We start from the (0,0) LiDAR coordinates and expand radially in the field of view until we reach a maximum number of pillars. createPillarsTarget (src/point_pillars.cpp) — Generates the regression targets which can be used to calculate the loss values later. For each 3D bounding box given inside the labels file, it is compared to the anchor boxes. First, a search radius is created around the original bounding box based on object dimensions (red circle on the grid below). Then for each grid cell inside that radius, the anchor boxes are placed and IoU is calculated between each anchor box and the original bounding box. If the IoU value is above a certain threshold, then the targets (delta - x, y, z, length, width height, yaw, etc.) are stored for that bounding box. Otherwise, if no anchor passed the threshold, the best anchor based on IoU scores is chosen for that grid cell and is stored. These values are then used to calculate the loss values as described above. The last part of this codebase is the point_pillars_prediction.py file used for inferencing. After we have trained the network based on the loss functions described before, during the inference stage, the output of the network is the regression targets, occupancy index, and the classification confidence value for each prediction. You can verify that for each grid cell, the network outputs 4 bounding boxes with their respective parameters. We can remove most of the predicted boxes based on the occupancy index since we only want the boxes with occupancy 1, which means that the network has actually predicted a bounding box on that grid cell. Still, there can be many bounding boxes that are predicted by the network for the same object. To filter these, we can use Non-Maximum Suppression and come up with final bounding box predictions. Non-Maximum Suppression ranks the bounding boxes on the basis of IoU and their classification confidence values and selects the one with the best value as the final bounding box. Refer to this post to read more on Non-Maximum Suppression. This post covered the details of Point Pillars implementation on Tensorflow. All the code details including configuration files, model implementation, data generators, training, and inference are explained with code examples. The code is available in this Github repo and can be used to experiment with the details given in this article. As the next steps, we are working on generating inference results on the Kitti data which will be posted on the Github repo. If you are interested in contributing to this project, please check out the issues on the GitHub repo.
[ { "code": null, "e": 483, "s": 172, "text": "If you want to get started on 3D Object Detection and more specifically on Point Pillars, I have a series of posts written on it just for that purpose. Here’s the link. Also, going through the Point Pillars paper directly will be really helpful to understand this post better, however, it’s not a prerequisite." }, { "code": null, "e": 609, "s": 483, "text": "Github Repo for this tutorial: https://github.com/tyagi-iiitv/PointPillars. Thanks to Francesco Ferroni for the initial code." }, { "code": null, "e": 641, "s": 609, "text": "Defining Initial Configurations" }, { "code": null, "e": 672, "s": 641, "text": "Building Point Pillars Network" }, { "code": null, "e": 687, "s": 672, "text": "Loss functions" }, { "code": null, "e": 718, "s": 687, "text": "Data Readers for Kitti Dataset" }, { "code": null, "e": 727, "s": 718, "text": "Training" }, { "code": null, "e": 737, "s": 727, "text": "Inference" }, { "code": null, "e": 1129, "s": 737, "text": "We define initial configurations that include the limits for x,y,z dimensions. These limits define the region of interest in which we will be predicting the bounding boxes. Since the range of LiDARs is generally very high, we focus on a smaller region in this space which is defined by these limits. Other configurations include the maximum number of Pillars, maximum points per pillar, etc." }, { "code": null, "e": 1390, "s": 1129, "text": "These configurations are generally used to transfer the point cloud from 3D coordinates to Pillar coordinates in the Point Pillars detection pipeline as discussed in the next section. For now, just remember that all the configurations are defined in this file." }, { "code": null, "e": 1575, "s": 1390, "text": "The overall architecture of Point Pillars contains three components: A pillar feature net, A Backbone 2D CNN, and a Detection Head. We will discuss these three components individually." }, { "code": null, "e": 1995, "s": 1575, "text": "pillars/input (Input Layer) (4,12000,100,7) refers to — Batch Size (4), Maximum Number of Pillars (12000), Maximum number of Points per Pillar (100), 7 dim vector: [x,y,z,intensity,Xc,Yc,Zc]. X,y,z are the 3D coordinates of a point inside a point cloud and its intensity as measured by the LiDAR device is stored inside “intensity”, Xc, Yc, Zc stores the distance of that point from the Pillar Center in each dimension." }, { "code": null, "e": 2107, "s": 1995, "text": "This input is now transformed from 7 dimensions to a 64-dimensional vector with features extracted using a CNN." }, { "code": null, "e": 2426, "s": 2107, "text": "pillars/indices (InputLayer) (4,12000,3) refers to — Batch Size, Maximum number of Pillars, and the center of each pillar, i.e. the x,y and z coordinates. This layer contains the center of each pillar, which is used to map the features learned for each pillar back to the x-y grid in pillars/scatter_nd (Lambda) layer." }, { "code": null, "e": 2639, "s": 2426, "text": "pillars/scatter_nd (Lambda) — Using the x,y coordinates from the above layer, the point cloud space is divided into (504 X 504) x-y grid with each grid cell containing the 64 features of the corresponding pillar." }, { "code": null, "e": 3031, "s": 2639, "text": "This is a practically simple layer with input being the pillar features encoded in an x-y grid, as described in the previous section. This grid is treated as an image and is transformed into different scales with features extracted at those scales and finally concatenated. We are trying to capture features from different scales of the point cloud and concatenate them into a single tensor." }, { "code": null, "e": 3417, "s": 3031, "text": "In this part, we are predicting the regression targets for the anchor boxes as described below. All of these predictions are for each grid cell in the x-y coordinates (252 X 252). The bounding boxes are not directly predicted in this case, but the initial anchor boxes are resized to generate the predicted bounding box. The initial anchor boxes are provided inside the config.py file." }, { "code": null, "e": 3610, "s": 3417, "text": "Occupancy — Whether the predicted label contains an element. 1 — Yes and No Otherwise. So we only need to check other predictions (loc, size, angle, heading, and clf) only when occupancy is 1." }, { "code": null, "e": 3675, "s": 3610, "text": "Loc — Contains the delta x,y,z for the corresponding anchor box." }, { "code": null, "e": 3757, "s": 3675, "text": "Size — Contains delta length, width, and height for the corresponding anchor box." }, { "code": null, "e": 3795, "s": 3757, "text": "Angle — Contains the delta yaw value." }, { "code": null, "e": 3873, "s": 3795, "text": "Heading — Contains if Angle is > 90 to check the heading angle of the object." }, { "code": null, "e": 3956, "s": 3873, "text": "Clf — Contains the classification id and the confidence score for each prediction." }, { "code": null, "e": 4081, "s": 3956, "text": "Note that the Detection head predicts 4 bounding boxes per grid cell, and each bounding box has the properties listed above." }, { "code": null, "e": 4433, "s": 4081, "text": "Once we have decided on the network architecture, we create the loss functions to complete the training process definitions. As you can see in the loss.py file, we are calculating the loss values for each of our regression targets and adding them with weights assigned to each error. So, the final loss value will be a weighted sum of each loss value." }, { "code": null, "e": 4535, "s": 4433, "text": "focal_weight*focal_loss + loc_weight*loc_loss + size_weight*size_loss + angle_weight*angle_loss + ..." }, { "code": null, "e": 4734, "s": 4535, "text": "We have designed a class to read the files in the Kitti Dataset and extract the 3D bounding box dimensions from the label (txt) files. Every row in the labels file contain the following information:" }, { "code": null, "e": 5086, "s": 4734, "text": "Type of object (Car, Truck, etc.)Truncated Float, 0 means truncated and 1 means non-truncatedOcclusion State, 0=Fully Visible, 1=Partly Occluded, 2=Largely Occluded, 3=UnknownAlpha Observation angle4 2D bounding box parameters (center, length, width)3D object dimensions (height, width, length)3D object location (x,y,z) in camera coordinatesYaw angle" }, { "code": null, "e": 5120, "s": 5086, "text": "Type of object (Car, Truck, etc.)" }, { "code": null, "e": 5181, "s": 5120, "text": "Truncated Float, 0 means truncated and 1 means non-truncated" }, { "code": null, "e": 5264, "s": 5181, "text": "Occlusion State, 0=Fully Visible, 1=Partly Occluded, 2=Largely Occluded, 3=Unknown" }, { "code": null, "e": 5288, "s": 5264, "text": "Alpha Observation angle" }, { "code": null, "e": 5341, "s": 5288, "text": "4 2D bounding box parameters (center, length, width)" }, { "code": null, "e": 5386, "s": 5341, "text": "3D object dimensions (height, width, length)" }, { "code": null, "e": 5435, "s": 5386, "text": "3D object location (x,y,z) in camera coordinates" }, { "code": null, "e": 5445, "s": 5435, "text": "Yaw angle" }, { "code": null, "e": 5673, "s": 5445, "text": "After defining loss functions, configurations, and data generators for each data point in the Kitti dataset, the SimpleDataGenerator in the processor.py file, generates the training examples. The main steps in this process are:" }, { "code": null, "e": 5765, "s": 5673, "text": "Generate Pillars and Pillar Ids (DataProcessor.make_point_pillars inside processor.py file)" }, { "code": null, "e": 5941, "s": 5765, "text": "Generate the regression targets (discussed above) from the label files and given anchor boxes in the config.py file. (DataProcessor.make_ground_truth inside processor.py file)" }, { "code": null, "e": 6094, "s": 5941, "text": "The helper functions for these two tasks are provided inside the src/point_pillars.cpp file which is included with the current python code using Pybind." }, { "code": null, "e": 6558, "s": 6094, "text": "createPillars (src/point_pillars.cpp) — Generates the maximum number of pillars and assign pillar centers to each pillar. Use zero-padding if the number of points inside a pillar is less than the maximum points and random sampling otherwise. Each pillar will have 100 points and 7 values for each point (x, y, z, intensity, Xc, Yc, Zc). We start from the (0,0) LiDAR coordinates and expand radially in the field of view until we reach a maximum number of pillars." }, { "code": null, "e": 7057, "s": 6558, "text": "createPillarsTarget (src/point_pillars.cpp) — Generates the regression targets which can be used to calculate the loss values later. For each 3D bounding box given inside the labels file, it is compared to the anchor boxes. First, a search radius is created around the original bounding box based on object dimensions (red circle on the grid below). Then for each grid cell inside that radius, the anchor boxes are placed and IoU is calculated between each anchor box and the original bounding box." }, { "code": null, "e": 7408, "s": 7057, "text": "If the IoU value is above a certain threshold, then the targets (delta - x, y, z, length, width height, yaw, etc.) are stored for that bounding box. Otherwise, if no anchor passed the threshold, the best anchor based on IoU scores is chosen for that grid cell and is stored. These values are then used to calculate the loss values as described above." }, { "code": null, "e": 7851, "s": 7408, "text": "The last part of this codebase is the point_pillars_prediction.py file used for inferencing. After we have trained the network based on the loss functions described before, during the inference stage, the output of the network is the regression targets, occupancy index, and the classification confidence value for each prediction. You can verify that for each grid cell, the network outputs 4 bounding boxes with their respective parameters." }, { "code": null, "e": 8490, "s": 7851, "text": "We can remove most of the predicted boxes based on the occupancy index since we only want the boxes with occupancy 1, which means that the network has actually predicted a bounding box on that grid cell. Still, there can be many bounding boxes that are predicted by the network for the same object. To filter these, we can use Non-Maximum Suppression and come up with final bounding box predictions. Non-Maximum Suppression ranks the bounding boxes on the basis of IoU and their classification confidence values and selects the one with the best value as the final bounding box. Refer to this post to read more on Non-Maximum Suppression." }, { "code": null, "e": 8953, "s": 8490, "text": "This post covered the details of Point Pillars implementation on Tensorflow. All the code details including configuration files, model implementation, data generators, training, and inference are explained with code examples. The code is available in this Github repo and can be used to experiment with the details given in this article. As the next steps, we are working on generating inference results on the Kitti data which will be posted on the Github repo." } ]
The globals(), locals() and reload() Functions in Python
The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called. If locals() is called from within a function, it will return all the names that can be accessed locally from that function. If globals() is called from within a function, it will return all the names that can be accessed globally from that function. The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function. When the module is imported into a script, the code in the top-level portion of a module is executed only once. Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this − reload(module_name) Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following − reload(hello)
[ { "code": null, "e": 1220, "s": 1062, "text": "The globals() and locals() functions can be used to return the names in the global and local namespaces depending on the location from where they are called." }, { "code": null, "e": 1344, "s": 1220, "text": "If locals() is called from within a function, it will return all the names that can be accessed locally from that function." }, { "code": null, "e": 1470, "s": 1344, "text": "If globals() is called from within a function, it will return all the names that can be accessed globally from that function." }, { "code": null, "e": 1586, "s": 1470, "text": "The return type of both these functions is dictionary. Therefore, names can be extracted using the keys() function." }, { "code": null, "e": 1698, "s": 1586, "text": "When the module is imported into a script, the code in the top-level portion of a module is executed only once." }, { "code": null, "e": 1913, "s": 1698, "text": "Therefore, if you want to reexecute the top-level code in a module, you can use the reload() function. The reload() function imports a previously imported module again. The syntax of the reload() function is this −" }, { "code": null, "e": 1933, "s": 1913, "text": "reload(module_name)" }, { "code": null, "e": 2099, "s": 1933, "text": "Here, module_name is the name of the module you want to reload and not the string containing the module name. For example, to reload hello module, do the following −" }, { "code": null, "e": 2114, "s": 2099, "text": "reload(hello)\n" } ]
How to map data into Components using ReactJS? - GeeksforGeeks
05 Jul, 2021 Map all individual custom pieces of data to the custom component. For example: Instead of writing custom components again and again with different props. I will make an array that contains all props and use the map() function to map the array element with a custom component in a single component call. A map is a data collection type where data is stored in the form of key-value pairs. The value stored in the map must be mapped to the key. The map is a JavaScript function that can be called on any array. With the map function, we map every element of the array to the custom components in a single line of code. That means there is no need to call components and their props as array elements again and again. Syntax: var array = [1,2,3,4,5] var PlusOne= array.map((e)=>{ return (e+1); }); // All array element value will increase by one. list.js: Contain an array with the user’s name and roll number in the form of key-value pairs. Javascript const Users=[ { name:"Deepak", rollNo:"123" }, { name:"Yash", rollNo:"124" }, { name:"Raj", rollNo:"125" },{ name:"Rohan", rollNo:"126" }, { name:"Puneet", rollNo:"127" }, { name:"Vivek", rollNo:"128" }, { name:"Aman", rollNo:"129" },]export default Users; Info.js: Username and roll number as props in the Info component. Javascript import React from 'react'; function Info (props){ return ( <div style={{border:'1px solid black', margin:'10px',width:'20%'}}> <p> {props.name} </p> <p> {props.rollNo}</p> </div> )}export default Info; Example: Mapping data from list.js file to custom Info component using the map function. App.js: Import Users array and Info component in the App.js file. Use the map function to map each element of User arrays to the Info component. Javascript import React from 'react';import './App.css';import Users from './list';import Info from './Info'; function App() { return ( <div style={{margin:'40px'}} > <h1 style={{color:'green'}}> Geeks For Geeks </h1> <p> Mapping Data to component in React js. </p> {Users.map((e)=>{ return ( <Info name={e.name} rollNo={e.rollNo}/> );})} </div> );}export default App; Output : Example 2: Mapping data from list.js file to Info component without using the map function. App.js file: Javascript import React from 'react';import './App.css';import Users from './list';import Info from './Info'; function App() { return ( <div style={{margin:'40px'}} > <h1 style={{color:'green'}}> Geeks For Geeks </h1> <p> Mapping Data to component in React js. </p> <Info name={Users[0].name} rollNo={Users[0].rollNo}/> <Info name={Users[1].name} rollNo={Users[1].rollNo}/> <Info name={Users[2].name} rollNo={Users[2].rollNo}/> <Info name={Users[3].name} rollNo={Users[3].rollNo}/> <Info name={Users[4].name} rollNo={Users[4].rollNo}/> <Info name={Users[5].name} rollNo={Users[5].rollNo}/> <Info name={Users[6].name} rollNo={Users[6].rollNo}/> </div> );}export default App; Output: From both the above example, we get the same output but one can observe by using the map function in the App.js file, mapping array data to component becomes more easy and less code is needed. simranarora5sos Picked react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Express.js express.Router() Function Top 10 Angular Libraries For Web Developers Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Set the value of an input field in JavaScript How to Insert Form Data into Database using PHP ? Client-Server Model How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 23873, "s": 23845, "text": "\n05 Jul, 2021" }, { "code": null, "e": 23940, "s": 23873, "text": "Map all individual custom pieces of data to the custom component. " }, { "code": null, "e": 24177, "s": 23940, "text": "For example: Instead of writing custom components again and again with different props. I will make an array that contains all props and use the map() function to map the array element with a custom component in a single component call." }, { "code": null, "e": 24589, "s": 24177, "text": "A map is a data collection type where data is stored in the form of key-value pairs. The value stored in the map must be mapped to the key. The map is a JavaScript function that can be called on any array. With the map function, we map every element of the array to the custom components in a single line of code. That means there is no need to call components and their props as array elements again and again." }, { "code": null, "e": 24597, "s": 24589, "text": "Syntax:" }, { "code": null, "e": 24726, "s": 24597, "text": "var array = [1,2,3,4,5]\nvar PlusOne= array.map((e)=>{\n return (e+1);\n });\n // All array element value will increase by one. " }, { "code": null, "e": 24821, "s": 24726, "text": "list.js: Contain an array with the user’s name and roll number in the form of key-value pairs." }, { "code": null, "e": 24832, "s": 24821, "text": "Javascript" }, { "code": "const Users=[ { name:\"Deepak\", rollNo:\"123\" }, { name:\"Yash\", rollNo:\"124\" }, { name:\"Raj\", rollNo:\"125\" },{ name:\"Rohan\", rollNo:\"126\" }, { name:\"Puneet\", rollNo:\"127\" }, { name:\"Vivek\", rollNo:\"128\" }, { name:\"Aman\", rollNo:\"129\" },]export default Users;", "e": 25145, "s": 24832, "text": null }, { "code": null, "e": 25211, "s": 25145, "text": "Info.js: Username and roll number as props in the Info component." }, { "code": null, "e": 25222, "s": 25211, "text": "Javascript" }, { "code": "import React from 'react'; function Info (props){ return ( <div style={{border:'1px solid black', margin:'10px',width:'20%'}}> <p> {props.name} </p> <p> {props.rollNo}</p> </div> )}export default Info;", "e": 25466, "s": 25222, "text": null }, { "code": null, "e": 25555, "s": 25466, "text": "Example: Mapping data from list.js file to custom Info component using the map function." }, { "code": null, "e": 25701, "s": 25555, "text": "App.js: Import Users array and Info component in the App.js file. Use the map function to map each element of User arrays to the Info component. " }, { "code": null, "e": 25712, "s": 25701, "text": "Javascript" }, { "code": "import React from 'react';import './App.css';import Users from './list';import Info from './Info'; function App() { return ( <div style={{margin:'40px'}} > <h1 style={{color:'green'}}> Geeks For Geeks </h1> <p> Mapping Data to component in React js. </p> {Users.map((e)=>{ return ( <Info name={e.name} rollNo={e.rollNo}/> );})} </div> );}export default App;", "e": 26111, "s": 25712, "text": null }, { "code": null, "e": 26121, "s": 26111, "text": "Output : " }, { "code": null, "e": 26213, "s": 26121, "text": "Example 2: Mapping data from list.js file to Info component without using the map function." }, { "code": null, "e": 26227, "s": 26213, "text": "App.js file: " }, { "code": null, "e": 26238, "s": 26227, "text": "Javascript" }, { "code": "import React from 'react';import './App.css';import Users from './list';import Info from './Info'; function App() { return ( <div style={{margin:'40px'}} > <h1 style={{color:'green'}}> Geeks For Geeks </h1> <p> Mapping Data to component in React js. </p> <Info name={Users[0].name} rollNo={Users[0].rollNo}/> <Info name={Users[1].name} rollNo={Users[1].rollNo}/> <Info name={Users[2].name} rollNo={Users[2].rollNo}/> <Info name={Users[3].name} rollNo={Users[3].rollNo}/> <Info name={Users[4].name} rollNo={Users[4].rollNo}/> <Info name={Users[5].name} rollNo={Users[5].rollNo}/> <Info name={Users[6].name} rollNo={Users[6].rollNo}/> </div> );}export default App;", "e": 26966, "s": 26238, "text": null }, { "code": null, "e": 26975, "s": 26966, "text": "Output: " }, { "code": null, "e": 27168, "s": 26975, "text": "From both the above example, we get the same output but one can observe by using the map function in the App.js file, mapping array data to component becomes more easy and less code is needed." }, { "code": null, "e": 27184, "s": 27168, "text": "simranarora5sos" }, { "code": null, "e": 27191, "s": 27184, "text": "Picked" }, { "code": null, "e": 27200, "s": 27191, "text": "react-js" }, { "code": null, "e": 27217, "s": 27200, "text": "Web Technologies" }, { "code": null, "e": 27315, "s": 27217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27324, "s": 27315, "text": "Comments" }, { "code": null, "e": 27337, "s": 27324, "text": "Old Comments" }, { "code": null, "e": 27374, "s": 27337, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27418, "s": 27374, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 27463, "s": 27418, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27523, "s": 27463, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27569, "s": 27523, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 27619, "s": 27569, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27639, "s": 27619, "text": "Client-Server Model" }, { "code": null, "e": 27682, "s": 27639, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27754, "s": 27682, "text": "Differences between Functional Components and Class Components in React" } ]
HTML5 Canvas - Drawing Bezier Curves
We need the following methods to draw Bezier curves on the canvas − beginPath() This method resets the current path. moveTo(x, y) This method creates a new subpath with the given point. closePath() This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath. fill() This method fills the subpaths with the current fill style. stroke() This method strokes the subpaths with the current stroke style. bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) This method adds the given point to the current path, connected to the previous one by a cubic Bezier curve with the given control points. The x and y parameters in bezierCurveTo() method are the coordinates of the end point. cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the coordinates of the second control point. Following is a simple example which makes use of above mentioned methods to draw a Bezier curves. <!DOCTYPE HTML> <html> <head> <style> #test { width: 100px; height:100px; margin: 0px auto; } </style> <script type = "text/javascript"> function drawShape() { // get the canvas element using the DOM var canvas = document.getElementById('mycanvas'); // Make sure we don't execute when canvas isn't supported if (canvas.getContext) { // use getContext to use the canvas for drawing var ctx = canvas.getContext('2d'); ctx.beginPath(); ctx.moveTo(75,40); ctx.bezierCurveTo(75,37,70,25,50,25); ctx.bezierCurveTo(20,25,20,62.5,20,62.5); ctx.bezierCurveTo(20,80,40,102,75,120); ctx.bezierCurveTo(110,102,130,80,130,62.5); ctx.bezierCurveTo(130,62.5,130,25,100,25); ctx.bezierCurveTo(85,25,75,37,75,40); ctx.fill(); } else { alert('You need Safari or Firefox 1.5+ to see this demo.'); } } </script> </head> <body id = "test" onload = "drawShape();"> <canvas id = "mycanvas"></canvas> </body> </html> The above example would draw the following shape − 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2676, "s": 2608, "text": "We need the following methods to draw Bezier curves on the canvas −" }, { "code": null, "e": 2688, "s": 2676, "text": "beginPath()" }, { "code": null, "e": 2725, "s": 2688, "text": "This method resets the current path." }, { "code": null, "e": 2738, "s": 2725, "text": "moveTo(x, y)" }, { "code": null, "e": 2794, "s": 2738, "text": "This method creates a new subpath with the given point." }, { "code": null, "e": 2806, "s": 2794, "text": "closePath()" }, { "code": null, "e": 2952, "s": 2806, "text": "This method marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath." }, { "code": null, "e": 2959, "s": 2952, "text": "fill()" }, { "code": null, "e": 3019, "s": 2959, "text": "This method fills the subpaths with the current fill style." }, { "code": null, "e": 3028, "s": 3019, "text": "stroke()" }, { "code": null, "e": 3092, "s": 3028, "text": "This method strokes the subpaths with the current stroke style." }, { "code": null, "e": 3136, "s": 3092, "text": "bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)" }, { "code": null, "e": 3275, "s": 3136, "text": "This method adds the given point to the current path, connected to the previous one by a cubic Bezier curve with the given control points." }, { "code": null, "e": 3491, "s": 3275, "text": "The x and y parameters in bezierCurveTo() method are the coordinates of the end point. cp1x and cp1y are the coordinates of the first control point, and cp2x and cp2y are the coordinates of the second control point." }, { "code": null, "e": 3589, "s": 3491, "text": "Following is a simple example which makes use of above mentioned methods to draw a Bezier curves." }, { "code": null, "e": 4990, "s": 3589, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <style>\n #test {\n width: 100px;\n height:100px;\n margin: 0px auto;\n }\n </style>\n \n <script type = \"text/javascript\">\n function drawShape() {\n \n // get the canvas element using the DOM\n var canvas = document.getElementById('mycanvas');\n \n // Make sure we don't execute when canvas isn't supported\n if (canvas.getContext) {\n \n // use getContext to use the canvas for drawing\n var ctx = canvas.getContext('2d');\n \n ctx.beginPath();\n ctx.moveTo(75,40);\n \n ctx.bezierCurveTo(75,37,70,25,50,25);\n ctx.bezierCurveTo(20,25,20,62.5,20,62.5);\n \n ctx.bezierCurveTo(20,80,40,102,75,120);\n ctx.bezierCurveTo(110,102,130,80,130,62.5);\n \n ctx.bezierCurveTo(130,62.5,130,25,100,25);\n ctx.bezierCurveTo(85,25,75,37,75,40);\n \n ctx.fill();\n } else {\n alert('You need Safari or Firefox 1.5+ to see this demo.');\n }\n }\n </script>\n </head>\n \n <body id = \"test\" onload = \"drawShape();\">\n <canvas id = \"mycanvas\"></canvas>\n </body>\n \n</html>" }, { "code": null, "e": 5041, "s": 4990, "text": "The above example would draw the following shape −" }, { "code": null, "e": 5074, "s": 5041, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 5088, "s": 5074, "text": " Anadi Sharma" }, { "code": null, "e": 5123, "s": 5088, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5137, "s": 5123, "text": " Anadi Sharma" }, { "code": null, "e": 5172, "s": 5137, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5189, "s": 5172, "text": " Frahaan Hussain" }, { "code": null, "e": 5224, "s": 5189, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5255, "s": 5224, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5288, "s": 5255, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 5319, "s": 5288, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5354, "s": 5319, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 5385, "s": 5354, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 5392, "s": 5385, "text": " Print" }, { "code": null, "e": 5403, "s": 5392, "text": " Add Notes" } ]
Java Guava | Bytes.toArray() method with Examples - GeeksforGeeks
31 Jan, 2019 The toArray() method of Bytes Class in the Guava library is used to convert the byte values, passed as the parameter to this method, into a Byte Array. These byte values are passed as a Collection to this method. This method returns a Byte array. Syntax: public static byte[] toArray(Collection<? extends Number> collection) Parameters: This method accepts a mandatory parameter collection which is the collection of byte values to be converted in to a Byte array. Return Value: This method returns a byte array containing the same values as a collection, in the same order. Exceptions: This method throws NullPointerException if the passed collection or any of its elements is null. Below programs illustrate the use of toArray() method: Example 1: // Java code to show implementation of// Guava's Bytes.toArray() method import com.google.common.primitives.Bytes;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a List of Bytes List<Byte> myList = Arrays.asList((byte)1, (byte)2, (byte)3, (byte)4, (byte)5); // Using Bytes.toArray() method to convert // a List or Set of Byte to an array // of Byte byte[] arr = Bytes.toArray(myList); // Displaying an array containing each // value of collection, // converted to a byte value System.out.println(Arrays.toString(arr)); }} [1, 2, 3, 4, 5] Example 2: // Java code to show implementation of// Guava's Bytes.toArray() method import com.google.common.primitives.Bytes;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { try { // Creating a List of Bytes List<Byte> myList = Arrays.asList((byte)2, (byte)4, null); // Using Bytes.toArray() method // to convert a List or Set of Byte // to an array of Byte. // This should raise "NullPointerException" // as the collection contains // "null" as an element byte[] arr = Bytes.toArray(myList); // Displaying an array containing each // value of collection, // converted to a byte value System.out.println(Arrays.toString(arr)); } catch (Exception e) { System.out.println(e); } }} java.lang.NullPointerException Reference: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Bytes.html#toArray(java.util.Collection) Guava-Bytes Guava-Functions Java-Functions java-guava Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Exceptions in Java Functional Interfaces in Java Stream In Java Different ways of Reading a text file in Java Internal Working of HashMap in Java Iterators in Java Java Programming Examples Comparator Interface in Java with Examples Strings in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n31 Jan, 2019" }, { "code": null, "e": 23804, "s": 23557, "text": "The toArray() method of Bytes Class in the Guava library is used to convert the byte values, passed as the parameter to this method, into a Byte Array. These byte values are passed as a Collection to this method. This method returns a Byte array." }, { "code": null, "e": 23812, "s": 23804, "text": "Syntax:" }, { "code": null, "e": 23882, "s": 23812, "text": "public static byte[] toArray(Collection<? extends Number> collection)" }, { "code": null, "e": 24022, "s": 23882, "text": "Parameters: This method accepts a mandatory parameter collection which is the collection of byte values to be converted in to a Byte array." }, { "code": null, "e": 24132, "s": 24022, "text": "Return Value: This method returns a byte array containing the same values as a collection, in the same order." }, { "code": null, "e": 24241, "s": 24132, "text": "Exceptions: This method throws NullPointerException if the passed collection or any of its elements is null." }, { "code": null, "e": 24296, "s": 24241, "text": "Below programs illustrate the use of toArray() method:" }, { "code": null, "e": 24307, "s": 24296, "text": "Example 1:" }, { "code": "// Java code to show implementation of// Guava's Bytes.toArray() method import com.google.common.primitives.Bytes;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { // Creating a List of Bytes List<Byte> myList = Arrays.asList((byte)1, (byte)2, (byte)3, (byte)4, (byte)5); // Using Bytes.toArray() method to convert // a List or Set of Byte to an array // of Byte byte[] arr = Bytes.toArray(myList); // Displaying an array containing each // value of collection, // converted to a byte value System.out.println(Arrays.toString(arr)); }}", "e": 25121, "s": 24307, "text": null }, { "code": null, "e": 25138, "s": 25121, "text": "[1, 2, 3, 4, 5]\n" }, { "code": null, "e": 25149, "s": 25138, "text": "Example 2:" }, { "code": "// Java code to show implementation of// Guava's Bytes.toArray() method import com.google.common.primitives.Bytes;import java.util.Arrays;import java.util.List; class GFG { // Driver's code public static void main(String[] args) { try { // Creating a List of Bytes List<Byte> myList = Arrays.asList((byte)2, (byte)4, null); // Using Bytes.toArray() method // to convert a List or Set of Byte // to an array of Byte. // This should raise \"NullPointerException\" // as the collection contains // \"null\" as an element byte[] arr = Bytes.toArray(myList); // Displaying an array containing each // value of collection, // converted to a byte value System.out.println(Arrays.toString(arr)); } catch (Exception e) { System.out.println(e); } }}", "e": 26168, "s": 25149, "text": null }, { "code": null, "e": 26200, "s": 26168, "text": "java.lang.NullPointerException\n" }, { "code": null, "e": 26335, "s": 26200, "text": "Reference: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/primitives/Bytes.html#toArray(java.util.Collection)" }, { "code": null, "e": 26347, "s": 26335, "text": "Guava-Bytes" }, { "code": null, "e": 26363, "s": 26347, "text": "Guava-Functions" }, { "code": null, "e": 26378, "s": 26363, "text": "Java-Functions" }, { "code": null, "e": 26389, "s": 26378, "text": "java-guava" }, { "code": null, "e": 26394, "s": 26389, "text": "Java" }, { "code": null, "e": 26399, "s": 26394, "text": "Java" }, { "code": null, "e": 26497, "s": 26399, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26506, "s": 26497, "text": "Comments" }, { "code": null, "e": 26519, "s": 26506, "text": "Old Comments" }, { "code": null, "e": 26540, "s": 26519, "text": "Constructors in Java" }, { "code": null, "e": 26559, "s": 26540, "text": "Exceptions in Java" }, { "code": null, "e": 26589, "s": 26559, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26604, "s": 26589, "text": "Stream In Java" }, { "code": null, "e": 26650, "s": 26604, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26686, "s": 26650, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 26704, "s": 26686, "text": "Iterators in Java" }, { "code": null, "e": 26730, "s": 26704, "text": "Java Programming Examples" }, { "code": null, "e": 26773, "s": 26730, "text": "Comparator Interface in Java with Examples" } ]
Implement two stacks in an array | Practice | GeeksforGeeks
Your task is to implement 2 stacks in one array efficiently. Example 1: Input: push1(2) push1(3) push2(4) pop1() pop2() pop2() Output: 3 4 -1 Explanation: push1(2) the stack1 will be {2} push1(3) the stack1 will be {2,3} push2(4) the stack2 will be {4} pop1() the poped element will be 3 from stack1 and stack1 will be {2} pop2() the poped element will be 4 from stack2 and now stack2 is empty pop2() the stack2 is now empty hence -1 . Your Task: You don't need to read input or print anything. You are required to complete the 4 methods push1, push2 which takes one argument an integer 'x' to be pushed into stack one and two and pop1, pop2 which returns the integer poped out from stack one and two. If no integer is present in the array return -1. Expected Time Complexity: O(1) for all the four methods. Expected Auxiliary Space: O(1) for all the four methods. Constraints: 1 <= Number of queries <= 100 1 <= value in the stack <= 100 The sum of elements in both the stacks < size of the given array 0 jainmuskan5652 weeks ago void twoStacks :: push1(int x){ if(top1+1<top2){ top1++; arr[top1]=x; }} //Function to push an integer into the stack2.void twoStacks ::push2(int x){ if(top2-1> top1){ top2--; arr[top2]=x; }} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1==-1){ return -1; } int tmp= arr[top1]; top1--; return tmp;} //Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2==-1 || top2== size){ return -1; } int tmp= arr[top2]; top2++; return tmp;} 0 hharshit81182 weeks ago Time Complexity : O(1) for all methods void twoStacks :: push1(int x){ if(top1+1 < top2){ ++top1; arr[top1] = x; }} //Function to push an integer into the stack2.void twoStacks ::push2(int x){ if(top1 < top2-1){ --top2; arr[top2] = x; }} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1 == -1){ return -1; } int x = arr[top1]; top1--; return x;} //Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2 == size){ return -1; } +1 injamamulmzp2315012 weeks ago Easy Solution in Python def push1(a,x): #code here i = 0 while a[i]!=-1: i+=1 a[i] = x#Function to push an integer into the stack2.def push2(a,x): #code here a.append(x) #Function to remove an element from top of the stack1. def pop1(a): #code here i = 0 while a[i]!=-1: i+=1 if i>0: x = a[i-1] a[i-1]=-1 return x return -1 #Function to remove an element from top of the stack2. def pop2(a): #code here if a[-1]!=-1: return a.pop() return -1 +1 jagannath23sahoo2 weeks ago C++ Solution TC: O(1) Aux SC: O(1) //Function to push an integer into the stack1. void twoStacks :: push1(int x) { if(top1 < top2-1) { arr[++top1] = x; } } //Function to push an integer into the stack2. void twoStacks ::push2(int x) { if(top1 < top2-1) { arr[--top2] = x; } } //Function to remove an element from top of the stack1. int twoStacks ::pop1() { int x; if(top1 >= 0) { x = arr[top1]; top1--; } else{ return -1; } return x; } //Function to remove an element from top of the stack2. int twoStacks :: pop2() { int x; if(top2 < size) { x = arr[top2]; top2++; } else{ return -1; } return x; } +1 22kavachdheer2 weeks ago //Function to push an integer into the stack1.void twoStacks :: push1(int x){ if(top1 < top2-1){ top1++; arr[top1]=x; }} //Function to push an integer into the stack2.void twoStacks ::push2(int x){ if(top1 < top2-1){ top2--; arr[top2]=x; }} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1 >=0){ int x=arr[top1]; top1--; return x; } else return(-1);} //Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2 < size){ int x=arr[top2]; top2++; return x; } else return(-1);} +1 himanshukug19cs3 weeks ago java soution void push1(int x, TwoStack sq) { sq.arr[sq.top1+1]=x; sq.top1=sq.top1+1; } //Function to push an integer into the stack2. void push2(int x, TwoStack sq) { sq.arr[sq.top2-1]=x; sq.top2=sq.top2-1; } //Function to remove an element from top of the stack1. int pop1(TwoStack sq) { if(sq.top1!=-1){ int temp=sq.arr[sq.top1]; sq.arr[sq.top1]=0; sq.top1=sq.top1-1; return temp; } return -1; } //Function to remove an element from top of the stack2. int pop2(TwoStack sq) {if(sq.top2!=100){ int temp=sq.arr[sq.top2]; sq.arr[sq.top2]=0; sq.top2=sq.top2+1; return temp; } return -1; } 0 maneshram20Premium4 weeks ago C++ – BEST SOLUTION : EASY UNDERSTANDING void twoStacks :: push1(int x) { if(top2-top1>1){ arr[++top1] = x; } } //Function to push an integer into the stack2. void twoStacks ::push2(int x) { if(top2-top1>1){ arr[--top2] = x; } } //Function to remove an element from top of the stack1. int twoStacks ::pop1() { if(top1>=0){ int n = arr[top1]; top1--; return n; } else return -1; } //Function to remove an element from top of the stack2. int twoStacks :: pop2() { if(top2<size){ int n = arr[top2]; top2++; return n; } else return -1; } 0 piyush104 weeks ago C#public void push1(int x, TwoStack sq) { sq.arr[++sq.top1] = x; } //Function to push an integer into the stack2. public void push2(int x, TwoStack sq) { sq.arr[--sq.top2] = x; } //Function to remove an element from top of the stack1. public int pop1(TwoStack sq) { if(sq.top1 < 0) return -1; return sq.arr[sq.top1--]; } //Function to remove an element from top of the stack2. public int pop2(TwoStack sq) { if(sq.top2 >= sq.size) return -1; return sq.arr[sq.top2++]; } 0 tarunkanade1 month ago 0.4/1.6 class Stacks { //Function to push an integer into the stack1. void push1(int x, TwoStack sq) { if(sq.top1 < sq.top2-1){ sq.arr[++sq.top1] = x; } } //Function to push an integer into the stack2. void push2(int x, TwoStack sq) { if(sq.top1 < sq.top2-1){ sq.arr[--sq.top2] = x; } } //Function to remove an element from top of the stack1. int pop1(TwoStack sq) { if(sq.top1 != -1){ int res = sq.arr[sq.top1]; sq.top1--; return res; } return -1; } //Function to remove an element from top of the stack2. int pop2(TwoStack sq) { if(sq.top2 != sq.size){ int res = sq.arr[sq.top2]; sq.top2++; return res; } return -1; } } 0 amarrajsmart1971 month ago Easy C++ Solution .Time Taken =0.0 /2.0 time complexity =O(1) in constant time. set Top1 At the starting of the array and top2 at the end of the array. void twoStacks :: push1(int x){ arr[++top1]=x; } //Function to push an integer into the stack2.void twoStacks ::push2(int x){ arr[--top2]=x;} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1==-1) return -1; return arr[top1--];} //Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2==size) return -1; return arr[top2++];} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 300, "s": 238, "text": "Your task is to implement 2 stacks in one array efficiently." }, { "code": null, "e": 313, "s": 302, "text": "Example 1:" }, { "code": null, "e": 687, "s": 313, "text": "Input:\npush1(2)\npush1(3)\npush2(4)\npop1()\npop2()\npop2()\n\nOutput:\n3 4 -1\n\nExplanation:\npush1(2) the stack1 will be {2}\npush1(3) the stack1 will be {2,3}\npush2(4) the stack2 will be {4}\npop1() the poped element will be 3 \nfrom stack1 and stack1 will be {2}\npop2() the poped element will be 4 \nfrom stack2 and now stack2 is empty\npop2() the stack2 is now empty hence -1 ." }, { "code": null, "e": 1004, "s": 689, "text": "Your Task:\nYou don't need to read input or print anything. You are required to complete the 4 methods push1, push2 which takes one argument an integer 'x' to be pushed into stack one and two and pop1, pop2 which returns the integer poped out from stack one and two. If no integer is present in the array return -1." }, { "code": null, "e": 1120, "s": 1006, "text": "Expected Time Complexity: O(1) for all the four methods.\nExpected Auxiliary Space: O(1) for all the four methods." }, { "code": null, "e": 1261, "s": 1122, "text": "Constraints:\n1 <= Number of queries <= 100\n1 <= value in the stack <= 100\nThe sum of elements in both the stacks < size of the given array" }, { "code": null, "e": 1263, "s": 1261, "text": "0" }, { "code": null, "e": 1288, "s": 1263, "text": "jainmuskan5652 weeks ago" }, { "code": null, "e": 1677, "s": 1288, "text": "void twoStacks :: push1(int x){ if(top1+1<top2){ top1++; arr[top1]=x; }} //Function to push an integer into the stack2.void twoStacks ::push2(int x){ if(top2-1> top1){ top2--; arr[top2]=x; }} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1==-1){ return -1; } int tmp= arr[top1]; top1--; return tmp;}" }, { "code": null, "e": 1858, "s": 1677, "text": "//Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2==-1 || top2== size){ return -1; } int tmp= arr[top2]; top2++; return tmp;} " }, { "code": null, "e": 1860, "s": 1858, "text": "0" }, { "code": null, "e": 1884, "s": 1860, "text": "hharshit81182 weeks ago" }, { "code": null, "e": 1923, "s": 1884, "text": "Time Complexity : O(1) for all methods" }, { "code": null, "e": 2316, "s": 1923, "text": "void twoStacks :: push1(int x){ if(top1+1 < top2){ ++top1; arr[top1] = x; }} //Function to push an integer into the stack2.void twoStacks ::push2(int x){ if(top1 < top2-1){ --top2; arr[top2] = x; }} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1 == -1){ return -1; } int x = arr[top1]; top1--; return x;}" }, { "code": null, "e": 2439, "s": 2316, "text": "//Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2 == size){ return -1; }" }, { "code": null, "e": 2442, "s": 2439, "text": "+1" }, { "code": null, "e": 2472, "s": 2442, "text": "injamamulmzp2315012 weeks ago" }, { "code": null, "e": 2496, "s": 2472, "text": "Easy Solution in Python" }, { "code": null, "e": 2991, "s": 2496, "text": "def push1(a,x): #code here i = 0 while a[i]!=-1: i+=1 a[i] = x#Function to push an integer into the stack2.def push2(a,x): #code here a.append(x) #Function to remove an element from top of the stack1. def pop1(a): #code here i = 0 while a[i]!=-1: i+=1 if i>0: x = a[i-1] a[i-1]=-1 return x return -1 #Function to remove an element from top of the stack2. def pop2(a): #code here if a[-1]!=-1: return a.pop() return -1 " }, { "code": null, "e": 2994, "s": 2991, "text": "+1" }, { "code": null, "e": 3022, "s": 2994, "text": "jagannath23sahoo2 weeks ago" }, { "code": null, "e": 3035, "s": 3022, "text": "C++ Solution" }, { "code": null, "e": 3044, "s": 3035, "text": "TC: O(1)" }, { "code": null, "e": 3057, "s": 3044, "text": "Aux SC: O(1)" }, { "code": null, "e": 3778, "s": 3057, "text": "//Function to push an integer into the stack1.\nvoid twoStacks :: push1(int x)\n{\n if(top1 < top2-1)\n {\n arr[++top1] = x;\n }\n \n}\n \n//Function to push an integer into the stack2.\nvoid twoStacks ::push2(int x)\n{\n if(top1 < top2-1)\n {\n arr[--top2] = x;\n }\n}\n \n//Function to remove an element from top of the stack1.\nint twoStacks ::pop1()\n{\n int x;\n if(top1 >= 0)\n {\n x = arr[top1];\n top1--;\n }\n else{\n return -1;\n }\n return x;\n}\n\n//Function to remove an element from top of the stack2.\nint twoStacks :: pop2()\n{\n int x;\n if(top2 < size)\n {\n x = arr[top2];\n top2++;\n }\n else{\n return -1;\n }\n return x;\n}" }, { "code": null, "e": 3781, "s": 3778, "text": "+1" }, { "code": null, "e": 3806, "s": 3781, "text": "22kavachdheer2 weeks ago" }, { "code": null, "e": 4252, "s": 3806, "text": "//Function to push an integer into the stack1.void twoStacks :: push1(int x){ if(top1 < top2-1){ top1++; arr[top1]=x; }} //Function to push an integer into the stack2.void twoStacks ::push2(int x){ if(top1 < top2-1){ top2--; arr[top2]=x; }} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1 >=0){ int x=arr[top1]; top1--; return x; } else return(-1);}" }, { "code": null, "e": 4434, "s": 4252, "text": "//Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2 < size){ int x=arr[top2]; top2++; return x; } else return(-1);}" }, { "code": null, "e": 4439, "s": 4436, "text": "+1" }, { "code": null, "e": 4466, "s": 4439, "text": "himanshukug19cs3 weeks ago" }, { "code": null, "e": 4479, "s": 4466, "text": "java soution" }, { "code": null, "e": 4571, "s": 4479, "text": " void push1(int x, TwoStack sq) { sq.arr[sq.top1+1]=x; sq.top1=sq.top1+1; }" }, { "code": null, "e": 4711, "s": 4571, "text": " //Function to push an integer into the stack2. void push2(int x, TwoStack sq) { sq.arr[sq.top2-1]=x; sq.top2=sq.top2-1;" }, { "code": null, "e": 4716, "s": 4711, "text": " }" }, { "code": null, "e": 4943, "s": 4716, "text": " //Function to remove an element from top of the stack1. int pop1(TwoStack sq) { if(sq.top1!=-1){ int temp=sq.arr[sq.top1]; sq.arr[sq.top1]=0; sq.top1=sq.top1-1; return temp; } return -1; }" }, { "code": null, "e": 5174, "s": 4943, "text": " //Function to remove an element from top of the stack2. int pop2(TwoStack sq) {if(sq.top2!=100){ int temp=sq.arr[sq.top2]; sq.arr[sq.top2]=0; sq.top2=sq.top2+1; return temp; } return -1; }" }, { "code": null, "e": 5176, "s": 5174, "text": "0" }, { "code": null, "e": 5206, "s": 5176, "text": "maneshram20Premium4 weeks ago" }, { "code": null, "e": 5249, "s": 5206, "text": "C++ – BEST SOLUTION : EASY UNDERSTANDING " }, { "code": null, "e": 5856, "s": 5249, "text": "void twoStacks :: push1(int x)\n{\n if(top2-top1>1){\n arr[++top1] = x;\n }\n}\n \n//Function to push an integer into the stack2.\nvoid twoStacks ::push2(int x)\n{\n if(top2-top1>1){\n arr[--top2] = x;\n }\n}\n \n//Function to remove an element from top of the stack1.\nint twoStacks ::pop1()\n{\n if(top1>=0){\n int n = arr[top1];\n top1--;\n return n;\n }\n else return -1;\n}\n\n//Function to remove an element from top of the stack2.\nint twoStacks :: pop2()\n{\n if(top2<size){\n int n = arr[top2];\n top2++;\n return n;\n }\n else return -1;\n}\n" }, { "code": null, "e": 5858, "s": 5856, "text": "0" }, { "code": null, "e": 5878, "s": 5858, "text": "piyush104 weeks ago" }, { "code": null, "e": 6501, "s": 5878, "text": "C#public void push1(int x, TwoStack sq) { sq.arr[++sq.top1] = x; } //Function to push an integer into the stack2. public void push2(int x, TwoStack sq) { sq.arr[--sq.top2] = x; } //Function to remove an element from top of the stack1. public int pop1(TwoStack sq) { if(sq.top1 < 0) return -1; return sq.arr[sq.top1--]; } //Function to remove an element from top of the stack2. public int pop2(TwoStack sq) { if(sq.top2 >= sq.size) return -1; return sq.arr[sq.top2++]; }" }, { "code": null, "e": 6503, "s": 6501, "text": "0" }, { "code": null, "e": 6526, "s": 6503, "text": "tarunkanade1 month ago" }, { "code": null, "e": 6534, "s": 6526, "text": "0.4/1.6" }, { "code": null, "e": 7409, "s": 6534, "text": "class Stacks\n{\n //Function to push an integer into the stack1.\n void push1(int x, TwoStack sq)\n {\n if(sq.top1 < sq.top2-1){\n sq.arr[++sq.top1] = x;\n }\n }\n\n //Function to push an integer into the stack2.\n void push2(int x, TwoStack sq)\n {\n if(sq.top1 < sq.top2-1){\n sq.arr[--sq.top2] = x;\n }\n }\n\n //Function to remove an element from top of the stack1.\n int pop1(TwoStack sq)\n {\n if(sq.top1 != -1){\n int res = sq.arr[sq.top1];\n sq.top1--;\n return res;\n }\n \n return -1;\n }\n\n //Function to remove an element from top of the stack2.\n int pop2(TwoStack sq)\n {\n if(sq.top2 != sq.size){\n int res = sq.arr[sq.top2];\n sq.top2++;\n return res;\n }\n \n return -1;\n }\n}" }, { "code": null, "e": 7411, "s": 7409, "text": "0" }, { "code": null, "e": 7438, "s": 7411, "text": "amarrajsmart1971 month ago" }, { "code": null, "e": 7478, "s": 7438, "text": "Easy C++ Solution .Time Taken =0.0 /2.0" }, { "code": null, "e": 7518, "s": 7478, "text": "time complexity =O(1) in constant time." }, { "code": null, "e": 7590, "s": 7518, "text": "set Top1 At the starting of the array and top2 at the end of the array." }, { "code": null, "e": 7875, "s": 7592, "text": "void twoStacks :: push1(int x){ arr[++top1]=x; } //Function to push an integer into the stack2.void twoStacks ::push2(int x){ arr[--top2]=x;} //Function to remove an element from top of the stack1.int twoStacks ::pop1(){ if(top1==-1) return -1; return arr[top1--];}" }, { "code": null, "e": 8008, "s": 7875, "text": "//Function to remove an element from top of the stack2.int twoStacks :: pop2(){ if(top2==size) return -1; return arr[top2++];}" }, { "code": null, "e": 8154, "s": 8008, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8190, "s": 8154, "text": " Login to access your submissions. " }, { "code": null, "e": 8200, "s": 8190, "text": "\nProblem\n" }, { "code": null, "e": 8210, "s": 8200, "text": "\nContest\n" }, { "code": null, "e": 8273, "s": 8210, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8421, "s": 8273, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8629, "s": 8421, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8735, "s": 8629, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python - Lists
The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth. Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial. There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements. The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type. Creating a list is as simple as putting different comma-separated values between square brackets. For example − list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5 ]; list3 = ["a", "b", "c", "d"] Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on. To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example − #!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; list2 = [1, 2, 3, 4, 5, 6, 7 ]; print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5] When the above code is executed, it produces the following result − list1[0]: physics list2[1:5]: [2, 3, 4, 5] You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example − #!/usr/bin/python list = ['physics', 'chemistry', 1997, 2000]; print "Value available at index 2 : " print list[2] list[2] = 2001; print "New value available at index 2 : " print list[2] Note − append() method is discussed in subsequent section. When the above code is executed, it produces the following result − Value available at index 2 : 1997 New value available at index 2 : 2001 To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example − #!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000]; print list1 del list1[2]; print "After deleting value at index 2 : " print list1 When the above code is executed, it produces following result − ['physics', 'chemistry', 1997, 2000] After deleting value at index 2 : ['physics', 'chemistry', 2000] Note − remove() method is discussed in subsequent section. Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string. In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter. Because lists are sequences, indexing and slicing work the same way for lists as they do for strings. Assuming following input − L = ['spam', 'Spam', 'SPAM!'] Python includes the following list functions − Compares elements of both lists. Gives the total length of the list. Returns item from the list with max value. Returns item from the list with min value. Converts a tuple into list. Python includes following list methods Appends object obj to list Returns count of how many times obj occurs in list Appends the contents of seq to list Returns the lowest index in list that obj appears Inserts object obj into list at offset index Removes and returns last object or obj from list Removes object obj from list Reverses objects of list in place Sorts objects of list, use compare func if given 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": 2438, "s": 2244, "text": "The most basic data structure in Python is the sequence. Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth." }, { "code": null, "e": 2566, "s": 2438, "text": "Python has six built-in types of sequences, but the most common ones are lists and tuples, which we would see in this tutorial." }, { "code": null, "e": 2852, "s": 2566, "text": "There are certain things you can do with all sequence types. These operations include indexing, slicing, adding, multiplying, and checking for membership. In addition, Python has built-in functions for finding the length of a sequence and for finding its largest and smallest elements." }, { "code": null, "e": 3083, "s": 2852, "text": "The list is a most versatile datatype available in Python which can be written as a list of comma-separated values (items) between square brackets. Important thing about a list is that items in a list need not be of the same type." }, { "code": null, "e": 3195, "s": 3083, "text": "Creating a list is as simple as putting different comma-separated values between square brackets. For example −" }, { "code": null, "e": 3297, "s": 3195, "text": "list1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5 ];\nlist3 = [\"a\", \"b\", \"c\", \"d\"]\n" }, { "code": null, "e": 3398, "s": 3297, "text": "Similar to string indices, list indices start at 0, and lists can be sliced, concatenated and so on." }, { "code": null, "e": 3548, "s": 3398, "text": "To access values in lists, use the square brackets for slicing along with the index or indices to obtain value available at that index. For example −" }, { "code": null, "e": 3707, "s": 3548, "text": "#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nlist2 = [1, 2, 3, 4, 5, 6, 7 ];\nprint \"list1[0]: \", list1[0]\nprint \"list2[1:5]: \", list2[1:5]" }, { "code": null, "e": 3775, "s": 3707, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 3821, "s": 3775, "text": "list1[0]: physics\nlist2[1:5]: [2, 3, 4, 5]\n" }, { "code": null, "e": 4021, "s": 3821, "text": "You can update single or multiple elements of lists by giving the slice on the left-hand side of the assignment operator, and you can add to elements in a list with the append() method. For example −" }, { "code": null, "e": 4209, "s": 4021, "text": "#!/usr/bin/python\n\nlist = ['physics', 'chemistry', 1997, 2000];\nprint \"Value available at index 2 : \"\nprint list[2]\nlist[2] = 2001;\nprint \"New value available at index 2 : \"\nprint list[2]" }, { "code": null, "e": 4268, "s": 4209, "text": "Note − append() method is discussed in subsequent section." }, { "code": null, "e": 4336, "s": 4268, "text": "When the above code is executed, it produces the following result −" }, { "code": null, "e": 4409, "s": 4336, "text": "Value available at index 2 :\n1997\nNew value available at index 2 :\n2001\n" }, { "code": null, "e": 4583, "s": 4409, "text": "To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know. For example −" }, { "code": null, "e": 4729, "s": 4583, "text": "#!/usr/bin/python\n\nlist1 = ['physics', 'chemistry', 1997, 2000];\nprint list1\ndel list1[2];\nprint \"After deleting value at index 2 : \"\nprint list1" }, { "code": null, "e": 4793, "s": 4729, "text": "When the above code is executed, it produces following result −" }, { "code": null, "e": 4896, "s": 4793, "text": "['physics', 'chemistry', 1997, 2000]\nAfter deleting value at index 2 :\n['physics', 'chemistry', 2000]\n" }, { "code": null, "e": 4955, "s": 4896, "text": "Note − remove() method is discussed in subsequent section." }, { "code": null, "e": 5114, "s": 4955, "text": "Lists respond to the + and * operators much like strings; they mean concatenation and repetition here too, except that the result is a new list, not a string." }, { "code": null, "e": 5220, "s": 5114, "text": "In fact, lists respond to all of the general sequence operations we used on strings in the prior chapter." }, { "code": null, "e": 5322, "s": 5220, "text": "Because lists are sequences, indexing and slicing work the same way for lists as they do for strings." }, { "code": null, "e": 5349, "s": 5322, "text": "Assuming following input −" }, { "code": null, "e": 5380, "s": 5349, "text": "L = ['spam', 'Spam', 'SPAM!']\n" }, { "code": null, "e": 5427, "s": 5380, "text": "Python includes the following list functions −" }, { "code": null, "e": 5460, "s": 5427, "text": "Compares elements of both lists." }, { "code": null, "e": 5496, "s": 5460, "text": "Gives the total length of the list." }, { "code": null, "e": 5539, "s": 5496, "text": "Returns item from the list with max value." }, { "code": null, "e": 5582, "s": 5539, "text": "Returns item from the list with min value." }, { "code": null, "e": 5610, "s": 5582, "text": "Converts a tuple into list." }, { "code": null, "e": 5649, "s": 5610, "text": "Python includes following list methods" }, { "code": null, "e": 5676, "s": 5649, "text": "Appends object obj to list" }, { "code": null, "e": 5727, "s": 5676, "text": "Returns count of how many times obj occurs in list" }, { "code": null, "e": 5763, "s": 5727, "text": "Appends the contents of seq to list" }, { "code": null, "e": 5813, "s": 5763, "text": "Returns the lowest index in list that obj appears" }, { "code": null, "e": 5858, "s": 5813, "text": "Inserts object obj into list at offset index" }, { "code": null, "e": 5907, "s": 5858, "text": "Removes and returns last object or obj from list" }, { "code": null, "e": 5936, "s": 5907, "text": "Removes object obj from list" }, { "code": null, "e": 5970, "s": 5936, "text": "Reverses objects of list in place" }, { "code": null, "e": 6019, "s": 5970, "text": "Sorts objects of list, use compare func if given" }, { "code": null, "e": 6056, "s": 6019, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6072, "s": 6056, "text": " Malhar Lathkar" }, { "code": null, "e": 6105, "s": 6072, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 6124, "s": 6105, "text": " Arnab Chakraborty" }, { "code": null, "e": 6159, "s": 6124, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 6181, "s": 6159, "text": " In28Minutes Official" }, { "code": null, "e": 6215, "s": 6181, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 6243, "s": 6215, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6278, "s": 6243, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 6292, "s": 6278, "text": " Lets Kode It" }, { "code": null, "e": 6325, "s": 6292, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 6342, "s": 6325, "text": " Abhilash Nelson" }, { "code": null, "e": 6349, "s": 6342, "text": " Print" }, { "code": null, "e": 6360, "s": 6349, "text": " Add Notes" } ]
Software Testing | Mutation Testing - GeeksforGeeks
15 May, 2019 Mutation Testing is a type of Software Testing that is performed to design new software tests and also evaluate the quality of already existing software tests. Mutation testing is related to modification a program in small ways. It focuses to help the tester develop effective tests or locate weaknesses in the test data used for the program. History of Mutation Testing:Richard Lipton proposed the mutation testing in 1971 for the first time. Although high cost reduced the use of mutation testing but now it is widely used for languages such as Java and XML. Mutation Testing is a White Box Testing. Mutation testing can be applied to design models, specifications, databases, tests, and XML. It is a structural testing technique, which uses the structure of the code to guide the testing process. It can be described as the process of rewriting the source code in small ways in order to remove the redundancies in the source code. Objective of Mutation Testing:The objective of mutation testing is: To identify pieces of code that are not tested properly. To identify hidden defects that can’t be detected using other testing methods. To discover new kinds of errors or bugs. To calculate the mutation score. To study error propagation and state infection in the program. To assess the quality of the test cases. Types of Mutation Testing:Mutation testing is basically of 3 types: Value Mutations:In this type of testing the values are changed to detect errors in the program. Basically a small value is changed to a larger value or a larger value is changed to a smaller value. In this testing basically constants are changed.Example:Initial Code: int mod = 1000000007; int a = 12345678; int b = 98765432; int c = (a + b) % mod; Changed Code: int mod = 1007; int a = 12345678; int b = 98765432; int c = (a + b) % mod; Decision Mutations:In decisions mutations are logical or arithmetic operators are changed to detect errors in the program.Example:Initial Code: if(a < b) c = 10; else c = 20; Changed Code: if(a > b) c = 10; else c = 20; Statement Mutations:In statement mutations a statement is deleted or it is replaces by some other statement.Example:Initial Code: if(a < b) c = 10; else c = 20; Changed Code: if(a < b) d = 10; else d = 20; Value Mutations:In this type of testing the values are changed to detect errors in the program. Basically a small value is changed to a larger value or a larger value is changed to a smaller value. In this testing basically constants are changed.Example:Initial Code: int mod = 1000000007; int a = 12345678; int b = 98765432; int c = (a + b) % mod; Changed Code: int mod = 1007; int a = 12345678; int b = 98765432; int c = (a + b) % mod; Example: Initial Code: int mod = 1000000007; int a = 12345678; int b = 98765432; int c = (a + b) % mod; Changed Code: int mod = 1007; int a = 12345678; int b = 98765432; int c = (a + b) % mod; Decision Mutations:In decisions mutations are logical or arithmetic operators are changed to detect errors in the program.Example:Initial Code: if(a < b) c = 10; else c = 20; Changed Code: if(a > b) c = 10; else c = 20; Example: Initial Code: if(a < b) c = 10; else c = 20; Changed Code: if(a > b) c = 10; else c = 20; Statement Mutations:In statement mutations a statement is deleted or it is replaces by some other statement.Example:Initial Code: if(a < b) c = 10; else c = 20; Changed Code: if(a < b) d = 10; else d = 20; Example: Initial Code: if(a < b) c = 10; else c = 20; Changed Code: if(a < b) d = 10; else d = 20; Advantages of Mutation Testing: It brings a good level of error detection in the program. It discovers ambiguities in the source code. Disadvantages of Mutation Testing: It is highly costly and time-consuming. It is not able for Black Box Testing. Software Testing Software Engineering Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Software Engineering | Requirements Engineering Process Software Engineering | Classical Waterfall Model DFD for Library Management System Software Requirement Specification (SRS) Format Levels in Data Flow Diagrams (DFD) Differences between Verification and Validation Software Engineering | System configuration management Software Engineering | Evolutionary Model What is DFD(Data Flow Diagram)? Difference Between PERT and CPM
[ { "code": null, "e": 24932, "s": 24904, "text": "\n15 May, 2019" }, { "code": null, "e": 25275, "s": 24932, "text": "Mutation Testing is a type of Software Testing that is performed to design new software tests and also evaluate the quality of already existing software tests. Mutation testing is related to modification a program in small ways. It focuses to help the tester develop effective tests or locate weaknesses in the test data used for the program." }, { "code": null, "e": 25493, "s": 25275, "text": "History of Mutation Testing:Richard Lipton proposed the mutation testing in 1971 for the first time. Although high cost reduced the use of mutation testing but now it is widely used for languages such as Java and XML." }, { "code": null, "e": 25534, "s": 25493, "text": "Mutation Testing is a White Box Testing." }, { "code": null, "e": 25866, "s": 25534, "text": "Mutation testing can be applied to design models, specifications, databases, tests, and XML. It is a structural testing technique, which uses the structure of the code to guide the testing process. It can be described as the process of rewriting the source code in small ways in order to remove the redundancies in the source code." }, { "code": null, "e": 25934, "s": 25866, "text": "Objective of Mutation Testing:The objective of mutation testing is:" }, { "code": null, "e": 25991, "s": 25934, "text": "To identify pieces of code that are not tested properly." }, { "code": null, "e": 26070, "s": 25991, "text": "To identify hidden defects that can’t be detected using other testing methods." }, { "code": null, "e": 26111, "s": 26070, "text": "To discover new kinds of errors or bugs." }, { "code": null, "e": 26144, "s": 26111, "text": "To calculate the mutation score." }, { "code": null, "e": 26207, "s": 26144, "text": "To study error propagation and state infection in the program." }, { "code": null, "e": 26248, "s": 26207, "text": "To assess the quality of the test cases." }, { "code": null, "e": 26316, "s": 26248, "text": "Types of Mutation Testing:Mutation testing is basically of 3 types:" }, { "code": null, "e": 27198, "s": 26316, "text": "Value Mutations:In this type of testing the values are changed to detect errors in the program. Basically a small value is changed to a larger value or a larger value is changed to a smaller value. In this testing basically constants are changed.Example:Initial Code:\n\nint mod = 1000000007;\nint a = 12345678;\nint b = 98765432;\nint c = (a + b) % mod;\n\nChanged Code:\n\nint mod = 1007;\nint a = 12345678;\nint b = 98765432;\nint c = (a + b) % mod; Decision Mutations:In decisions mutations are logical or arithmetic operators are changed to detect errors in the program.Example:Initial Code:\n\nif(a < b)\n c = 10;\nelse\n c = 20;\n\nChanged Code:\n\nif(a > b)\n c = 10;\nelse\n c = 20; Statement Mutations:In statement mutations a statement is deleted or it is replaces by some other statement.Example:Initial Code:\n\nif(a < b)\n c = 10;\nelse\n c = 20;\n\nChanged Code:\n\nif(a < b)\n d = 10;\nelse\n d = 20; " }, { "code": null, "e": 27640, "s": 27198, "text": "Value Mutations:In this type of testing the values are changed to detect errors in the program. Basically a small value is changed to a larger value or a larger value is changed to a smaller value. In this testing basically constants are changed.Example:Initial Code:\n\nint mod = 1000000007;\nint a = 12345678;\nint b = 98765432;\nint c = (a + b) % mod;\n\nChanged Code:\n\nint mod = 1007;\nint a = 12345678;\nint b = 98765432;\nint c = (a + b) % mod; " }, { "code": null, "e": 27649, "s": 27640, "text": "Example:" }, { "code": null, "e": 27837, "s": 27649, "text": "Initial Code:\n\nint mod = 1000000007;\nint a = 12345678;\nint b = 98765432;\nint c = (a + b) % mod;\n\nChanged Code:\n\nint mod = 1007;\nint a = 12345678;\nint b = 98765432;\nint c = (a + b) % mod; " }, { "code": null, "e": 28065, "s": 27837, "text": "Decision Mutations:In decisions mutations are logical or arithmetic operators are changed to detect errors in the program.Example:Initial Code:\n\nif(a < b)\n c = 10;\nelse\n c = 20;\n\nChanged Code:\n\nif(a > b)\n c = 10;\nelse\n c = 20; " }, { "code": null, "e": 28074, "s": 28065, "text": "Example:" }, { "code": null, "e": 28172, "s": 28074, "text": "Initial Code:\n\nif(a < b)\n c = 10;\nelse\n c = 20;\n\nChanged Code:\n\nif(a > b)\n c = 10;\nelse\n c = 20; " }, { "code": null, "e": 28386, "s": 28172, "text": "Statement Mutations:In statement mutations a statement is deleted or it is replaces by some other statement.Example:Initial Code:\n\nif(a < b)\n c = 10;\nelse\n c = 20;\n\nChanged Code:\n\nif(a < b)\n d = 10;\nelse\n d = 20; " }, { "code": null, "e": 28395, "s": 28386, "text": "Example:" }, { "code": null, "e": 28493, "s": 28395, "text": "Initial Code:\n\nif(a < b)\n c = 10;\nelse\n c = 20;\n\nChanged Code:\n\nif(a < b)\n d = 10;\nelse\n d = 20; " }, { "code": null, "e": 28525, "s": 28493, "text": "Advantages of Mutation Testing:" }, { "code": null, "e": 28583, "s": 28525, "text": "It brings a good level of error detection in the program." }, { "code": null, "e": 28628, "s": 28583, "text": "It discovers ambiguities in the source code." }, { "code": null, "e": 28663, "s": 28628, "text": "Disadvantages of Mutation Testing:" }, { "code": null, "e": 28703, "s": 28663, "text": "It is highly costly and time-consuming." }, { "code": null, "e": 28741, "s": 28703, "text": "It is not able for Black Box Testing." }, { "code": null, "e": 28758, "s": 28741, "text": "Software Testing" }, { "code": null, "e": 28779, "s": 28758, "text": "Software Engineering" }, { "code": null, "e": 28877, "s": 28779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28886, "s": 28877, "text": "Comments" }, { "code": null, "e": 28899, "s": 28886, "text": "Old Comments" }, { "code": null, "e": 28955, "s": 28899, "text": "Software Engineering | Requirements Engineering Process" }, { "code": null, "e": 29004, "s": 28955, "text": "Software Engineering | Classical Waterfall Model" }, { "code": null, "e": 29038, "s": 29004, "text": "DFD for Library Management System" }, { "code": null, "e": 29086, "s": 29038, "text": "Software Requirement Specification (SRS) Format" }, { "code": null, "e": 29121, "s": 29086, "text": "Levels in Data Flow Diagrams (DFD)" }, { "code": null, "e": 29169, "s": 29121, "text": "Differences between Verification and Validation" }, { "code": null, "e": 29224, "s": 29169, "text": "Software Engineering | System configuration management" }, { "code": null, "e": 29266, "s": 29224, "text": "Software Engineering | Evolutionary Model" }, { "code": null, "e": 29298, "s": 29266, "text": "What is DFD(Data Flow Diagram)?" } ]
Clojure - Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. Clojure has the following types of operators − Arithmetic operators Relational operators Logical operators Bitwise operators Note − In Clojure, operators and operands work in the following syntax manner. (operator operand1 operand2 operandn) For example, (+ 1 2) The above example does an arithmetic operation on the numbers 1 and 2. Clojure language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available in Clojure. Show Examples Relational operators allow comparison of objects. Following are the relational operators available in Clojure. Show Examples Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy. Show Examples The following code snippet shows how the various operators can be used. Clojure provides four bitwise operators. Following are the bitwise operators available in Clojure. Show Examples bit-and This is the bitwise “and” operator bit-or This is the bitwise “or” operator bit-xor This is the bitwise “xor” or Exclusive ‘or’ operator bit-not This is the bitwise negation operator Following is the truth table showcasing these operators. As is the case with LISPs in general, there is no need to worry about operator precedence. This is one of the benefits of S-Expressions and prefix notation. All functions evaluate left to right and inside out. The operators in Clojure are just functions, and everything is fully parenthesized. Print Add Notes Bookmark this page
[ { "code": null, "e": 2481, "s": 2374, "text": "An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations." }, { "code": null, "e": 2528, "s": 2481, "text": "Clojure has the following types of operators −" }, { "code": null, "e": 2549, "s": 2528, "text": "Arithmetic operators" }, { "code": null, "e": 2570, "s": 2549, "text": "Relational operators" }, { "code": null, "e": 2588, "s": 2570, "text": "Logical operators" }, { "code": null, "e": 2606, "s": 2588, "text": "Bitwise operators" }, { "code": null, "e": 2685, "s": 2606, "text": "Note − In Clojure, operators and operands work in the following syntax manner." }, { "code": null, "e": 2724, "s": 2685, "text": "(operator operand1 operand2 operandn)\n" }, { "code": null, "e": 2737, "s": 2724, "text": "For example," }, { "code": null, "e": 2745, "s": 2737, "text": "(+ 1 2)" }, { "code": null, "e": 2816, "s": 2745, "text": "The above example does an arithmetic operation on the numbers 1 and 2." }, { "code": null, "e": 2952, "s": 2816, "text": "Clojure language supports the normal Arithmetic operators as any language. Following are the Arithmetic operators available in Clojure." }, { "code": null, "e": 2966, "s": 2952, "text": "Show Examples" }, { "code": null, "e": 3077, "s": 2966, "text": "Relational operators allow comparison of objects. Following are the relational operators available in Clojure." }, { "code": null, "e": 3091, "s": 3077, "text": "Show Examples" }, { "code": null, "e": 3208, "s": 3091, "text": "Logical operators are used to evaluate Boolean expressions. Following are the logical operators available in Groovy." }, { "code": null, "e": 3222, "s": 3208, "text": "Show Examples" }, { "code": null, "e": 3294, "s": 3222, "text": "The following code snippet shows how the various operators can be used." }, { "code": null, "e": 3393, "s": 3294, "text": "Clojure provides four bitwise operators. Following are the bitwise operators available in Clojure." }, { "code": null, "e": 3407, "s": 3393, "text": "Show Examples" }, { "code": null, "e": 3415, "s": 3407, "text": "bit-and" }, { "code": null, "e": 3450, "s": 3415, "text": "This is the bitwise “and” operator" }, { "code": null, "e": 3457, "s": 3450, "text": "bit-or" }, { "code": null, "e": 3491, "s": 3457, "text": "This is the bitwise “or” operator" }, { "code": null, "e": 3499, "s": 3491, "text": "bit-xor" }, { "code": null, "e": 3552, "s": 3499, "text": "This is the bitwise “xor” or Exclusive ‘or’ operator" }, { "code": null, "e": 3560, "s": 3552, "text": "bit-not" }, { "code": null, "e": 3598, "s": 3560, "text": "This is the bitwise negation operator" }, { "code": null, "e": 3655, "s": 3598, "text": "Following is the truth table showcasing these operators." }, { "code": null, "e": 3949, "s": 3655, "text": "As is the case with LISPs in general, there is no need to worry about operator precedence. This is one of the benefits of S-Expressions and prefix notation. All functions evaluate left to right and inside out. The operators in Clojure are just functions, and everything is fully parenthesized." }, { "code": null, "e": 3956, "s": 3949, "text": " Print" }, { "code": null, "e": 3967, "s": 3956, "text": " Add Notes" } ]
DeepChem — A framework for using ML and DL for Life Science and Chemoinformatics | by Aditya Bhattacharya | Towards Data Science
Application of Machine Learning and Deep Learning for Drug Discovery, Genomics, Microsocopy and Quantum Chemistry can create radical impact and holds the potential to significantly accelerate the process of medical research and vaccine development, which is a necessity for any pandemic like Covid19. Before we even begin, this article is a very high level one and specifically targeted for Data Scientists and ML Researchers interested in Drug Discovery, especially during the time of an existing pandemic like Covid19. If you are some one with a strong background in Bio-informatics or Chem-informatics and wants to venture into the world of data science for these use-cases, please reach out to me through any of the options mentioned here, and we can discuss few interesting opportunities for the greater good of mankind. DeepChem, an open source framework, which internally uses TensorFlow, that has been specifically designed to simplify the creation of deep learning models for various life science applications. In this tutorial, we will see how to setup DeepChem and we will see how to use DeepChem for : 1. training a model that can predict toxicity of molecules 2. training a model to predict solubility of molecules 3. using SMART strings to query molecular structures. Although, in multiple sources, I have seen users have expressed their concern in setting up DeepChem in Windows, Linux and Mac environments, but I found it quite easy to do that using pip installer. The DeepChem development team, is very active and they do provide daily builds, so I would like everyone to take a look at their pypi page: https://pypi.org/project/deepchem/#history and install a suitable version in case if the latest version has any issue. A simple pip install deepchem would install the very latest version. Next, along with DeepChem, you would require TensorFlow to be installed. I had installed the latest version of TensorFlow using pip install tensorflow and RDkit which is an open source Cheminformatics software package. For RDkit and for installing in Windows, I did not find any reliable pip installer, so that installed it from https://anaconda.org/rdkit/rdkit using the conda installer : conda install -c rdkit rdkit Once these three modules are installed, we are ready to start with our experiments. Molecular toxicity can be defined as sum of adverse effects exhibited by a substance on any organism. Computational methods can actually determine the toxicity of a given compound using chemical and strcutral properties of the molecule and molecular featurization using molecular descriptors (Dong et al., 2015) and fingerprints (Xue and Bajorath, 2000), can effectively extract the chemical and structural information inherent in any given molecule for prediction-based approaches. For predicting toxicity, we will use the Tox21 toxicity dataset from MoleculeNet and we will use DeepChem to load the required dataset. import numpy as npimport deepchem as dctox21_tasks, tox21_datasets, transformers = dc.molnet.load_tox21() After this we will see all the toxicity classes, just be printing tox21_tasks ['NR-AR', 'NR-AR-LBD', 'NR-AhR', 'NR-Aromatase', 'NR-ER', 'NR-ER-LBD', 'NR-PPAR-gamma', 'SR-ARE', 'SR-ATAD5', 'SR-HSE', 'SR-MMP', 'SR-p53'] We can divide the entire dataset into training, testing and validation dataset by: train_dataset, valid_dataset, test_dataset = tox21_datasets If we check the distribution of the dataset, we will see that the dataset is not balanced, so we would need to balance the dataset as typically we are trying to solve a MultiClass Classification problem. And so if the dataset is not balanced, the majority class will add bias to the classifier, which will skew the results. So, the transformer object used by default is a balancing transformer. print(transformers)[<deepchem.trans.transformers.BalancingTransformer at 0x26b5642dc88>] now, for the training part : model = dc.models.MultitaskClassifier(n_tasks=12, n_features=1024, layer_sizes=[1000])model.fit(train_dataset, nb_epoch=10)metric = dc.metrics.Metric(dc.metrics.roc_auc_score, np.mean)train_scores = model.evaluate(train_dataset, [metric], transformers)test_scores = model.evaluate(test_dataset, [metric], transformers) Now, DeepChem’s submodule contains a variety of dc.models different life science–specific models. And finally we see, that the final AUC-ROC scores are: {'training mean-roc_auc_score': 0.9556297601807405}{'testing mean-roc_auc_score': 0.7802496964641786} This shows us that there is some over-fitting in the model as the test dataset metric scores are much less as compared to the train-set. But, nevertheless, now we do have a model that can predict toxicity from molecules! Solubility is a measure, which shows how easily a molecule can dissolve in water. For any drug discovery, it is very important to check the solubility of the compound as the drug should dissolve into the patient’s bloodstream to have the required therapeutic effect. Usually, medicinal chemists spend a lot of time in modifying molecules to increase this property of solubility. In this section we will use DeepChem to predict solubility of molecules. We will be using the delaney dataset from MoleculeNet, which is also available in DeepChem, for predicting molecular solubility. # load the featurized data tasks, datasets, transformers = dc.molnet.load_delaney(featurizer='GraphConv')# Split into traintest-validation datasettrain_dataset, valid_dataset, test_dataset = datasets# Fit the modelmodel = dc.models.GraphConvModel(n_tasks=1, mode='regression', dropout=0.2)model.fit(train_dataset, nb_epoch=100)# Use r2 score as model evaluation metricmetric = dc.metrics.Metric(dc.metrics.pearson_r2_score)print(model.evaluate(train_dataset, [metric], transformers))print(model.evaluate(test_dataset, [metric], transformers)) Even in the first pass, we see some overfitting from the model evaluation results. {'training pearson_r2_score': 0.9203419837932797}{'testing pearson_r2_score': 0.7529095508565846} Let’s see how to predict solubility for a new set of molecules: smiles = ['COC(C)(C)CCCC(C)CC=CC(C)=CC(=O)OC(C)C','CCOC(=O)CC','CSc1nc(NC(C)C)nc(NC(C)C)n1','CC(C#C)N(C)C(=O)Nc1ccc(Cl)cc1','Cc1cc2ccccc2cc1C'] Next, we need to featurize these new set of molecules from their SMILES format from rdkit import Chemmols = [Chem.MolFromSmiles(s) for s in smiles]featurizer = dc.feat.ConvMolFeaturizer()x = featurizer.featurize(mols)predicted_solubility = model.predict_on_batch(x)predicted_solubility And thus, we can see the predicted solubility values : array([[-0.45654652], [ 1.5316172 ], [ 0.19090167], [ 0.44833142], [-0.32875094]], dtype=float32) We saw very easily how DeepChem makes it very easy for the above two usecases, which may require alot of time for a human chemist to solve these problem! For the final part, we will see few visualizations and querying techniques available as a part of RDkit which is very much required when anyone is working for such use cases. SMARTS is an extension of the SMILES language described previously that can be used to create queries. # To gain a visual understanding of compounds in our dataset, let's draw them using rdkit. We define a couple of helper functions to get startedimport tempfilefrom rdkit import Chemfrom rdkit.Chem import Drawfrom itertools import islicefrom IPython.display import Image, displaydef display_images(filenames): """Helper to pretty-print images.""" for file in filenames: display(Image(file))def mols_to_pngs(mols, basename="test"): """Helper to write RDKit mols to png files.""" filenames = [] for i, mol in enumerate(mols): filename = "%s%d.png" % (basename, i) Draw.MolToFile(mol, filename) filenames.append(filename) return filenames Now, let’s take a sample SMILES string and visualize the molecular structure. from rdkit import Chemfrom rdkit.Chem.Draw import MolsToGridImagesmiles_list = ["CCCCC","CCOCC","CCNCC","CCSCC"]mol_list = [Chem.MolFromSmiles(x) for x in smiles_list]display_images(mols_to_pngs(mol_list)) This is how the visual structures are formed from the SMILES string. Now, let’s say we want to query SMILES string that has three adjacent carbons. query = Chem.MolFromSmarts("CCC")match_list = [mol.GetSubstructMatch(query) for mol inmol_list]MolsToGridImage(mols=mol_list, molsPerRow=4,highlightAtomLists=match_list) We see, that the highlighted part, represents the compound with three adjacent carbons. Similarly, let’s see some wild character query and other sub-structure query options. query = Chem.MolFromSmarts("C*C")match_list = [mol.GetSubstructMatch(query) for mol inmol_list]MolsToGridImage(mols=mol_list, molsPerRow=4,highlightAtomLists=match_list) query = Chem.MolFromSmarts("C[C,N,O]C")match_list = [mol.GetSubstructMatch(query) for mol inmol_list]MolsToGridImage(mols=mol_list, molsPerRow=4,highlightAtomLists=match_list) Thus, we can see that selective subquery can also be easily handled. Thus, this brings us to the end of this article. I know this article was very high level and specifically targeted for Data Scientists and ML Researchers interested in Drug Discovery, especially during the time of an existing pandemic like Covid19. Hope I was able to help! If you are someone with a strong background in Bio-informatics or Chem-informatics and wants to venture into the world of data science, please reach out to me through any of the options mentioned here. Keep following: https://medium.com/@adib0073 and my website: https://www.aditya-bhattacharya.net/ for more!
[ { "code": null, "e": 473, "s": 172, "text": "Application of Machine Learning and Deep Learning for Drug Discovery, Genomics, Microsocopy and Quantum Chemistry can create radical impact and holds the potential to significantly accelerate the process of medical research and vaccine development, which is a necessity for any pandemic like Covid19." }, { "code": null, "e": 998, "s": 473, "text": "Before we even begin, this article is a very high level one and specifically targeted for Data Scientists and ML Researchers interested in Drug Discovery, especially during the time of an existing pandemic like Covid19. If you are some one with a strong background in Bio-informatics or Chem-informatics and wants to venture into the world of data science for these use-cases, please reach out to me through any of the options mentioned here, and we can discuss few interesting opportunities for the greater good of mankind." }, { "code": null, "e": 1192, "s": 998, "text": "DeepChem, an open source framework, which internally uses TensorFlow, that has been specifically designed to simplify the creation of deep learning models for various life science applications." }, { "code": null, "e": 1286, "s": 1192, "text": "In this tutorial, we will see how to setup DeepChem and we will see how to use DeepChem for :" }, { "code": null, "e": 1345, "s": 1286, "text": "1. training a model that can predict toxicity of molecules" }, { "code": null, "e": 1400, "s": 1345, "text": "2. training a model to predict solubility of molecules" }, { "code": null, "e": 1454, "s": 1400, "text": "3. using SMART strings to query molecular structures." }, { "code": null, "e": 1653, "s": 1454, "text": "Although, in multiple sources, I have seen users have expressed their concern in setting up DeepChem in Windows, Linux and Mac environments, but I found it quite easy to do that using pip installer." }, { "code": null, "e": 1981, "s": 1653, "text": "The DeepChem development team, is very active and they do provide daily builds, so I would like everyone to take a look at their pypi page: https://pypi.org/project/deepchem/#history and install a suitable version in case if the latest version has any issue. A simple pip install deepchem would install the very latest version." }, { "code": null, "e": 2400, "s": 1981, "text": "Next, along with DeepChem, you would require TensorFlow to be installed. I had installed the latest version of TensorFlow using pip install tensorflow and RDkit which is an open source Cheminformatics software package. For RDkit and for installing in Windows, I did not find any reliable pip installer, so that installed it from https://anaconda.org/rdkit/rdkit using the conda installer : conda install -c rdkit rdkit" }, { "code": null, "e": 2484, "s": 2400, "text": "Once these three modules are installed, we are ready to start with our experiments." }, { "code": null, "e": 2967, "s": 2484, "text": "Molecular toxicity can be defined as sum of adverse effects exhibited by a substance on any organism. Computational methods can actually determine the toxicity of a given compound using chemical and strcutral properties of the molecule and molecular featurization using molecular descriptors (Dong et al., 2015) and fingerprints (Xue and Bajorath, 2000), can effectively extract the chemical and structural information inherent in any given molecule for prediction-based approaches." }, { "code": null, "e": 3103, "s": 2967, "text": "For predicting toxicity, we will use the Tox21 toxicity dataset from MoleculeNet and we will use DeepChem to load the required dataset." }, { "code": null, "e": 3209, "s": 3103, "text": "import numpy as npimport deepchem as dctox21_tasks, tox21_datasets, transformers = dc.molnet.load_tox21()" }, { "code": null, "e": 3287, "s": 3209, "text": "After this we will see all the toxicity classes, just be printing tox21_tasks" }, { "code": null, "e": 3427, "s": 3287, "text": "['NR-AR', 'NR-AR-LBD', 'NR-AhR', 'NR-Aromatase', 'NR-ER', 'NR-ER-LBD', 'NR-PPAR-gamma', 'SR-ARE', 'SR-ATAD5', 'SR-HSE', 'SR-MMP', 'SR-p53']" }, { "code": null, "e": 3510, "s": 3427, "text": "We can divide the entire dataset into training, testing and validation dataset by:" }, { "code": null, "e": 3570, "s": 3510, "text": "train_dataset, valid_dataset, test_dataset = tox21_datasets" }, { "code": null, "e": 3965, "s": 3570, "text": "If we check the distribution of the dataset, we will see that the dataset is not balanced, so we would need to balance the dataset as typically we are trying to solve a MultiClass Classification problem. And so if the dataset is not balanced, the majority class will add bias to the classifier, which will skew the results. So, the transformer object used by default is a balancing transformer." }, { "code": null, "e": 4054, "s": 3965, "text": "print(transformers)[<deepchem.trans.transformers.BalancingTransformer at 0x26b5642dc88>]" }, { "code": null, "e": 4083, "s": 4054, "text": "now, for the training part :" }, { "code": null, "e": 4402, "s": 4083, "text": "model = dc.models.MultitaskClassifier(n_tasks=12, n_features=1024, layer_sizes=[1000])model.fit(train_dataset, nb_epoch=10)metric = dc.metrics.Metric(dc.metrics.roc_auc_score, np.mean)train_scores = model.evaluate(train_dataset, [metric], transformers)test_scores = model.evaluate(test_dataset, [metric], transformers)" }, { "code": null, "e": 4500, "s": 4402, "text": "Now, DeepChem’s submodule contains a variety of dc.models different life science–specific models." }, { "code": null, "e": 4555, "s": 4500, "text": "And finally we see, that the final AUC-ROC scores are:" }, { "code": null, "e": 4657, "s": 4555, "text": "{'training mean-roc_auc_score': 0.9556297601807405}{'testing mean-roc_auc_score': 0.7802496964641786}" }, { "code": null, "e": 4878, "s": 4657, "text": "This shows us that there is some over-fitting in the model as the test dataset metric scores are much less as compared to the train-set. But, nevertheless, now we do have a model that can predict toxicity from molecules!" }, { "code": null, "e": 5330, "s": 4878, "text": "Solubility is a measure, which shows how easily a molecule can dissolve in water. For any drug discovery, it is very important to check the solubility of the compound as the drug should dissolve into the patient’s bloodstream to have the required therapeutic effect. Usually, medicinal chemists spend a lot of time in modifying molecules to increase this property of solubility. In this section we will use DeepChem to predict solubility of molecules." }, { "code": null, "e": 5459, "s": 5330, "text": "We will be using the delaney dataset from MoleculeNet, which is also available in DeepChem, for predicting molecular solubility." }, { "code": null, "e": 6002, "s": 5459, "text": "# load the featurized data tasks, datasets, transformers = dc.molnet.load_delaney(featurizer='GraphConv')# Split into traintest-validation datasettrain_dataset, valid_dataset, test_dataset = datasets# Fit the modelmodel = dc.models.GraphConvModel(n_tasks=1, mode='regression', dropout=0.2)model.fit(train_dataset, nb_epoch=100)# Use r2 score as model evaluation metricmetric = dc.metrics.Metric(dc.metrics.pearson_r2_score)print(model.evaluate(train_dataset, [metric], transformers))print(model.evaluate(test_dataset, [metric], transformers))" }, { "code": null, "e": 6085, "s": 6002, "text": "Even in the first pass, we see some overfitting from the model evaluation results." }, { "code": null, "e": 6183, "s": 6085, "text": "{'training pearson_r2_score': 0.9203419837932797}{'testing pearson_r2_score': 0.7529095508565846}" }, { "code": null, "e": 6247, "s": 6183, "text": "Let’s see how to predict solubility for a new set of molecules:" }, { "code": null, "e": 6391, "s": 6247, "text": "smiles = ['COC(C)(C)CCCC(C)CC=CC(C)=CC(=O)OC(C)C','CCOC(=O)CC','CSc1nc(NC(C)C)nc(NC(C)C)n1','CC(C#C)N(C)C(=O)Nc1ccc(Cl)cc1','Cc1cc2ccccc2cc1C']" }, { "code": null, "e": 6470, "s": 6391, "text": "Next, we need to featurize these new set of molecules from their SMILES format" }, { "code": null, "e": 6677, "s": 6470, "text": "from rdkit import Chemmols = [Chem.MolFromSmiles(s) for s in smiles]featurizer = dc.feat.ConvMolFeaturizer()x = featurizer.featurize(mols)predicted_solubility = model.predict_on_batch(x)predicted_solubility" }, { "code": null, "e": 6732, "s": 6677, "text": "And thus, we can see the predicted solubility values :" }, { "code": null, "e": 6854, "s": 6732, "text": "array([[-0.45654652], [ 1.5316172 ], [ 0.19090167], [ 0.44833142], [-0.32875094]], dtype=float32)" }, { "code": null, "e": 7008, "s": 6854, "text": "We saw very easily how DeepChem makes it very easy for the above two usecases, which may require alot of time for a human chemist to solve these problem!" }, { "code": null, "e": 7183, "s": 7008, "text": "For the final part, we will see few visualizations and querying techniques available as a part of RDkit which is very much required when anyone is working for such use cases." }, { "code": null, "e": 7286, "s": 7183, "text": "SMARTS is an extension of the SMILES language described previously that can be used to create queries." }, { "code": null, "e": 7969, "s": 7286, "text": "# To gain a visual understanding of compounds in our dataset, let's draw them using rdkit. We define a couple of helper functions to get startedimport tempfilefrom rdkit import Chemfrom rdkit.Chem import Drawfrom itertools import islicefrom IPython.display import Image, displaydef display_images(filenames): \"\"\"Helper to pretty-print images.\"\"\" for file in filenames: display(Image(file))def mols_to_pngs(mols, basename=\"test\"): \"\"\"Helper to write RDKit mols to png files.\"\"\" filenames = [] for i, mol in enumerate(mols): filename = \"%s%d.png\" % (basename, i) Draw.MolToFile(mol, filename) filenames.append(filename) return filenames" }, { "code": null, "e": 8047, "s": 7969, "text": "Now, let’s take a sample SMILES string and visualize the molecular structure." }, { "code": null, "e": 8253, "s": 8047, "text": "from rdkit import Chemfrom rdkit.Chem.Draw import MolsToGridImagesmiles_list = [\"CCCCC\",\"CCOCC\",\"CCNCC\",\"CCSCC\"]mol_list = [Chem.MolFromSmiles(x) for x in smiles_list]display_images(mols_to_pngs(mol_list))" }, { "code": null, "e": 8322, "s": 8253, "text": "This is how the visual structures are formed from the SMILES string." }, { "code": null, "e": 8401, "s": 8322, "text": "Now, let’s say we want to query SMILES string that has three adjacent carbons." }, { "code": null, "e": 8571, "s": 8401, "text": "query = Chem.MolFromSmarts(\"CCC\")match_list = [mol.GetSubstructMatch(query) for mol inmol_list]MolsToGridImage(mols=mol_list, molsPerRow=4,highlightAtomLists=match_list)" }, { "code": null, "e": 8659, "s": 8571, "text": "We see, that the highlighted part, represents the compound with three adjacent carbons." }, { "code": null, "e": 8745, "s": 8659, "text": "Similarly, let’s see some wild character query and other sub-structure query options." }, { "code": null, "e": 8915, "s": 8745, "text": "query = Chem.MolFromSmarts(\"C*C\")match_list = [mol.GetSubstructMatch(query) for mol inmol_list]MolsToGridImage(mols=mol_list, molsPerRow=4,highlightAtomLists=match_list)" }, { "code": null, "e": 9091, "s": 8915, "text": "query = Chem.MolFromSmarts(\"C[C,N,O]C\")match_list = [mol.GetSubstructMatch(query) for mol inmol_list]MolsToGridImage(mols=mol_list, molsPerRow=4,highlightAtomLists=match_list)" }, { "code": null, "e": 9160, "s": 9091, "text": "Thus, we can see that selective subquery can also be easily handled." } ]
Print objects of a class in Python - GeeksforGeeks
29 Dec, 2019 An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances. Refer to the below articles to get the idea about classes and objects in Python. Python Classes and Objects Printing objects give us information about the objects we are working with. In C++, we can do this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class. In Java, we use toString() method. In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users. Example: # Python program to demonstrate# object printing # Defining a classclass Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return "Test a:% s b:% s" % (self.a, self.b) def __str__(self): return "From str method of Test: a is % s, " \ "b is % s" % (self.a, self.b) # Driver Code t = Test(1234, 5678) # This calls __str__() print(t) # This calls __repr__() print([t]) Output: From str method of Test: a is 1234, b is 5678 [Test a:1234 b:5678] Important Points about Printing: Python uses __repr__ method if there is no __str__ method.Example:class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return "Test a:% s b:% s" % (self.a, self.b) # Driver Code t = Test(1234, 5678) print(t)Output:Test a:1234 b:5678 Example: class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return "Test a:% s b:% s" % (self.a, self.b) # Driver Code t = Test(1234, 5678) print(t) Output: Test a:1234 b:5678 If no __repr__ method is defined then the default is used.Example:class Test: def __init__(self, a, b): self.a = a self.b = b # Driver Code t = Test(1234, 5678) print(t) Output:<__main__.Test object at 0x7f9b5738c550> Example: class Test: def __init__(self, a, b): self.a = a self.b = b # Driver Code t = Test(1234, 5678) print(t) Output: <__main__.Test object at 0x7f9b5738c550> Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary How to Install PIP on Windows ? Read a file line by line in Python Different ways to create Pandas Dataframe Python program to convert a list to string Reading and Writing to text files in Python Python OOPs Concepts Create a Pandas DataFrame from Lists *args and **kwargs in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 24317, "s": 24289, "text": "\n29 Dec, 2019" }, { "code": null, "e": 24717, "s": 24317, "text": "An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances." }, { "code": null, "e": 24798, "s": 24717, "text": "Refer to the below articles to get the idea about classes and objects in Python." }, { "code": null, "e": 24825, "s": 24798, "text": "Python Classes and Objects" }, { "code": null, "e": 25245, "s": 24825, "text": "Printing objects give us information about the objects we are working with. In C++, we can do this by adding a friend ostream& operator << (ostream&, const Foobar&) method for the class. In Java, we use toString() method. In Python, this can be achieved by using __repr__ or __str__ methods. __repr__ is used if we need a detailed information for debugging while __str__ is used to print a string version for the users." }, { "code": null, "e": 25254, "s": 25245, "text": "Example:" }, { "code": "# Python program to demonstrate# object printing # Defining a classclass Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return \"Test a:% s b:% s\" % (self.a, self.b) def __str__(self): return \"From str method of Test: a is % s, \" \\ \"b is % s\" % (self.a, self.b) # Driver Code t = Test(1234, 5678) # This calls __str__() print(t) # This calls __repr__() print([t])", "e": 25729, "s": 25254, "text": null }, { "code": null, "e": 25737, "s": 25729, "text": "Output:" }, { "code": null, "e": 25805, "s": 25737, "text": "From str method of Test: a is 1234, b is 5678\n[Test a:1234 b:5678]\n" }, { "code": null, "e": 25838, "s": 25805, "text": "Important Points about Printing:" }, { "code": null, "e": 26147, "s": 25838, "text": "Python uses __repr__ method if there is no __str__ method.Example:class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return \"Test a:% s b:% s\" % (self.a, self.b) # Driver Code t = Test(1234, 5678) print(t)Output:Test a:1234 b:5678\n" }, { "code": null, "e": 26156, "s": 26147, "text": "Example:" }, { "code": "class Test: def __init__(self, a, b): self.a = a self.b = b def __repr__(self): return \"Test a:% s b:% s\" % (self.a, self.b) # Driver Code t = Test(1234, 5678) print(t)", "e": 26373, "s": 26156, "text": null }, { "code": null, "e": 26381, "s": 26373, "text": "Output:" }, { "code": null, "e": 26401, "s": 26381, "text": "Test a:1234 b:5678\n" }, { "code": null, "e": 26653, "s": 26401, "text": "If no __repr__ method is defined then the default is used.Example:class Test: def __init__(self, a, b): self.a = a self.b = b # Driver Code t = Test(1234, 5678) print(t) Output:<__main__.Test object at 0x7f9b5738c550>\n" }, { "code": null, "e": 26662, "s": 26653, "text": "Example:" }, { "code": "class Test: def __init__(self, a, b): self.a = a self.b = b # Driver Code t = Test(1234, 5678) print(t) ", "e": 26800, "s": 26662, "text": null }, { "code": null, "e": 26808, "s": 26800, "text": "Output:" }, { "code": null, "e": 26850, "s": 26808, "text": "<__main__.Test object at 0x7f9b5738c550>\n" }, { "code": null, "e": 26861, "s": 26850, "text": "Python-OOP" }, { "code": null, "e": 26868, "s": 26861, "text": "Python" }, { "code": null, "e": 26966, "s": 26868, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26975, "s": 26966, "text": "Comments" }, { "code": null, "e": 26988, "s": 26975, "text": "Old Comments" }, { "code": null, "e": 27006, "s": 26988, "text": "Python Dictionary" }, { "code": null, "e": 27038, "s": 27006, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27073, "s": 27038, "text": "Read a file line by line in Python" }, { "code": null, "e": 27115, "s": 27073, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27158, "s": 27115, "text": "Python program to convert a list to string" }, { "code": null, "e": 27202, "s": 27158, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27223, "s": 27202, "text": "Python OOPs Concepts" }, { "code": null, "e": 27260, "s": 27223, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27289, "s": 27260, "text": "*args and **kwargs in Python" } ]
Java Program to Convert a Stack Trace to a String
The Java.io.StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect. The Java.io.PrintWriter class prints formatted representations of objects to a text-output stream. Using these two classes you can convert a Stack Trace to a String. Live Demo import java.io.PrintWriter; import java.io.StringWriter; public class StackTraceToString { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String myString = writer.toString(); System.out.println("Stack trace message ::"+myString); } } } Stack trace message ::java.lang.ArrayIndexOutOfBoundsException: 3 at lastRound.StackTraceToString.main(StackTraceToString.java:10)
[ { "code": null, "e": 1244, "s": 1062, "text": "The Java.io.StringWriter class is a character stream that collects its output in a string buffer, which can then be used to construct a string. Closing a StringWriter has no effect." }, { "code": null, "e": 1343, "s": 1244, "text": "The Java.io.PrintWriter class prints formatted representations of objects to a text-output stream." }, { "code": null, "e": 1410, "s": 1343, "text": "Using these two classes you can convert a Stack Trace to a String." }, { "code": null, "e": 1420, "s": 1410, "text": "Live Demo" }, { "code": null, "e": 1942, "s": 1420, "text": "import java.io.PrintWriter;\nimport java.io.StringWriter;\n\npublic class StackTraceToString {\n public static void main(String args[]) {\n try {\n int a[] = new int[2];\n System.out.println(\"Access element three :\" + a[3]);\n } catch (ArrayIndexOutOfBoundsException e) {\n StringWriter writer = new StringWriter();\n e.printStackTrace(new PrintWriter(writer));\n\n String myString = writer.toString();\n System.out.println(\"Stack trace message ::\"+myString);\n }\n }\n}" }, { "code": null, "e": 2076, "s": 1942, "text": "Stack trace message ::java.lang.ArrayIndexOutOfBoundsException: 3\n at lastRound.StackTraceToString.main(StackTraceToString.java:10)" } ]