title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Python - Data Cleansing
Missing data is always a problem in real life scenarios. Areas like machine learning and data mining face severe issues in the accuracy of their model predictions because of poor quality of data caused by missing values. In these areas, missing value treatment is a major point of focus to make their models more accurate and valid. Let us consider an online survey for a product. Many a times, people do not share all the information related to them. Few people share their experience, but not how long they are using the product; few people share how long they are using the product, their experience but not their contact information. Thus, in some or the other way a part of data is always missing, and this is very common in real time. Let us now see how we can handle missing values (say NA or NaN) using Pandas. # import the pandas library import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print df Its output is as follows − one two three a 0.077988 0.476149 0.965836 b NaN NaN NaN c -0.390208 -0.551605 -2.301950 d NaN NaN NaN e -2.000303 -0.788201 1.510072 f -0.930230 -0.670473 1.146615 g NaN NaN NaN h 0.085100 0.532791 0.887415 Using reindexing, we have created a DataFrame with missing values. In the output, NaN means Not a Number. To make detecting missing values easier (and across different array dtypes), Pandas provides the isnull() and notnull() functions, which are also methods on Series and DataFrame objects − import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print df['one'].isnull() Its output is as follows − a False b True c False d True e False f False g True h False Name: one, dtype: bool Pandas provides various methods for cleaning the missing values. The fillna function can “fill in” NA values with non-null data in a couple of ways, which we have illustrated in the following sections. The following program shows how you can replace "NaN" with "0". import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c']) print df print ("NaN replaced with '0':") print df.fillna(0) Its output is as follows − one two three a -0.576991 -0.741695 0.553172 b NaN NaN NaN c 0.744328 -1.735166 1.749580 NaN replaced with '0': one two three a -0.576991 -0.741695 0.553172 b 0.000000 0.000000 0.000000 c 0.744328 -1.735166 1.749580 Here, we are filling with value zero; instead we can also fill with any other value. Using the concepts of filling discussed in the ReIndexing Chapter we will fill the missing values. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print df.fillna(method='pad') Its output is as follows − one two three a 0.077988 0.476149 0.965836 b 0.077988 0.476149 0.965836 c -0.390208 -0.551605 -2.301950 d -0.390208 -0.551605 -2.301950 e -2.000303 -0.788201 1.510072 f -0.930230 -0.670473 1.146615 g -0.930230 -0.670473 1.146615 h 0.085100 0.532791 0.887415 If you want to simply exclude the missing values, then use the dropna function along with the axis argument. By default, axis=0, i.e., along row, which means that if any value within a row is NA then the whole row is excluded. import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f', 'h'],columns=['one', 'two', 'three']) df = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']) print df.dropna() Its output is as follows − one two three a 0.077988 0.476149 0.965836 c -0.390208 -0.551605 -2.301950 e -2.000303 -0.788201 1.510072 f -0.930230 -0.670473 1.146615 h 0.085100 0.532791 0.887415 Many times, we have to replace a generic value with some specific value. We can achieve this by applying the replace method. Replacing NA with a scalar value is equivalent behavior of the fillna() function. import pandas as pd import numpy as np df = pd.DataFrame({'one':[10,20,30,40,50,2000], 'two':[1000,0,30,40,50,60]}) print df.replace({1000:10,2000:60}) Its output is as follows − one two 0 10 10 1 20 0 2 30 30 3 40 40 4 50 50 5 60 60
[ { "code": null, "e": 2996, "s": 2663, "text": "Missing data is always a problem in real life scenarios. Areas like machine learning and data mining face severe issues in the accuracy of their model predictions because of poor quality of data caused by missing values. In these areas, missing value treatment is a major point of focus to make their models more accurate and valid." }, { "code": null, "e": 3404, "s": 2996, "text": "Let us consider an online survey for a product. Many a times, people do not share all the information related to them. Few people share their experience, but not how long they are using the product; few people share how long they are using the product, their experience but not their contact information. Thus, in some or the other way a part of data is always missing, and this is very common in real time." }, { "code": null, "e": 3482, "s": 3404, "text": "Let us now see how we can handle missing values (say NA or NaN) using Pandas." }, { "code": null, "e": 3725, "s": 3482, "text": "# import the pandas library\nimport pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',\n'h'],columns=['one', 'two', 'three'])\n\ndf = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])\n\nprint df" }, { "code": null, "e": 3752, "s": 3725, "text": "Its output is as follows −" }, { "code": null, "e": 4068, "s": 3752, "text": " one two three\na 0.077988 0.476149 0.965836\nb NaN NaN NaN\nc -0.390208 -0.551605 -2.301950\nd NaN NaN NaN\ne -2.000303 -0.788201 1.510072\nf -0.930230 -0.670473 1.146615\ng NaN NaN NaN\nh 0.085100 0.532791 0.887415\n" }, { "code": null, "e": 4174, "s": 4068, "text": "Using reindexing, we have created a DataFrame with missing values. In the output, NaN means Not a Number." }, { "code": null, "e": 4362, "s": 4174, "text": "To make detecting missing values easier (and across different array dtypes), Pandas provides the isnull() and notnull() functions, which are also methods on Series and DataFrame objects −" }, { "code": null, "e": 4594, "s": 4362, "text": "import pandas as pd\nimport numpy as np\n \ndf = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',\n'h'],columns=['one', 'two', 'three'])\n\ndf = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])\n\nprint df['one'].isnull()" }, { "code": null, "e": 4621, "s": 4594, "text": "Its output is as follows −" }, { "code": null, "e": 4714, "s": 4621, "text": "a False\nb True\nc False\nd True\ne False\nf False\ng True\nh False\nName: one, dtype: bool\n" }, { "code": null, "e": 4916, "s": 4714, "text": "Pandas provides various methods for cleaning the missing values. The fillna function can “fill in” NA values with non-null data in a couple of ways, which we have illustrated in the following sections." }, { "code": null, "e": 4980, "s": 4916, "text": "The following program shows how you can replace \"NaN\" with \"0\"." }, { "code": null, "e": 5209, "s": 4980, "text": "import pandas as pd\nimport numpy as np\ndf = pd.DataFrame(np.random.randn(3, 3), index=['a', 'c', 'e'],columns=['one',\n'two', 'three'])\ndf = df.reindex(['a', 'b', 'c'])\nprint df\nprint (\"NaN replaced with '0':\")\nprint df.fillna(0)" }, { "code": null, "e": 5236, "s": 5209, "text": "Its output is as follows −" }, { "code": null, "e": 5533, "s": 5236, "text": " one two three\na -0.576991 -0.741695 0.553172\nb NaN NaN NaN\nc 0.744328 -1.735166 1.749580\n\nNaN replaced with '0':\n one two three\na -0.576991 -0.741695 0.553172\nb 0.000000 0.000000 0.000000\nc 0.744328 -1.735166 1.749580\n" }, { "code": null, "e": 5618, "s": 5533, "text": "Here, we are filling with value zero; instead we can also fill with any other value." }, { "code": null, "e": 5717, "s": 5618, "text": "Using the concepts of filling discussed in the ReIndexing Chapter we will fill the missing values." }, { "code": null, "e": 5952, "s": 5717, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',\n'h'],columns=['one', 'two', 'three'])\ndf = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])\n\nprint df.fillna(method='pad')" }, { "code": null, "e": 5979, "s": 5952, "text": "Its output is as follows −" }, { "code": null, "e": 6295, "s": 5979, "text": " one two three\na 0.077988 0.476149 0.965836\nb 0.077988 0.476149 0.965836\nc -0.390208 -0.551605 -2.301950\nd -0.390208 -0.551605 -2.301950\ne -2.000303 -0.788201 1.510072\nf -0.930230 -0.670473 1.146615\ng -0.930230 -0.670473 1.146615\nh 0.085100 0.532791 0.887415\n" }, { "code": null, "e": 6522, "s": 6295, "text": "If you want to simply exclude the missing values, then use the dropna function along with the axis argument. By default, axis=0, i.e., along row, which means that if any value within a row is NA then the whole row is excluded." }, { "code": null, "e": 6745, "s": 6522, "text": "import pandas as pd\nimport numpy as np\n\ndf = pd.DataFrame(np.random.randn(5, 3), index=['a', 'c', 'e', 'f',\n'h'],columns=['one', 'two', 'three'])\n\ndf = df.reindex(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'])\nprint df.dropna()" }, { "code": null, "e": 6772, "s": 6745, "text": "Its output is as follows −" }, { "code": null, "e": 6983, "s": 6772, "text": " one two three\na 0.077988 0.476149 0.965836\nc -0.390208 -0.551605 -2.301950\ne -2.000303 -0.788201 1.510072\nf -0.930230 -0.670473 1.146615\nh 0.085100 0.532791 0.887415\n" }, { "code": null, "e": 7108, "s": 6983, "text": "Many times, we have to replace a generic value with some specific value. We can achieve this by applying the replace method." }, { "code": null, "e": 7190, "s": 7108, "text": "Replacing NA with a scalar value is equivalent behavior of the fillna() function." }, { "code": null, "e": 7342, "s": 7190, "text": "import pandas as pd\nimport numpy as np\ndf = pd.DataFrame({'one':[10,20,30,40,50,2000],\n'two':[1000,0,30,40,50,60]})\nprint df.replace({1000:10,2000:60})" }, { "code": null, "e": 7369, "s": 7342, "text": "Its output is as follows −" } ]
Count unique values with Pandas per groups
29 Jul, 2021 Prerequisites: Pandas In this article, we are finding and counting the unique values present in the group/column with Pandas. Unique values are the distinct values that occur only once in the dataset or the first occurrences of duplicate values counted as unique values. Import the pandas library. Import or create dataframe using DataFrame() function in which pass the data as a parameter on which you want to create dataframe, let it be named as “df”, or for importing dataset use pandas.read_csv() function in which pass the path and name of the dataset. Select the column in which you want to check or count the unique values. For finding unique values we are using unique() function provided by pandas and stored it in a variable, let named as ‘unique_values’. Syntax: pandas.unique(df(column_name)) or df[‘column_name’].unique() It will give the unique values present in that group/column. For counting the number of unique values, we have to first initialize the variable let named as ‘count’ as 0, then have to run the for loop for ‘unique_values’ and count the number of times loop runs and increment the value of ‘count’ by 1 Then print the ‘count’, this stored value is the number of unique values present in that particular group/column. For finding the number of times the unique value is repeating in the particular column we are using value_counts() function provided by Pandas. Syntax: pandas.value_counts(df[‘column_name’] or df[‘column_name’].value_counts() This will give the number of times each unique values is repeating in that particular column. For a better understanding of the topic. Let’s take some examples and implement the functions as discussed above in the approach. Example 1: Creating DataFrame using pandas library. Python # importing libraryimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using# pandas DataFrame function.car_df = pd.DataFrame(car_data) # printing the dataframecar_df Output: Example 2: Printing Unique values present in the per groups. Python # importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # printing the unique values present in the Gear column# finding unique values present# in the Gear column using unique() functionprint(f"Unique values present in Gear column are: {car_df['Gear'].unique()}") # printing the unique values present# in the Cylinder column# finding unique values present in the# Cylinder column using unique() functionprint(f"Unique values present in Cylinder column are: {car_df['Cylinder'].unique()}") Output: From the above output image, we can observe that we are getting three unique value from both of the groups. Example 3: Another way of finding unique values present in per groups. Python # importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # finding unique values present in the# groups using unique() functionunique_gear = pd.unique(car_df.Gear)unique_cyl = pd.unique(car_df.Cylinder) # printing the unique values present in the Gear columnprint(f"Unique values present in Gear column are: {unique_gear}") # printing the unique values present in the Cylinder columnprint(f"Unique values present in Cylinder column are: {unique_cyl}") Output: The output is similar but the difference is that in this example we had founded the unique values present in per groups by using pd.unique() function in which we had passed our dataframe column. Example 4: Counting the number of times each unique value is repeating. Python # importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # counting number of times each unique values# present in the particular group using# value_counts() functiongear_count = pd.value_counts(car_df.Gear)cyl_count = pd.value_counts(car_df.Cylinder) # another way of obtaining the same outputg_count = car_df['Gear'].value_counts()cy_count = car_df['Cylinder'].value_counts()print('----Output from first method-----') # printing number of times each unique# values present in the particular groupprint(gear_count)print(cyl_count) # printing output from the second methodprint('----Output from second method----')print(g_count)print(cy_count) Output: From the above output image, we are getting the same result from both of the methods of writing the code. We can observe that in Gear column we are getting unique values 3,4 and 5 which are repeating 8,6 and 1 time respectively whereas in Cylinder column we are getting unique values 8,4 and 6 which are repeating 7,5 and 3 times respectively. Example 5: Counting number of unique values present in the group. Python # importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # finding unique values present in the particular group.name_count = pd.unique(car_df['Model Name'])gear_count = pd.unique(car_df.Gear)cyl_count = pd.unique(car_df.Cylinder) # initializing variable to 0 for countingname_unique = 0gear_unique = 0cyl_unique = 0 # writing separate for loop of each groupsfor item in name_count: name_unique += 1 for item in gear_count: gear_unique += 1 for item in gear_count: cyl_unique += 1 # printing the number of unique values present in each groupprint(f'Number of unique values present in Model Name: {name_unique}')print(f'Number of unique values present in Gear: {gear_unique}')print(f'Number of unique values present in Cylinder: {cyl_unique}') Output: From the above output image, we can observe that we are getting 15,3 and 3 unique values present in Model Name, Gear and Cylinder columns respectively. ruhelaa48 varshagumber28 Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2021" }, { "code": null, "e": 50, "s": 28, "text": "Prerequisites: Pandas" }, { "code": null, "e": 299, "s": 50, "text": "In this article, we are finding and counting the unique values present in the group/column with Pandas. Unique values are the distinct values that occur only once in the dataset or the first occurrences of duplicate values counted as unique values." }, { "code": null, "e": 326, "s": 299, "text": "Import the pandas library." }, { "code": null, "e": 586, "s": 326, "text": "Import or create dataframe using DataFrame() function in which pass the data as a parameter on which you want to create dataframe, let it be named as “df”, or for importing dataset use pandas.read_csv() function in which pass the path and name of the dataset." }, { "code": null, "e": 659, "s": 586, "text": "Select the column in which you want to check or count the unique values." }, { "code": null, "e": 794, "s": 659, "text": "For finding unique values we are using unique() function provided by pandas and stored it in a variable, let named as ‘unique_values’." }, { "code": null, "e": 863, "s": 794, "text": "Syntax: pandas.unique(df(column_name)) or df[‘column_name’].unique()" }, { "code": null, "e": 924, "s": 863, "text": "It will give the unique values present in that group/column." }, { "code": null, "e": 1164, "s": 924, "text": "For counting the number of unique values, we have to first initialize the variable let named as ‘count’ as 0, then have to run the for loop for ‘unique_values’ and count the number of times loop runs and increment the value of ‘count’ by 1" }, { "code": null, "e": 1278, "s": 1164, "text": "Then print the ‘count’, this stored value is the number of unique values present in that particular group/column." }, { "code": null, "e": 1422, "s": 1278, "text": "For finding the number of times the unique value is repeating in the particular column we are using value_counts() function provided by Pandas." }, { "code": null, "e": 1504, "s": 1422, "text": "Syntax: pandas.value_counts(df[‘column_name’] or df[‘column_name’].value_counts()" }, { "code": null, "e": 1598, "s": 1504, "text": "This will give the number of times each unique values is repeating in that particular column." }, { "code": null, "e": 1728, "s": 1598, "text": "For a better understanding of the topic. Let’s take some examples and implement the functions as discussed above in the approach." }, { "code": null, "e": 1780, "s": 1728, "text": "Example 1: Creating DataFrame using pandas library." }, { "code": null, "e": 1787, "s": 1780, "text": "Python" }, { "code": "# importing libraryimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using# pandas DataFrame function.car_df = pd.DataFrame(car_data) # printing the dataframecar_df", "e": 2827, "s": 1787, "text": null }, { "code": null, "e": 2835, "s": 2827, "text": "Output:" }, { "code": null, "e": 2896, "s": 2835, "text": "Example 2: Printing Unique values present in the per groups." }, { "code": null, "e": 2903, "s": 2896, "text": "Python" }, { "code": "# importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # printing the unique values present in the Gear column# finding unique values present# in the Gear column using unique() functionprint(f\"Unique values present in Gear column are: {car_df['Gear'].unique()}\") # printing the unique values present# in the Cylinder column# finding unique values present in the# Cylinder column using unique() functionprint(f\"Unique values present in Cylinder column are: {car_df['Cylinder'].unique()}\")", "e": 4326, "s": 2903, "text": null }, { "code": null, "e": 4335, "s": 4326, "text": "Output: " }, { "code": null, "e": 4443, "s": 4335, "text": "From the above output image, we can observe that we are getting three unique value from both of the groups." }, { "code": null, "e": 4514, "s": 4443, "text": "Example 3: Another way of finding unique values present in per groups." }, { "code": null, "e": 4521, "s": 4514, "text": "Python" }, { "code": "# importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # finding unique values present in the# groups using unique() functionunique_gear = pd.unique(car_df.Gear)unique_cyl = pd.unique(car_df.Cylinder) # printing the unique values present in the Gear columnprint(f\"Unique values present in Gear column are: {unique_gear}\") # printing the unique values present in the Cylinder columnprint(f\"Unique values present in Cylinder column are: {unique_cyl}\")", "e": 5906, "s": 4521, "text": null }, { "code": null, "e": 5914, "s": 5906, "text": "Output:" }, { "code": null, "e": 6109, "s": 5914, "text": "The output is similar but the difference is that in this example we had founded the unique values present in per groups by using pd.unique() function in which we had passed our dataframe column." }, { "code": null, "e": 6181, "s": 6109, "text": "Example 4: Counting the number of times each unique value is repeating." }, { "code": null, "e": 6188, "s": 6181, "text": "Python" }, { "code": "# importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # counting number of times each unique values# present in the particular group using# value_counts() functiongear_count = pd.value_counts(car_df.Gear)cyl_count = pd.value_counts(car_df.Cylinder) # another way of obtaining the same outputg_count = car_df['Gear'].value_counts()cy_count = car_df['Cylinder'].value_counts()print('----Output from first method-----') # printing number of times each unique# values present in the particular groupprint(gear_count)print(cyl_count) # printing output from the second methodprint('----Output from second method----')print(g_count)print(cy_count)", "e": 7765, "s": 6188, "text": null }, { "code": null, "e": 7773, "s": 7765, "text": "Output:" }, { "code": null, "e": 7879, "s": 7773, "text": "From the above output image, we are getting the same result from both of the methods of writing the code." }, { "code": null, "e": 8117, "s": 7879, "text": "We can observe that in Gear column we are getting unique values 3,4 and 5 which are repeating 8,6 and 1 time respectively whereas in Cylinder column we are getting unique values 8,4 and 6 which are repeating 7,5 and 3 times respectively." }, { "code": null, "e": 8183, "s": 8117, "text": "Example 5: Counting number of unique values present in the group." }, { "code": null, "e": 8190, "s": 8183, "text": "Python" }, { "code": "# importing librariesimport pandas as pd # storing the data of cars in the dictionarycar_data = {'Model Name': ['Valiant', 'Duster 360', 'Merc 240D', 'Merc 230', 'Merc 280', 'Merc 280C', 'Merc 450SE', 'Merc 450SL', 'Merc 450SLC', 'Cadillac Fleetwood', 'Lincoln Continental', 'Chrysler Imperial', 'Fiat 128', 'Honda Civic', 'Toyota Corolla'], 'Gear': [3, 3, 4, 4, 5, 4, 3, 3, 3, 3, 3, 3, 4, 4, 4], 'Cylinder': [6, 8, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 4, 4, 4]} # creating DataFrame for the data using pandascar_df = pd.DataFrame(car_data) # finding unique values present in the particular group.name_count = pd.unique(car_df['Model Name'])gear_count = pd.unique(car_df.Gear)cyl_count = pd.unique(car_df.Cylinder) # initializing variable to 0 for countingname_unique = 0gear_unique = 0cyl_unique = 0 # writing separate for loop of each groupsfor item in name_count: name_unique += 1 for item in gear_count: gear_unique += 1 for item in gear_count: cyl_unique += 1 # printing the number of unique values present in each groupprint(f'Number of unique values present in Model Name: {name_unique}')print(f'Number of unique values present in Gear: {gear_unique}')print(f'Number of unique values present in Cylinder: {cyl_unique}')", "e": 9875, "s": 8190, "text": null }, { "code": null, "e": 9883, "s": 9875, "text": "Output:" }, { "code": null, "e": 10035, "s": 9883, "text": "From the above output image, we can observe that we are getting 15,3 and 3 unique values present in Model Name, Gear and Cylinder columns respectively." }, { "code": null, "e": 10045, "s": 10035, "text": "ruhelaa48" }, { "code": null, "e": 10060, "s": 10045, "text": "varshagumber28" }, { "code": null, "e": 10067, "s": 10060, "text": "Picked" }, { "code": null, "e": 10091, "s": 10067, "text": "Python pandas-dataFrame" }, { "code": null, "e": 10114, "s": 10091, "text": "Python Pandas-exercise" }, { "code": null, "e": 10128, "s": 10114, "text": "Python-pandas" }, { "code": null, "e": 10152, "s": 10128, "text": "Technical Scripter 2020" }, { "code": null, "e": 10159, "s": 10152, "text": "Python" }, { "code": null, "e": 10178, "s": 10159, "text": "Technical Scripter" } ]
Underscore.js _.find() Function
27 Dec, 2021 The _.find() function looks at each element of the list and returns the first occurrence of the element that satisfy the condition. If any element of list is not satisfy the condition then it returns the undefined value. Syntax: _.find(list, predicate, [context]) Parameters: This function accept three parameters as mentioned above and described below: list: This parameter is used to hold the list of items. predicate: This parameter is used to hold the truth condition. context: The text content which need to be display. It is an optional parameter. Return value: It returns the first occurrence of the element that satisfy the condition. Example 1: <!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var oddNo = _.find([5, 6, 7, 8, 9, 10], function (num) { return num % 2 != 0; }); console.log(oddNo); </script></body> </html> Output: 5 Example 2: <!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> var words = ['javascript', 'java', 'unix', 'hypertext', 'underscore', 'CSS']; const result = words.find(word => word.length == 9); console.log(result); </script></body> </html> Output: hypertext sumitgumber28 JavaScript - Underscore.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Dec, 2021" }, { "code": null, "e": 249, "s": 28, "text": "The _.find() function looks at each element of the list and returns the first occurrence of the element that satisfy the condition. If any element of list is not satisfy the condition then it returns the undefined value." }, { "code": null, "e": 257, "s": 249, "text": "Syntax:" }, { "code": null, "e": 292, "s": 257, "text": "_.find(list, predicate, [context])" }, { "code": null, "e": 382, "s": 292, "text": "Parameters: This function accept three parameters as mentioned above and described below:" }, { "code": null, "e": 438, "s": 382, "text": "list: This parameter is used to hold the list of items." }, { "code": null, "e": 501, "s": 438, "text": "predicate: This parameter is used to hold the truth condition." }, { "code": null, "e": 582, "s": 501, "text": "context: The text content which need to be display. It is an optional parameter." }, { "code": null, "e": 671, "s": 582, "text": "Return value: It returns the first occurrence of the element that satisfy the condition." }, { "code": null, "e": 682, "s": 671, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var oddNo = _.find([5, 6, 7, 8, 9, 10], function (num) { return num % 2 != 0; }); console.log(oddNo); </script></body> </html>", "e": 1076, "s": 682, "text": null }, { "code": null, "e": 1084, "s": 1076, "text": "Output:" }, { "code": null, "e": 1086, "s": 1084, "text": "5" }, { "code": null, "e": 1097, "s": 1086, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> var words = ['javascript', 'java', 'unix', 'hypertext', 'underscore', 'CSS']; const result = words.find(word => word.length == 9); console.log(result); </script></body> </html>", "e": 1533, "s": 1097, "text": null }, { "code": null, "e": 1541, "s": 1533, "text": "Output:" }, { "code": null, "e": 1551, "s": 1541, "text": "hypertext" }, { "code": null, "e": 1565, "s": 1551, "text": "sumitgumber28" }, { "code": null, "e": 1592, "s": 1565, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 1603, "s": 1592, "text": "JavaScript" }, { "code": null, "e": 1620, "s": 1603, "text": "Web Technologies" }, { "code": null, "e": 1718, "s": 1620, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1779, "s": 1718, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1851, "s": 1779, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1891, "s": 1851, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1944, "s": 1891, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 1985, "s": 1944, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2018, "s": 1985, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2080, "s": 2018, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2141, "s": 2080, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2191, "s": 2141, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
MySQL query to find a value appearing more than once?
Let us first create a table − mysql> create table DemoTable -> ( -> value int -> ); Query OK, 0 rows affected (0.82 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable values(10); Query OK, 1 row affected (0.34 sec) mysql> insert into DemoTable values(30); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable values(40); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(20); Query OK, 1 row affected (0.07 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-------+ | value | +-------+ | 10 | | 100 | | 20 | | 10 | | 30 | | 40 | | 20 | +-------+ 7 rows in set (0.00 sec) Following is the query to find a value appearing more than once − mysql> select *from DemoTable group by value having count(*) > 1; This will produce the following output − +-------+ | value | +-------+ | 10 | | 20 | +-------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1192, "s": 1092, "text": "mysql> create table DemoTable\n -> (\n -> value int\n -> );\nQuery OK, 0 rows affected (0.82 sec)" }, { "code": null, "e": 1248, "s": 1192, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1794, "s": 1248, "text": "mysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DemoTable values(100);\nQuery OK, 1 row affected (0.10 sec)\n\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.28 sec)\n\nmysql> insert into DemoTable values(10);\nQuery OK, 1 row affected (0.34 sec)\n\nmysql> insert into DemoTable values(30);\nQuery OK, 1 row affected (0.24 sec)\n\nmysql> insert into DemoTable values(40);\nQuery OK, 1 row affected (0.11 sec)\n\nmysql> insert into DemoTable values(20);\nQuery OK, 1 row affected (0.07 sec)" }, { "code": null, "e": 1854, "s": 1794, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1885, "s": 1854, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1926, "s": 1885, "text": "This will produce the following output −" }, { "code": null, "e": 2061, "s": 1926, "text": "+-------+\n| value |\n+-------+\n| 10 |\n| 100 |\n| 20 |\n| 10 |\n| 30 |\n| 40 |\n| 20 |\n+-------+\n7 rows in set (0.00 sec)" }, { "code": null, "e": 2127, "s": 2061, "text": "Following is the query to find a value appearing more than once −" }, { "code": null, "e": 2193, "s": 2127, "text": "mysql> select *from DemoTable group by value having count(*) > 1;" }, { "code": null, "e": 2234, "s": 2193, "text": "This will produce the following output −" }, { "code": null, "e": 2319, "s": 2234, "text": "+-------+\n| value |\n+-------+\n| 10 |\n| 20 |\n+-------+\n2 rows in set (0.00 sec)" } ]
Sqoop - Import
This chapter describes how to import data from MySQL database to Hadoop HDFS. The ‘Import tool’ imports individual tables from RDBMS to HDFS. Each row in a table is treated as a record in HDFS. All records are stored as text data in the text files or as binary data in Avro and Sequence files. The following syntax is used to import data into HDFS. $ sqoop import (generic-args) (import-args) $ sqoop-import (generic-args) (import-args) Let us take an example of three tables named as emp, emp_add, and emp_contact, which are in a database called userdb in a MySQL database server. The three tables and their data are as follows. Sqoop tool ‘import’ is used to import table data from the table to the Hadoop file system as a text file or a binary file. The following command is used to import the emp table from MySQL database server to HDFS. $ sqoop import \ --connect jdbc:mysql://localhost/userdb \ --username root \ --table emp --m 1 If it is executed successfully, then you get the following output. 14/12/22 15:24:54 INFO sqoop.Sqoop: Running Sqoop version: 1.4.5 14/12/22 15:24:56 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset. 14/12/22 15:24:56 INFO tool.CodeGenTool: Beginning code generation 14/12/22 15:24:58 INFO manager.SqlManager: Executing SQL statement: SELECT t.* FROM `emp` AS t LIMIT 1 14/12/22 15:24:58 INFO manager.SqlManager: Executing SQL statement: SELECT t.* FROM `emp` AS t LIMIT 1 14/12/22 15:24:58 INFO orm.CompilationManager: HADOOP_MAPRED_HOME is /usr/local/hadoop 14/12/22 15:25:11 INFO orm.CompilationManager: Writing jar file: /tmp/sqoop-hadoop/compile/cebe706d23ebb1fd99c1f063ad51ebd7/emp.jar ----------------------------------------------------- ----------------------------------------------------- 14/12/22 15:25:40 INFO mapreduce.Job: The url to track the job: http://localhost:8088/proxy/application_1419242001831_0001/ 14/12/22 15:26:45 INFO mapreduce.Job: Job job_1419242001831_0001 running in uber mode : false 14/12/22 15:26:45 INFO mapreduce.Job: map 0% reduce 0% 14/12/22 15:28:08 INFO mapreduce.Job: map 100% reduce 0% 14/12/22 15:28:16 INFO mapreduce.Job: Job job_1419242001831_0001 completed successfully ----------------------------------------------------- ----------------------------------------------------- 14/12/22 15:28:17 INFO mapreduce.ImportJobBase: Transferred 145 bytes in 177.5849 seconds (0.8165 bytes/sec) 14/12/22 15:28:17 INFO mapreduce.ImportJobBase: Retrieved 5 records. To verify the imported data in HDFS, use the following command. $ $HADOOP_HOME/bin/hadoop fs -cat /emp/part-m-* It shows you the emp table data and fields are separated with comma (,). 1201, gopal, manager, 50000, TP 1202, manisha, preader, 50000, TP 1203, kalil, php dev, 30000, AC 1204, prasanth, php dev, 30000, AC 1205, kranthi, admin, 20000, TP We can specify the target directory while importing table data into HDFS using the Sqoop import tool. Following is the syntax to specify the target directory as option to the Sqoop import command. --target-dir <new or exist directory in HDFS> The following command is used to import emp_add table data into ‘/queryresult’ directory. $ sqoop import \ --connect jdbc:mysql://localhost/userdb \ --username root \ --table emp_add \ --m 1 \ --target-dir /queryresult The following command is used to verify the imported data in /queryresult directory form emp_add table. $ $HADOOP_HOME/bin/hadoop fs -cat /queryresult/part-m-* It will show you the emp_add table data with comma (,) separated fields. 1201, 288A, vgiri, jublee 1202, 108I, aoc, sec-bad 1203, 144Z, pgutta, hyd 1204, 78B, oldcity, sec-bad 1205, 720C, hitech, sec-bad We can import a subset of a table using the ‘where’ clause in Sqoop import tool. It executes the corresponding SQL query in the respective database server and stores the result in a target directory in HDFS. The syntax for where clause is as follows. --where <condition> The following command is used to import a subset of emp_add table data. The subset query is to retrieve the employee id and address, who lives in Secunderabad city. $ sqoop import \ --connect jdbc:mysql://localhost/userdb \ --username root \ --table emp_add \ --m 1 \ --where “city =’sec-bad’” \ --target-dir /wherequery The following command is used to verify the imported data in /wherequery directory from the emp_add table. $ $HADOOP_HOME/bin/hadoop fs -cat /wherequery/part-m-* It will show you the emp_add table data with comma (,) separated fields. 1202, 108I, aoc, sec-bad 1204, 78B, oldcity, sec-bad 1205, 720C, hitech, sec-bad Incremental import is a technique that imports only the newly added rows in a table. It is required to add ‘incremental’, ‘check-column’, and ‘last-value’ options to perform the incremental import. The following syntax is used for the incremental option in Sqoop import command. --incremental <mode> --check-column <column name> --last value <last check column value> Let us assume the newly added data into emp table is as follows − 1206, satish p, grp des, 20000, GR The following command is used to perform the incremental import in the emp table. $ sqoop import \ --connect jdbc:mysql://localhost/userdb \ --username root \ --table emp \ --m 1 \ --incremental append \ --check-column id \ -last value 1205 The following command is used to verify the imported data from emp table to HDFS emp/ directory. $ $HADOOP_HOME/bin/hadoop fs -cat /emp/part-m-* It shows you the emp table data with comma (,) separated fields. 1201, gopal, manager, 50000, TP 1202, manisha, preader, 50000, TP 1203, kalil, php dev, 30000, AC 1204, prasanth, php dev, 30000, AC 1205, kranthi, admin, 20000, TP 1206, satish p, grp des, 20000, GR The following command is used to see the modified or newly added rows from the emp table. $ $HADOOP_HOME/bin/hadoop fs -cat /emp/part-m-*1 It shows you the newly added rows to the emp table with comma (,) separated fields. 1206, satish p, grp des, 20000, GR 50 Lectures 4 hours Navdeep Kaur Print Add Notes Bookmark this page
[ { "code": null, "e": 2081, "s": 1787, "text": "This chapter describes how to import data from MySQL database to Hadoop HDFS. The ‘Import tool’ imports individual tables from RDBMS to HDFS. Each row in a table is treated as a record in HDFS. All records are stored as text data in the text files or as binary data in Avro and Sequence files." }, { "code": null, "e": 2136, "s": 2081, "text": "The following syntax is used to import data into HDFS." }, { "code": null, "e": 2225, "s": 2136, "text": "$ sqoop import (generic-args) (import-args) \n$ sqoop-import (generic-args) (import-args)" }, { "code": null, "e": 2370, "s": 2225, "text": "Let us take an example of three tables named as emp, emp_add, and emp_contact, which are in a database called userdb in a MySQL database server." }, { "code": null, "e": 2418, "s": 2370, "text": "The three tables and their data are as follows." }, { "code": null, "e": 2541, "s": 2418, "text": "Sqoop tool ‘import’ is used to import table data from the table to the Hadoop file system as a text file or a binary file." }, { "code": null, "e": 2631, "s": 2541, "text": "The following command is used to import the emp table from MySQL database server to HDFS." }, { "code": null, "e": 2726, "s": 2631, "text": "$ sqoop import \\\n--connect jdbc:mysql://localhost/userdb \\\n--username root \\\n--table emp --m 1" }, { "code": null, "e": 2793, "s": 2726, "text": "If it is executed successfully, then you get the following output." }, { "code": null, "e": 4278, "s": 2793, "text": "14/12/22 15:24:54 INFO sqoop.Sqoop: Running Sqoop version: 1.4.5\n14/12/22 15:24:56 INFO manager.MySQLManager: Preparing to use a MySQL streaming resultset.\n14/12/22 15:24:56 INFO tool.CodeGenTool: Beginning code generation\n14/12/22 15:24:58 INFO manager.SqlManager: Executing SQL statement: \n SELECT t.* FROM `emp` AS t LIMIT 1\n14/12/22 15:24:58 INFO manager.SqlManager: Executing SQL statement: \n SELECT t.* FROM `emp` AS t LIMIT 1\n14/12/22 15:24:58 INFO orm.CompilationManager: HADOOP_MAPRED_HOME is /usr/local/hadoop\n14/12/22 15:25:11 INFO orm.CompilationManager: Writing jar file: \n /tmp/sqoop-hadoop/compile/cebe706d23ebb1fd99c1f063ad51ebd7/emp.jar\n-----------------------------------------------------\n-----------------------------------------------------\n14/12/22 15:25:40 INFO mapreduce.Job: The url to track the job: \n http://localhost:8088/proxy/application_1419242001831_0001/\n14/12/22 15:26:45 INFO mapreduce.Job: Job job_1419242001831_0001 running in uber mode : \n false\n14/12/22 15:26:45 INFO mapreduce.Job: map 0% reduce 0%\n14/12/22 15:28:08 INFO mapreduce.Job: map 100% reduce 0%\n14/12/22 15:28:16 INFO mapreduce.Job: Job job_1419242001831_0001 completed successfully\n-----------------------------------------------------\n-----------------------------------------------------\n14/12/22 15:28:17 INFO mapreduce.ImportJobBase: Transferred 145 bytes in 177.5849 seconds \n (0.8165 bytes/sec)\n14/12/22 15:28:17 INFO mapreduce.ImportJobBase: Retrieved 5 records.\n" }, { "code": null, "e": 4342, "s": 4278, "text": "To verify the imported data in HDFS, use the following command." }, { "code": null, "e": 4390, "s": 4342, "text": "$ $HADOOP_HOME/bin/hadoop fs -cat /emp/part-m-*" }, { "code": null, "e": 4463, "s": 4390, "text": "It shows you the emp table data and fields are separated with comma (,)." }, { "code": null, "e": 4639, "s": 4463, "text": "1201, gopal, manager, 50000, TP\n1202, manisha, preader, 50000, TP\n1203, kalil, php dev, 30000, AC\n1204, prasanth, php dev, 30000, AC\n1205, kranthi, admin, 20000, TP\n" }, { "code": null, "e": 4741, "s": 4639, "text": "We can specify the target directory while importing table data into HDFS using the Sqoop import tool." }, { "code": null, "e": 4836, "s": 4741, "text": "Following is the syntax to specify the target directory as option to the Sqoop import command." }, { "code": null, "e": 4882, "s": 4836, "text": "--target-dir <new or exist directory in HDFS>" }, { "code": null, "e": 4972, "s": 4882, "text": "The following command is used to import emp_add table data into ‘/queryresult’ directory." }, { "code": null, "e": 5101, "s": 4972, "text": "$ sqoop import \\\n--connect jdbc:mysql://localhost/userdb \\\n--username root \\\n--table emp_add \\\n--m 1 \\\n--target-dir /queryresult" }, { "code": null, "e": 5205, "s": 5101, "text": "The following command is used to verify the imported data in /queryresult directory form emp_add table." }, { "code": null, "e": 5261, "s": 5205, "text": "$ $HADOOP_HOME/bin/hadoop fs -cat /queryresult/part-m-*" }, { "code": null, "e": 5334, "s": 5261, "text": "It will show you the emp_add table data with comma (,) separated fields." }, { "code": null, "e": 5475, "s": 5334, "text": "1201, 288A, vgiri, jublee\n1202, 108I, aoc, sec-bad\n1203, 144Z, pgutta, hyd\n1204, 78B, oldcity, sec-bad\n1205, 720C, hitech, sec-bad\n" }, { "code": null, "e": 5683, "s": 5475, "text": "We can import a subset of a table using the ‘where’ clause in Sqoop import tool. It executes the corresponding SQL query in the respective database server and stores the result in a target directory in HDFS." }, { "code": null, "e": 5726, "s": 5683, "text": "The syntax for where clause is as follows." }, { "code": null, "e": 5746, "s": 5726, "text": "--where <condition>" }, { "code": null, "e": 5911, "s": 5746, "text": "The following command is used to import a subset of emp_add table data. The subset query is to retrieve the employee id and address, who lives in Secunderabad city." }, { "code": null, "e": 6067, "s": 5911, "text": "$ sqoop import \\\n--connect jdbc:mysql://localhost/userdb \\\n--username root \\\n--table emp_add \\\n--m 1 \\\n--where “city =’sec-bad’” \\\n--target-dir /wherequery" }, { "code": null, "e": 6174, "s": 6067, "text": "The following command is used to verify the imported data in /wherequery directory from the emp_add table." }, { "code": null, "e": 6229, "s": 6174, "text": "$ $HADOOP_HOME/bin/hadoop fs -cat /wherequery/part-m-*" }, { "code": null, "e": 6302, "s": 6229, "text": "It will show you the emp_add table data with comma (,) separated fields." }, { "code": null, "e": 6390, "s": 6302, "text": "1202, 108I, aoc, sec-bad\n1204, 78B, oldcity, sec-bad\n1205, 720C, hitech, sec-bad\n" }, { "code": null, "e": 6588, "s": 6390, "text": "Incremental import is a technique that imports only the newly added rows in a table. It is required to add ‘incremental’, ‘check-column’, and ‘last-value’ options to perform the incremental import." }, { "code": null, "e": 6669, "s": 6588, "text": "The following syntax is used for the incremental option in Sqoop import command." }, { "code": null, "e": 6758, "s": 6669, "text": "--incremental <mode>\n--check-column <column name>\n--last value <last check column value>" }, { "code": null, "e": 6824, "s": 6758, "text": "Let us assume the newly added data into emp table is as follows −" }, { "code": null, "e": 6860, "s": 6824, "text": "1206, satish p, grp des, 20000, GR\n" }, { "code": null, "e": 6942, "s": 6860, "text": "The following command is used to perform the incremental import in the emp table." }, { "code": null, "e": 7101, "s": 6942, "text": "$ sqoop import \\\n--connect jdbc:mysql://localhost/userdb \\\n--username root \\\n--table emp \\\n--m 1 \\\n--incremental append \\\n--check-column id \\\n-last value 1205" }, { "code": null, "e": 7198, "s": 7101, "text": "The following command is used to verify the imported data from emp table to HDFS emp/ directory." }, { "code": null, "e": 7246, "s": 7198, "text": "$ $HADOOP_HOME/bin/hadoop fs -cat /emp/part-m-*" }, { "code": null, "e": 7311, "s": 7246, "text": "It shows you the emp table data with comma (,) separated fields." }, { "code": null, "e": 7522, "s": 7311, "text": "1201, gopal, manager, 50000, TP\n1202, manisha, preader, 50000, TP\n1203, kalil, php dev, 30000, AC\n1204, prasanth, php dev, 30000, AC\n1205, kranthi, admin, 20000, TP\n1206, satish p, grp des, 20000, GR\n" }, { "code": null, "e": 7612, "s": 7522, "text": "The following command is used to see the modified or newly added rows from the emp table." }, { "code": null, "e": 7661, "s": 7612, "text": "$ $HADOOP_HOME/bin/hadoop fs -cat /emp/part-m-*1" }, { "code": null, "e": 7745, "s": 7661, "text": "It shows you the newly added rows to the emp table with comma (,) separated fields." }, { "code": null, "e": 7781, "s": 7745, "text": "1206, satish p, grp des, 20000, GR\n" }, { "code": null, "e": 7814, "s": 7781, "text": "\n 50 Lectures \n 4 hours \n" }, { "code": null, "e": 7828, "s": 7814, "text": " Navdeep Kaur" }, { "code": null, "e": 7835, "s": 7828, "text": " Print" }, { "code": null, "e": 7846, "s": 7835, "text": " Add Notes" } ]
What is the use of the "requires" clause in a module-info file in Java 9?
A module is an important concept introduced in Java 9. By using this concept, we can able to divide code into smaller components called modules. Therefore, each module has its own responsibility and declare its dependency on other modules to work properly. In order to declare a module, we need to include the "module-info.java" file to root source code. There are few types of "requires" clause in "module-info" file 1) requires <module>: By default, a module doesn't know other modules present in a module-path. So, it is necessary to add a line in our module-info.java: "requires" each time when we want to access another module. module com.tutorialspoint.gui { requires com.tutorialspoint.model; requires java.desktop; } 2) requires transitive <module>: In the case of our module "com.tutorialspoint.model": returns exported interface types of module "com.core". Therefore, any module that wants to use then it also requires "com.core" to access the classes of this second module with compilation errors. Java 9 allows the keyword "transitive" to indicate that by transitivity. Users "com.tutorialspoint.model" can be able to access "com. core" that allows implementation changes easily. module com.tutorialspoint.model { requires transitive com.core; } 3) requires static <module>: The keyword "requires static" represents the concept of optional dependence such a module is: mandatory at compilation: a compilation error can be raised if the module is not present in the path module at compilation. optional at runtime: the module can't be taken into account in the sanity check phase when an application is started. The application starts even if the module is not present. For instance, we want to propose the persistence of the data of an application, either in an oracle database or h2database. module com.tutorialspoint.model { requires static ojdbc requires static h2daabase.h2; }
[ { "code": null, "e": 1417, "s": 1062, "text": "A module is an important concept introduced in Java 9. By using this concept, we can able to divide code into smaller components called modules. Therefore, each module has its own responsibility and declare its dependency on other modules to work properly. In order to declare a module, we need to include the \"module-info.java\" file to root source code." }, { "code": null, "e": 1480, "s": 1417, "text": "There are few types of \"requires\" clause in \"module-info\" file" }, { "code": null, "e": 1696, "s": 1480, "text": "1) \nrequires <module>: By default, a module doesn't know other modules present in a module-path. So, it is necessary to add a line in our module-info.java: \"requires\" each time when we want to access another module." }, { "code": null, "e": 1794, "s": 1696, "text": "module com.tutorialspoint.gui {\n requires com.tutorialspoint.model;\n requires java.desktop;\n}" }, { "code": null, "e": 2261, "s": 1794, "text": "2) requires transitive <module>: In the case of our module \"com.tutorialspoint.model\": returns exported interface types of module \"com.core\". Therefore, any module that wants to use then it also requires \"com.core\" to access the classes of this second module with compilation errors. Java 9 allows the keyword \"transitive\" to indicate that by transitivity. Users \"com.tutorialspoint.model\" can be able to access \"com. core\" that allows implementation changes easily." }, { "code": null, "e": 2330, "s": 2261, "text": "module com.tutorialspoint.model {\n requires transitive com.core;\n}" }, { "code": null, "e": 2453, "s": 2330, "text": "3) requires static <module>: The keyword \"requires static\" represents the concept of optional dependence such a module is:" }, { "code": null, "e": 2577, "s": 2453, "text": "mandatory at compilation: a compilation error can be raised if the module is not present in the path module at compilation." }, { "code": null, "e": 2753, "s": 2577, "text": "optional at runtime: the module can't be taken into account in the sanity check phase when an application is started. The application starts even if the module is not present." }, { "code": null, "e": 2877, "s": 2753, "text": "For instance, we want to propose the persistence of the data of an application, either in an oracle database or h2database." }, { "code": null, "e": 2972, "s": 2877, "text": "module com.tutorialspoint.model {\n requires static ojdbc\n requires static h2daabase.h2; \n}" } ]
How to Find the Volume of a Tetrahedron Using Determinants in Java? - GeeksforGeeks
04 Nov, 2020 Given the vertices of a tetrahedron. The task is to determine the volume of that tetrahedron using determinants. Approach: 1. Given the four vertices of the tetrahedron (x1, y1, z1), (x2, y2, z2), (x3, y3, z3), and (x4, y4, z4). Using these vertices create a (4 × 4) matrix in which the coordinate triplets form the columns of the matrix, with an extra row with each value as 1 appended at the bottom. x1 x2 x3 x4 y1 y2 y3 y4 z1 z2 z3 z4 1 1 1 1 2. For a 4 × 4 matrix which has a row of 1’s at the bottom, we can use the given simplification formula to reduce into a (3 × 3) matrix. x1-x4 x2-x4 x3-x4 y1-y4 y2-y4 y3-y4 z1-z4 z2-z4 z3-z4 3. Volume of the tetrahedron is equal to 1/6 times the absolute value of the above calculated determinant of the matrix. Input: x1=9, x2=3, x3=7, x4=9, y1=5, y2=0, y3=4, y4=6, z1=1, z2=0, z3=3, z4=0 Output: Volume of the Tetrahedron Using Determinants: 3.0 Input: x1=6, x2=8, x3=5, x4=9, y1=7, y2=1, y3=7, y4=1, z1=6, z2=9, z3=2, z4=6 Output: Volume of the Tetrahedron Using Determinants: 7.0 Java // Java program to find the volume of a// tetrahedron using determinants import java.io.*; class VolumeOfADeterminant { public static double determinant(double m[][], int n) { double dt = 0; // if the matrix has only // one element if (n == 1) { dt = m[0][0]; } // if the matrix has 4 elements // find determinant else if (n == 2) { dt = m[0][0] * m[1][1] - m[1][0] * m[0][1]; } else { dt = 0; for (int j1 = 0; j1 < n; j1++) { double[][] w = new double[n - 1][]; for (int k = 0; k < (n - 1); k++) { w[k] = new double[n - 1]; } for (int i = 1; i < n; i++) { int j2 = 0; for (int j = 0; j < n; j++) { if (j == j1) continue; w[i - 1][j2] = m[i][j]; j2++; } } dt += Math.pow(-1.0, 1.0 + j1 + 1.0) * m[0][j1] * determinant(w, n - 1); } } return dt; } public static void main(String args[]) { // Input the vertices int x1 = 5, x2 = 8, x3 = 1, x4 = 9, y1 = 5, y2 = 0, y3 = 7, y4 = 8, z1 = 8, z2 = 3, z3 = 4, z4 = 1; // create a 4 * 4 matrix double[][] m = new double[4][4]; // Create a matrix of that vertices m[0][0] = x1; m[0][1] = x2; m[0][2] = x3; m[0][3] = x4; m[1][0] = y1; m[1][1] = y2; m[1][2] = y3; m[1][3] = y4; m[2][0] = z1; m[2][1] = z2; m[2][2] = z3; m[2][3] = z4; m[3][0] = 1; m[3][1] = 1; m[3][2] = 1; m[3][3] = 1; // Converting the 4x4 matrix into 3x3 double[][] m1 = new double[3][3]; m1[0][0] = x1 - x4; m1[0][1] = x2 - x4; m1[0][2] = x3 - x4; m1[1][0] = y1 - y4; m1[1][1] = y2 - y4; m1[1][2] = y3 - y4; m1[2][0] = z1 - z4; m1[2][1] = z2 - z4; m1[2][2] = z3 - z4; // find (determinant/6) double deter = determinant(m1, 3) / 6; // if determinant is negative if (deter < 0) System.out.println( "Volume of the Tetrahedron Using Determinants: " + (deter * -1)); else System.out.println( "Volume of the Tetrahedron Using Determinants: " + (deter * -1)); }} Volume of the Tetrahedron Using Determinants: 52.333333333333336 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Convert a String to Character array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n04 Nov, 2020" }, { "code": null, "e": 23670, "s": 23557, "text": "Given the vertices of a tetrahedron. The task is to determine the volume of that tetrahedron using determinants." }, { "code": null, "e": 23680, "s": 23670, "text": "Approach:" }, { "code": null, "e": 23959, "s": 23680, "text": "1. Given the four vertices of the tetrahedron (x1, y1, z1), (x2, y2, z2), (x3, y3, z3), and (x4, y4, z4). Using these vertices create a (4 × 4) matrix in which the coordinate triplets form the columns of the matrix, with an extra row with each value as 1 appended at the bottom." }, { "code": null, "e": 24019, "s": 23959, "text": "x1 x2 x3 x4\ny1 y2 y3 y4\nz1 z2 z3 z4\n1 1 1 1" }, { "code": null, "e": 24156, "s": 24019, "text": "2. For a 4 × 4 matrix which has a row of 1’s at the bottom, we can use the given simplification formula to reduce into a (3 × 3) matrix." }, { "code": null, "e": 24222, "s": 24156, "text": "x1-x4 x2-x4 x3-x4\ny1-y4 y2-y4 y3-y4\nz1-z4 z2-z4 z3-z4" }, { "code": null, "e": 24344, "s": 24222, "text": "3. Volume of the tetrahedron is equal to 1/6 times the absolute value of the above calculated determinant of the matrix. " }, { "code": null, "e": 24618, "s": 24344, "text": "Input: x1=9, x2=3, x3=7, x4=9, y1=5, y2=0, y3=4, y4=6, z1=1, z2=0, z3=3, z4=0\nOutput: Volume of the Tetrahedron Using Determinants: 3.0\n\nInput: x1=6, x2=8, x3=5, x4=9, y1=7, y2=1, y3=7, y4=1, z1=6, z2=9, z3=2, z4=6\nOutput: Volume of the Tetrahedron Using Determinants: 7.0\n" }, { "code": null, "e": 24623, "s": 24618, "text": "Java" }, { "code": "// Java program to find the volume of a// tetrahedron using determinants import java.io.*; class VolumeOfADeterminant { public static double determinant(double m[][], int n) { double dt = 0; // if the matrix has only // one element if (n == 1) { dt = m[0][0]; } // if the matrix has 4 elements // find determinant else if (n == 2) { dt = m[0][0] * m[1][1] - m[1][0] * m[0][1]; } else { dt = 0; for (int j1 = 0; j1 < n; j1++) { double[][] w = new double[n - 1][]; for (int k = 0; k < (n - 1); k++) { w[k] = new double[n - 1]; } for (int i = 1; i < n; i++) { int j2 = 0; for (int j = 0; j < n; j++) { if (j == j1) continue; w[i - 1][j2] = m[i][j]; j2++; } } dt += Math.pow(-1.0, 1.0 + j1 + 1.0) * m[0][j1] * determinant(w, n - 1); } } return dt; } public static void main(String args[]) { // Input the vertices int x1 = 5, x2 = 8, x3 = 1, x4 = 9, y1 = 5, y2 = 0, y3 = 7, y4 = 8, z1 = 8, z2 = 3, z3 = 4, z4 = 1; // create a 4 * 4 matrix double[][] m = new double[4][4]; // Create a matrix of that vertices m[0][0] = x1; m[0][1] = x2; m[0][2] = x3; m[0][3] = x4; m[1][0] = y1; m[1][1] = y2; m[1][2] = y3; m[1][3] = y4; m[2][0] = z1; m[2][1] = z2; m[2][2] = z3; m[2][3] = z4; m[3][0] = 1; m[3][1] = 1; m[3][2] = 1; m[3][3] = 1; // Converting the 4x4 matrix into 3x3 double[][] m1 = new double[3][3]; m1[0][0] = x1 - x4; m1[0][1] = x2 - x4; m1[0][2] = x3 - x4; m1[1][0] = y1 - y4; m1[1][1] = y2 - y4; m1[1][2] = y3 - y4; m1[2][0] = z1 - z4; m1[2][1] = z2 - z4; m1[2][2] = z3 - z4; // find (determinant/6) double deter = determinant(m1, 3) / 6; // if determinant is negative if (deter < 0) System.out.println( \"Volume of the Tetrahedron Using Determinants: \" + (deter * -1)); else System.out.println( \"Volume of the Tetrahedron Using Determinants: \" + (deter * -1)); }}", "e": 27200, "s": 24623, "text": null }, { "code": null, "e": 27266, "s": 27200, "text": "Volume of the Tetrahedron Using Determinants: 52.333333333333336\n" }, { "code": null, "e": 27271, "s": 27266, "text": "Java" }, { "code": null, "e": 27285, "s": 27271, "text": "Java Programs" }, { "code": null, "e": 27290, "s": 27285, "text": "Java" }, { "code": null, "e": 27388, "s": 27290, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27397, "s": 27388, "text": "Comments" }, { "code": null, "e": 27410, "s": 27397, "text": "Old Comments" }, { "code": null, "e": 27440, "s": 27410, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27455, "s": 27440, "text": "Stream In Java" }, { "code": null, "e": 27476, "s": 27455, "text": "Constructors in Java" }, { "code": null, "e": 27522, "s": 27476, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27541, "s": 27522, "text": "Exceptions in Java" }, { "code": null, "e": 27585, "s": 27541, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27611, "s": 27585, "text": "Java Programming Examples" }, { "code": null, "e": 27645, "s": 27611, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 27692, "s": 27645, "text": "Implementing a Linked List in Java using Class" } ]
GATE | GATE-CS-2015 (Set 3) | Question 65 - GeeksforGeeks
28 Jun, 2021 Consider a network connecting two systems located 8000 kilometers apart. The bandwidth of the network is 500 × 106 bits per second. The propagation speed of the media is 4 × 106 meters per second. It is needed to design a Go-Back-N sliding window protocol for this network. The average packet size is 107 bits. The network is to be used to its full capacity. Assume that processing delays at nodes are negligible. Then, the minimum size in bits of he sequence number field has to be ________.(A) 2(B) 4(C) 8(D) 16Answer: (C)Explanation: Propagation time = (8000 * 1000)/ (4 * 10^6) = 2 seconds Total round trip propagation time = 4 seconds Transmission time for one packet = (packet size) / (bandwidth) = (10^7) / (500 * 10^6) = 0.02 seconds Total number of packets that can be transferred before an acknowledgement comes back = 4 / 0.02 = 200 Maximum possible window size is 200. In Go-Back-N, maximum sequence number should be one more than window size. So total 201 sequence numbers are needed. 201 different sequence numbers can be represented using 8 bits. Quiz of this Question GATE-CS-2015 (Set 3) GATE-GATE-CS-2015 (Set 3) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-CS-2014-(Set-1) | Question 30 GATE | GATE-CS-2001 | Question 23 GATE | GATE-CS-2015 (Set 1) | Question 65 GATE | GATE CS 2010 | Question 45 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2004 | Question 3 GATE | GATE-CS-2014-(Set-1) | Question 65 C++ Program to count Vowels in a string using Pointer GATE | GATE-CS-2015 (Set 1) | Question 42 GATE | GATE-CS-2014-(Set-3) | Question 65
[ { "code": null, "e": 24145, "s": 24117, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24682, "s": 24145, "text": "Consider a network connecting two systems located 8000 kilometers apart. The bandwidth of the network is 500 × 106 bits per second. The propagation speed of the media is 4 × 106 meters per second. It is needed to design a Go-Back-N sliding window protocol for this network. The average packet size is 107 bits. The network is to be used to its full capacity. Assume that processing delays at nodes are negligible. Then, the minimum size in bits of he sequence number field has to be ________.(A) 2(B) 4(C) 8(D) 16Answer: (C)Explanation:" }, { "code": null, "e": 25299, "s": 24682, "text": "Propagation time = (8000 * 1000)/ (4 * 10^6)\n = 2 seconds\n\nTotal round trip propagation time = 4 seconds\n\nTransmission time for one packet = (packet size) / (bandwidth)\n = (10^7) / (500 * 10^6)\n = 0.02 seconds\n\nTotal number of packets that can be transferred before an \nacknowledgement comes back = 4 / 0.02 = 200\n\nMaximum possible window size is 200. \n\nIn Go-Back-N, maximum sequence number should be one more than\nwindow size.\n\nSo total 201 sequence numbers are needed. 201 different sequence\nnumbers can be represented using 8 bits." }, { "code": null, "e": 25321, "s": 25299, "text": "Quiz of this Question" }, { "code": null, "e": 25342, "s": 25321, "text": "GATE-CS-2015 (Set 3)" }, { "code": null, "e": 25368, "s": 25342, "text": "GATE-GATE-CS-2015 (Set 3)" }, { "code": null, "e": 25373, "s": 25368, "text": "GATE" }, { "code": null, "e": 25471, "s": 25373, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25480, "s": 25471, "text": "Comments" }, { "code": null, "e": 25493, "s": 25480, "text": "Old Comments" }, { "code": null, "e": 25535, "s": 25493, "text": "GATE | GATE-CS-2014-(Set-1) | Question 30" }, { "code": null, "e": 25569, "s": 25535, "text": "GATE | GATE-CS-2001 | Question 23" }, { "code": null, "e": 25611, "s": 25569, "text": "GATE | GATE-CS-2015 (Set 1) | Question 65" }, { "code": null, "e": 25645, "s": 25611, "text": "GATE | GATE CS 2010 | Question 45" }, { "code": null, "e": 25687, "s": 25645, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 25720, "s": 25687, "text": "GATE | GATE-CS-2004 | Question 3" }, { "code": null, "e": 25762, "s": 25720, "text": "GATE | GATE-CS-2014-(Set-1) | Question 65" }, { "code": null, "e": 25816, "s": 25762, "text": "C++ Program to count Vowels in a string using Pointer" }, { "code": null, "e": 25858, "s": 25816, "text": "GATE | GATE-CS-2015 (Set 1) | Question 42" } ]
Get execution stats in MongoDB for a collection
To get stats, use explain() in MongoDB. Let us create a collection with documents − > db.demo157.insertOne({"Status":"Active"}); { "acknowledged" : true, "insertedId" : ObjectId("5e354fdffdf09dd6d08539fc") } > db.demo157.insertOne({"Status":"InActive"}); { "acknowledged" : true, "insertedId" : ObjectId("5e354fe3fdf09dd6d08539fd") } Display all documents from a collection with the help of find() method − > db.demo157.find(); This will produce the following output − { "_id" : ObjectId("5e354fdffdf09dd6d08539fc"), "Status" : "Active" } { "_id" : ObjectId("5e354fe3fdf09dd6d08539fd"), "Status" : "InActive" } Following is how to implement explain() in MongoDB − > db.demo157.find({Status: { $in: ['Active','InActive'] }}).explain("executionStats"); This will produce the following output − { "queryPlanner" : { "plannerVersion" : 1, "namespace" : "test.demo157", "indexFilterSet" : false, "parsedQuery" : { "Status" : { "$in" : [ "Active", "InActive" ] } }, "winningPlan" : { "stage" : "COLLSCAN", "filter" : { "Status" : { "$in" : [ "Active", "InActive" ] } }, "direction" : "forward" }, "rejectedPlans" : [ ] }, "executionStats" : { "executionSuccess" : true, "nReturned" : 2, "executionTimeMillis" : 18, "totalKeysExamined" : 0, "totalDocsExamined" : 2, "executionStages" : { "stage" : "COLLSCAN", "filter" : { "Status" : { "$in" : [ "Active", "InActive" ] } }, "nReturned" : 2, "executionTimeMillisEstimate" : 0, "works" : 4, "advanced" : 2, "needTime" : 1, "needYield" : 0, "saveState" : 0, "restoreState" : 0, "isEOF" : 1, "invalidates" : 0, "direction" : "forward", "docsExamined" : 2 } }, "serverInfo" : { "host" : "DESKTOP-QN2RB3H", "port" : 27017, "version" : "4.0.5", "gitVersion" "3739429dd92b92d1b0ab120911a23d50bf03c412" }, "ok" : 1 }
[ { "code": null, "e": 1146, "s": 1062, "text": "To get stats, use explain() in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1408, "s": 1146, "text": "> db.demo157.insertOne({\"Status\":\"Active\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e354fdffdf09dd6d08539fc\")\n}\n> db.demo157.insertOne({\"Status\":\"InActive\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e354fe3fdf09dd6d08539fd\")\n}" }, { "code": null, "e": 1481, "s": 1408, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1502, "s": 1481, "text": "> db.demo157.find();" }, { "code": null, "e": 1543, "s": 1502, "text": "This will produce the following output −" }, { "code": null, "e": 1685, "s": 1543, "text": "{ \"_id\" : ObjectId(\"5e354fdffdf09dd6d08539fc\"), \"Status\" : \"Active\" }\n{ \"_id\" : ObjectId(\"5e354fe3fdf09dd6d08539fd\"), \"Status\" : \"InActive\" }" }, { "code": null, "e": 1738, "s": 1685, "text": "Following is how to implement explain() in MongoDB −" }, { "code": null, "e": 1825, "s": 1738, "text": "> db.demo157.find({Status: { $in: ['Active','InActive'] }}).explain(\"executionStats\");" }, { "code": null, "e": 1866, "s": 1825, "text": "This will produce the following output −" }, { "code": null, "e": 3389, "s": 1866, "text": "{\n \"queryPlanner\" : {\n \"plannerVersion\" : 1,\n \"namespace\" : \"test.demo157\",\n \"indexFilterSet\" : false,\n \"parsedQuery\" : {\n \"Status\" : {\n \"$in\" : [\n \"Active\",\n \"InActive\"\n ]\n }\n },\n \"winningPlan\" : {\n \"stage\" : \"COLLSCAN\",\n \"filter\" : {\n \"Status\" : {\n \"$in\" : [\n \"Active\",\n \"InActive\"\n ]\n }\n },\n \"direction\" : \"forward\"\n },\n \"rejectedPlans\" : [ ]\n },\n \"executionStats\" : {\n \"executionSuccess\" : true,\n \"nReturned\" : 2,\n \"executionTimeMillis\" : 18,\n \"totalKeysExamined\" : 0,\n \"totalDocsExamined\" : 2,\n \"executionStages\" : {\n \"stage\" : \"COLLSCAN\",\n \"filter\" : {\n \"Status\" : {\n \"$in\" : [\n \"Active\",\n \"InActive\"\n ]\n }\n },\n \"nReturned\" : 2,\n \"executionTimeMillisEstimate\" : 0,\n \"works\" : 4,\n \"advanced\" : 2,\n \"needTime\" : 1,\n \"needYield\" : 0,\n \"saveState\" : 0,\n \"restoreState\" : 0,\n \"isEOF\" : 1,\n \"invalidates\" : 0,\n \"direction\" : \"forward\",\n \"docsExamined\" : 2\n }\n },\n \"serverInfo\" : {\n \"host\" : \"DESKTOP-QN2RB3H\",\n \"port\" : 27017,\n \"version\" : \"4.0.5\",\n \"gitVersion\"\n \"3739429dd92b92d1b0ab120911a23d50bf03c412\"\n },\n \"ok\" : 1\n}" } ]
ggplot2 - Installation of R
R packages come with various capabilities like analyzing statistical information or getting in depth research of geospatial data or simple we can create basic reports. Packages of R can be defined as R functions, data and compiled code in a well-defined format. The folder or directory where the packages are stored is called the library. As visible in the above figure, libPaths() is the function which displays you the library which is located, and the function library shows the packages which are saved in the library. R includes number of functions which manipulates the packages. We will focus on three major functions which is primarily used, they are − Installing Package Loading a Package Learning about Package The syntax with function for installing a package in R is − Install.packages(“<package-name>”) The simple demonstration of installing a package is visible below. Consider we need to install package “ggplot2” which is data visualization library, the following syntax is used − Install.packages(“ggplot2”) To load the particular package, we need to follow the below mentioned syntax − Library(<package-name>) The same applies for ggplot2 as mentioned below − library(“ggplot2”) The output is depicted in snapshot below − To understand the need of required package and basic functionality, R provides help function which gives the complete detail of package which is installed. The complete syntax is mentioned below − help(ggplot2) Print Add Notes Bookmark this page
[ { "code": null, "e": 2190, "s": 2022, "text": "R packages come with various capabilities like analyzing statistical information or getting in depth research of geospatial data or simple we can create basic reports." }, { "code": null, "e": 2361, "s": 2190, "text": "Packages of R can be defined as R functions, data and compiled code in a well-defined format. The folder or directory where the packages are stored is called the library." }, { "code": null, "e": 2545, "s": 2361, "text": "As visible in the above figure, libPaths() is the function which displays you the library which is located, and the function library shows the packages which are saved in the library." }, { "code": null, "e": 2683, "s": 2545, "text": "R includes number of functions which manipulates the packages. We will focus on three major functions which is primarily used, they are −" }, { "code": null, "e": 2704, "s": 2683, "text": "Installing Package " }, { "code": null, "e": 2722, "s": 2704, "text": "Loading a Package" }, { "code": null, "e": 2745, "s": 2722, "text": "Learning about Package" }, { "code": null, "e": 2805, "s": 2745, "text": "The syntax with function for installing a package in R is −" }, { "code": null, "e": 2841, "s": 2805, "text": "Install.packages(“<package-name>”)\n" }, { "code": null, "e": 3022, "s": 2841, "text": "The simple demonstration of installing a package is visible below. Consider we need to install package “ggplot2” which is data visualization library, the following syntax is used −" }, { "code": null, "e": 3051, "s": 3022, "text": "Install.packages(“ggplot2”)\n" }, { "code": null, "e": 3130, "s": 3051, "text": "To load the particular package, we need to follow the below mentioned syntax −" }, { "code": null, "e": 3155, "s": 3130, "text": "Library(<package-name>)\n" }, { "code": null, "e": 3205, "s": 3155, "text": "The same applies for ggplot2 as mentioned below −" }, { "code": null, "e": 3225, "s": 3205, "text": "library(“ggplot2”)\n" }, { "code": null, "e": 3268, "s": 3225, "text": "The output is depicted in snapshot below −" }, { "code": null, "e": 3424, "s": 3268, "text": "To understand the need of required package and basic functionality, R provides help function which gives the complete detail of package which is installed." }, { "code": null, "e": 3465, "s": 3424, "text": "The complete syntax is mentioned below −" }, { "code": null, "e": 3480, "s": 3465, "text": "help(ggplot2)\n" }, { "code": null, "e": 3487, "s": 3480, "text": " Print" }, { "code": null, "e": 3498, "s": 3487, "text": " Add Notes" } ]
Python Tools for Web scraping
In computer science Web scraping means extracting data from websites. Using this technique transform the unstructured data on the web into structured data. Most common web Scraping tools In Python3 are − Urllib2 Requests BeautifulSoup Lxml Selenium MechanicalSoup Urllib2 − This tool is pre-installed with Python. This module is used for extracting the URL's. Using urlopen () function fetching the URL's using different protocols (FTP, HTTPetc.). from urllib.request import urlopen my_html = urlopen("https://www.tutorialspoint.com/") print(my_html.read()) b'<!DOCTYPE html<\r\n <!--[if IE 8]< <html class="ie ie8"< <![endif]--< \r\n<!--[if IE 9]< <html class="ie ie9"< <![endif]-->\r\n<!--[if gt IE 9]><!--< \r\n<html lang="en-US"< <!--<![endif]--< \r\n<head>\r\n<!-- Basic --< \r\n<meta charset="utf-8"< \r\n<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title< \r\n<meta name="Description" content="Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC), Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow"/< \r\n<meta name="Keywords" content="Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson, TestLink, Inter Process Communication (IPC), Logo"/<\r\n <meta http-equiv="X-UA-Compatible" content="IE=edge">\r\n<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=yes">\r\n<link href="https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css" rel="stylesheet" type="text/css" /<\r\n <link rel="stylesheet" href="/questions/css/home.css?v=3" /< \r\n <script src="/questions/js/jquery.min.js"< </script< \r\n<script src="/questions/js/fontawesome.js"< </script<\r\n <script src="https://cdn.muicss.com/mui-0.9.39/js/mui.min.js"< </script>\r\n </head>\r\n <body>\r\n <!-- Start of Body Content --> \r\n <div class="mui-appbar-home">\r\n <div class="mui-container">\r\n <div class="tp-primary-header mui-top-home">\r\n <a href="https://www.tutorialspoint.com/index.htm" target="_blank" title="TutorialsPoint - Home"> <i class="fa fa-home"> </i><span>Home</span></a>\r\n </div>\r\n <div class="tp-primary-header mui-top-qa">\r\n <a href="https://www.tutorialspoint.com/questions/index.php" target="_blank" title="Questions & Answers - The Best Technical Questions and Answers - TutorialsPoint"><i class="fa fa-location-arrow"></i> <span> Q/A</span></a>\r\n </div>\r\n <div class="tp-primary-header mui-top-tools">\r\n <a href="https://www.tutorialspoint.com/online_dev_tools.htm" target="_blank" title="Tools - Online Development and Testing Tools"> <i class="fa fa-cogs"></i><span>Tools</span></a>\r\n </div>\r\n <div class="tp-primary-header mui-top-coding-ground">\r\n <a href="https://www.tutorialspoint.com/codingground.htm" target="_blank" title="Coding Ground - Free Online IDE and Terminal"> <i class="fa fa-code"> </i> <span> Coding Ground </span> </a> \r\n </div>\r\n <div class="tp-primary-header mui-top-current-affairs">\r\n <a href="https://www.tutorialspoint.com/current_affairs/index.htm" target="_blank" title="Current Affairs - 2016, 2017 and 2018 | General Knowledge for Competitive Exams"><i class="fa fa-globe"> </i><span>Current Affairs</span> </a>\r\n </div>\r\n <div class="tp-primary-header mui-top-upsc">\r\n <a href="https://www.tutorialspoint.com/upsc_ias_exams.htm" target="_blank" title="UPSC IAS Exams Notes - TutorialsPoint"><i class="fa fa-user-tie"></i><span>UPSC Notes</span></a>\r\n </div>\r\n <div class="tp-primary-header mui-top-tutors">\r\n <a href="https://www.tutorialspoint.com/tutor_connect/index.php" target="_blank" title="Top Online Tutors - Tutor Connect"> <i class="fa fa-user"> </i> <span>Online Tutors</span> </a>\r\n </div>\r\n <div class="tp-primary-header mui-top-examples">\r\n .... Requests − This module is not preinstalled, we have to write the command line in command prompt.Requests send request to HTTP/1.1. import requests # get URL my_req = requests.get('https://www.tutorialspoint.com/') print(my_req.encoding) print(my_req.status_code) print(my_req.elapsed) print(my_req.url) print(my_req.history) print(my_req.headers['Content-Type']) UTF-8 200 0:00:00.205727 https://www.tutorialspoint.com/ [] text/html; charset=UTF-8 BeautifulSoup − This is a parsing library which is used in different parsers. Python’s standard library provides BeautifulSoup’s default parser. It builts a parser tree which is used to extract data from HTML page. For installing this module, we write command line in command prompt. pip install beautifulsoup4 from bs4 import BeautifulSoup # importing requests import requests # get URL my_req = requests.get("https://www.tutorialspoint.com/") my_data = my_req.text my_soup = BeautifulSoup(my_data) for my_link in my_soup.find_all('a'): print(my_link.get('href')) https://www.tutorialspoint.com/index.htm https://www.tutorialspoint.com/questions/index.php https://www.tutorialspoint.com/online_dev_tools.htm https://www.tutorialspoint.com/codingground.htm https://www.tutorialspoint.com/current_affairs/index.htm https://www.tutorialspoint.com/upsc_ias_exams.htm https://www.tutorialspoint.com/tutor_connect/index.php https://www.tutorialspoint.com/programming_examples/ https://www.tutorialspoint.com/whiteboard.htm https://www.tutorialspoint.com/netmeeting.php https://www.tutorialspoint.com/articles/ https://www.tutorialspoint.com/index.htm https://www.tutorialspoint.com/tutorialslibrary.htm https://www.tutorialspoint.com/videotutorials/index.htm https://store.tutorialspoint.com https://www.tutorialspoint.com/html_online_training/index.asp https://www.tutorialspoint.com/css_online_training/index.asp https://www.tutorialspoint.com/3d_animation_online_training/index.asp https://www.tutorialspoint.com/swift_4_online_training/index.asp https://www.tutorialspoint.com/blockchain_online_training/index.asp https://www.tutorialspoint.com/reactjs_online_training/index.asp https://www.tutorialspoint.com/tutorialslibrary.htm https://www.tutorialspoint.com/computer_fundamentals/index.htm https://www.tutorialspoint.com/compiler_design/index.htm https://www.tutorialspoint.com/operating_system/index.htm https://www.tutorialspoint.com/data_structures_algorithms/index.htm https://www.tutorialspoint.com/dbms/index.htm https://www.tutorialspoint.com/data_communication_computer_network/index.htm https://www.tutorialspoint.com/academic_tutorials.htm https://www.tutorialspoint.com/html/index.htm https://www.tutorialspoint.com/css/index.htm https://www.tutorialspoint.com/javascript/index.htm https://www.tutorialspoint.com/php/index.htm https://www.tutorialspoint.com/angular4/index.htm https://www.tutorialspoint.com/mysql/index.htm https://www.tutorialspoint.com/web_development_tutorials.htm https://www.tutorialspoint.com/cprogramming/index.htm https://www.tutorialspoint.com/cplusplus/index.htm https://www.tutorialspoint.com/java8/index.htm https://www.tutorialspoint.com/python/index.htm https://www.tutorialspoint.com/scala/index.htm https://www.tutorialspoint.com/csharp/index.htm https://www.tutorialspoint.com/computer_programming_tutorials.htm https://www.tutorialspoint.com/java8/index.htm https://www.tutorialspoint.com/jdbc/index.htm https://www.tutorialspoint.com/servlets/index.htm https://www.tutorialspoint.com/spring/index.htm https://www.tutorialspoint.com/hibernate/index.htm https://www.tutorialspoint.com/swing/index.htm https://www.tutorialspoint.com/java_technology_tutorials.htm https://www.tutorialspoint.com/android/index.htm https://www.tutorialspoint.com/swift/index.htm https://www.tutorialspoint.com/ios/index.htm https://www.tutorialspoint.com/kotlin/index.htm https://www.tutorialspoint.com/react_native/index.htm https://www.tutorialspoint.com/xamarin/index.htm https://www.tutorialspoint.com/mobile_development_tutorials.htm https://www.tutorialspoint.com/mongodb/index.htm https://www.tutorialspoint.com/plsql/index.htm https://www.tutorialspoint.com/sql/index.htm https://www.tutorialspoint.com/db2/index.htm https://www.tutorialspoint.com/mysql/index.htm https://www.tutorialspoint.com/memcached/index.htm https://www.tutorialspoint.com/database_tutorials.htm https://www.tutorialspoint.com/asp.net/index.htm https://www.tutorialspoint.com/entity_framework/index.htm https://www.tutorialspoint.com/vb.net/index.htm https://www.tutorialspoint.com/ms_project/index.htm https://www.tutorialspoint.com/excel/index.htm https://www.tutorialspoint.com/word/index.htm https://www.tutorialspoint.com/microsoft_technologies_tutorials.htm https://www.tutorialspoint.com/big_data_analytics/index.htm https://www.tutorialspoint.com/hadoop/index.htm https://www.tutorialspoint.com/sas/index.htm https://www.tutorialspoint.com/qlikview/index.htm https://www.tutorialspoint.com/power_bi/index.htm https://www.tutorialspoint.com/tableau/index.htm https://www.tutorialspoint.com/big_data_tutorials.htm https://www.tutorialspoint.com/tutorialslibrary.htm https://www.tutorialspoint.com/codingground.htm https://www.tutorialspoint.com/coding_platform_for_websites.htm https://www.tutorialspoint.com/developers_best_practices/index.htm https://www.tutorialspoint.com/effective_resume_writing.htm https://www.tutorialspoint.com/computer_glossary.htm https://www.tutorialspoint.com/computer_whoiswho.htm https://www.tutorialspoint.com/questions_and_answers.htm https://www.tutorialspoint.com/multi_language_tutorials.htm https://itunes.apple.com/us/app/tutorials-point/id914891263?ls=1&mt=8 https://play.google.com/store/apps/details?id=com.tutorialspoint.onlineviewer http://www.windowsphone.com/s?appid=91249671-7184-4ad6-8a5f-d11847946b09 /about/index.htm /about/about_team.htm /about/about_careers.htm /about/about_privacy.htm /about/about_terms_of_use.htm https://www.tutorialspoint.com/articles/ https://www.tutorialspoint.com/online_dev_tools.htm https://www.tutorialspoint.com/free_web_graphics.htm https://www.tutorialspoint.com/online_file_conversion.htm https://www.tutorialspoint.com/shared-tutorials.php https://www.tutorialspoint.com/netmeeting.php https://www.tutorialspoint.com/free_online_whiteboard.htm http://www.tutorialspoint.com https://www.facebook.com/tutorialspointindia https://plus.google.com/u/0/+tutorialspoint http://www.twitter.com/tutorialspoint http://www.linkedin.com/company/tutorialspoint https://www.youtube.com/channel/UCVLbzhxVTiTLiVKeGV7WEBg https://www.tutorialspoint.com/index.htm /about/about_privacy.htm#cookies /about/faq.htm /about/about_helping.htm /about/contact_us.htm Lxml − This is a parsing library, high-performance, production-quality HTML and XML parsing library. If we want high-quality, maximum speed, then we have to use this library. It has many module by which we can extract data from web site. For installing we write in Command prompt pip install lxml from lxml import etree my_root_elem = etree.Element('html') etree.SubElement(my_root_elem, 'head') etree.SubElement(my_root_elem, 'title') etree.SubElement(my_root_elem, 'body') print(etree.tostring(my_root_elem, pretty_print = True).decode("utf-8")) <html> <head/> <title/> <body/> </html> Selenium − This is an automates browsers tool, it is also known as web-drivers. When we use any website,we observe that sometimes we have to wait for some time, for example when we click any button or scrolling the page, in this moment Selenium is needed. For installing selenium we use this command pip install selenium from selenium import webdriver my_path_to_chromedriver ='/Users/Admin/Desktop/chromedriver' my_browser = webdriver.Chrome(executable_path = my_path_to_chromedriver) my_url = 'https://www.tutorialspoint.com/' my_browser.get(my_url) MechanicalSoup − This is another Python library for automating interaction with websites. By using this we can automatically store and send cookies, can follow redirects, and can follow links and submit forms. It doesn’t do JavaScript. For installing we can use following command pip install MechanicalSoup import mechanicalsoup my_browser = mechanicalsoup.StatefulBrowser() my_value = my_browser.open("https://www.tutorialspoint.com/") print(my_value) my_val = my_browser.get_url() print(my_val) my_va = my_browser.follow_link("forms") print(my_va) my_value1 = my_browser.get_url() print(my_value1)
[ { "code": null, "e": 1218, "s": 1062, "text": "In computer science Web scraping means extracting data from websites. Using this technique transform the unstructured data on the web into structured data." }, { "code": null, "e": 1266, "s": 1218, "text": "Most common web Scraping tools In Python3 are −" }, { "code": null, "e": 1274, "s": 1266, "text": "Urllib2" }, { "code": null, "e": 1283, "s": 1274, "text": "Requests" }, { "code": null, "e": 1297, "s": 1283, "text": "BeautifulSoup" }, { "code": null, "e": 1302, "s": 1297, "text": "Lxml" }, { "code": null, "e": 1311, "s": 1302, "text": "Selenium" }, { "code": null, "e": 1326, "s": 1311, "text": "MechanicalSoup" }, { "code": null, "e": 1510, "s": 1326, "text": "Urllib2 − This tool is pre-installed with Python. This module is used for extracting the URL's. Using urlopen () function fetching the URL's using different protocols (FTP, HTTPetc.)." }, { "code": null, "e": 1620, "s": 1510, "text": "from urllib.request import urlopen\nmy_html = urlopen(\"https://www.tutorialspoint.com/\")\nprint(my_html.read())" }, { "code": null, "e": 5191, "s": 1620, "text": "b'<!DOCTYPE html<\\r\\n\n<!--[if IE 8]<\n<html class=\"ie ie8\"<\n<![endif]--<\n\\r\\n<!--[if IE 9]<\n<html class=\"ie ie9\"<\n<![endif]-->\\r\\n<!--[if gt IE 9]><!--<\n\\r\\n<html lang=\"en-US\"<\n<!--<![endif]--<\n\\r\\n<head>\\r\\n<!-- Basic --<\n\\r\\n<meta charset=\"utf-8\"<\n\\r\\n<title>Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Apache Commons Collections</title<\n\\r\\n<meta name=\"Description\" content=\"Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Current Affairs 2018, Intellij Idea, Apache Commons Collections, Java 9, GSON, TestLink, Inter Process Communication (IPC), Logo, PySpark, Google Tag Manager, Free IFSC Code, SAP Workflow\"/<\n\\r\\n<meta name=\"Keywords\" content=\"Python Data Science, Java i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible, LOLCODE, Gson, TestLink, Inter Process Communication (IPC), Logo\"/<\\r\\n\n<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\\r\\n<meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0,user-scalable=yes\">\\r\\n<link href=\"https://cdn.muicss.com/mui-0.9.39/extra/mui-rem.min.css\" rel=\"stylesheet\" type=\"text/css\" /<\\r\\n\n<link rel=\"stylesheet\" href=\"/questions/css/home.css?v=3\" /< \\r\\n\n<script src=\"/questions/js/jquery.min.js\"<\n</script<\n\\r\\n<script src=\"/questions/js/fontawesome.js\"<\n</script<\\r\\n\n<script src=\"https://cdn.muicss.com/mui-0.9.39/js/mui.min.js\"<\n</script>\\r\\n\n</head>\\r\\n\n<body>\\r\\n\n<!-- Start of Body Content --> \\r\\n\n<div class=\"mui-appbar-home\">\\r\\n\n<div class=\"mui-container\">\\r\\n\n<div class=\"tp-primary-header mui-top-home\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/index.htm\" target=\"_blank\" title=\"TutorialsPoint - Home\">\n<i class=\"fa fa-home\">\n</i><span>Home</span></a>\\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-qa\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/questions/index.php\" target=\"_blank\" title=\"Questions & Answers - The Best Technical Questions and Answers - TutorialsPoint\"><i class=\"fa fa-location-arrow\"></i>\n<span>\nQ/A</span></a>\\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-tools\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/online_dev_tools.htm\" target=\"_blank\" title=\"Tools - Online Development and Testing Tools\">\n<i class=\"fa fa-cogs\"></i><span>Tools</span></a>\\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-coding-ground\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/codingground.htm\" target=\"_blank\" title=\"Coding Ground - Free Online IDE and Terminal\">\n<i class=\"fa fa-code\">\n</i>\n<span>\nCoding Ground </span>\n</a> \\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-current-affairs\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/current_affairs/index.htm\" target=\"_blank\" title=\"Current Affairs - 2016, 2017 and 2018 | General Knowledge for Competitive Exams\"><i class=\"fa fa-globe\">\n</i><span>Current Affairs</span>\n</a>\\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-upsc\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/upsc_ias_exams.htm\" target=\"_blank\" title=\"UPSC IAS Exams Notes - TutorialsPoint\"><i class=\"fa fa-user-tie\"></i><span>UPSC Notes</span></a>\\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-tutors\">\\r\\n\n<a href=\"https://www.tutorialspoint.com/tutor_connect/index.php\" target=\"_blank\" title=\"Top Online Tutors - Tutor Connect\">\n<i class=\"fa fa-user\">\n</i>\n<span>Online Tutors</span>\n</a>\\r\\n\n</div>\\r\\n\n<div class=\"tp-primary-header mui-top-examples\">\\r\\n\n...." }, { "code": null, "e": 5322, "s": 5191, "text": "Requests − This module is not preinstalled, we have to write the command line in command prompt.Requests send request to HTTP/1.1." }, { "code": null, "e": 5569, "s": 5322, "text": "import requests\n# get URL\nmy_req = requests.get('https://www.tutorialspoint.com/')\n print(my_req.encoding)\n print(my_req.status_code)\n print(my_req.elapsed)\n print(my_req.url)\n print(my_req.history)\nprint(my_req.headers['Content-Type'])" }, { "code": null, "e": 5654, "s": 5569, "text": "UTF-8\n200\n0:00:00.205727\nhttps://www.tutorialspoint.com/\n[]\ntext/html; charset=UTF-8" }, { "code": null, "e": 5869, "s": 5654, "text": "BeautifulSoup − This is a parsing library which is used in different parsers. Python’s standard library provides BeautifulSoup’s default parser. It builts a parser tree which is used to extract data from HTML page." }, { "code": null, "e": 5938, "s": 5869, "text": "For installing this module, we write command line in command prompt." }, { "code": null, "e": 5965, "s": 5938, "text": "pip install beautifulsoup4" }, { "code": null, "e": 6219, "s": 5965, "text": "from bs4 import BeautifulSoup\n# importing requests\nimport requests\n# get URL\nmy_req = requests.get(\"https://www.tutorialspoint.com/\")\nmy_data = my_req.text\nmy_soup = BeautifulSoup(my_data)\nfor my_link in my_soup.find_all('a'):\nprint(my_link.get('href'))" }, { "code": null, "e": 11893, "s": 6219, "text": "https://www.tutorialspoint.com/index.htm\nhttps://www.tutorialspoint.com/questions/index.php\nhttps://www.tutorialspoint.com/online_dev_tools.htm\nhttps://www.tutorialspoint.com/codingground.htm\nhttps://www.tutorialspoint.com/current_affairs/index.htm\nhttps://www.tutorialspoint.com/upsc_ias_exams.htm\nhttps://www.tutorialspoint.com/tutor_connect/index.php\nhttps://www.tutorialspoint.com/programming_examples/\nhttps://www.tutorialspoint.com/whiteboard.htm\nhttps://www.tutorialspoint.com/netmeeting.php\nhttps://www.tutorialspoint.com/articles/\nhttps://www.tutorialspoint.com/index.htm\nhttps://www.tutorialspoint.com/tutorialslibrary.htm\nhttps://www.tutorialspoint.com/videotutorials/index.htm\nhttps://store.tutorialspoint.com\nhttps://www.tutorialspoint.com/html_online_training/index.asp\nhttps://www.tutorialspoint.com/css_online_training/index.asp\nhttps://www.tutorialspoint.com/3d_animation_online_training/index.asp\nhttps://www.tutorialspoint.com/swift_4_online_training/index.asp\nhttps://www.tutorialspoint.com/blockchain_online_training/index.asp\nhttps://www.tutorialspoint.com/reactjs_online_training/index.asp\nhttps://www.tutorialspoint.com/tutorialslibrary.htm\nhttps://www.tutorialspoint.com/computer_fundamentals/index.htm\nhttps://www.tutorialspoint.com/compiler_design/index.htm\nhttps://www.tutorialspoint.com/operating_system/index.htm\nhttps://www.tutorialspoint.com/data_structures_algorithms/index.htm\nhttps://www.tutorialspoint.com/dbms/index.htm\nhttps://www.tutorialspoint.com/data_communication_computer_network/index.htm\nhttps://www.tutorialspoint.com/academic_tutorials.htm\nhttps://www.tutorialspoint.com/html/index.htm\nhttps://www.tutorialspoint.com/css/index.htm\nhttps://www.tutorialspoint.com/javascript/index.htm\nhttps://www.tutorialspoint.com/php/index.htm\nhttps://www.tutorialspoint.com/angular4/index.htm\nhttps://www.tutorialspoint.com/mysql/index.htm\nhttps://www.tutorialspoint.com/web_development_tutorials.htm\nhttps://www.tutorialspoint.com/cprogramming/index.htm\nhttps://www.tutorialspoint.com/cplusplus/index.htm\nhttps://www.tutorialspoint.com/java8/index.htm\nhttps://www.tutorialspoint.com/python/index.htm\nhttps://www.tutorialspoint.com/scala/index.htm\nhttps://www.tutorialspoint.com/csharp/index.htm\nhttps://www.tutorialspoint.com/computer_programming_tutorials.htm\nhttps://www.tutorialspoint.com/java8/index.htm\nhttps://www.tutorialspoint.com/jdbc/index.htm\nhttps://www.tutorialspoint.com/servlets/index.htm\nhttps://www.tutorialspoint.com/spring/index.htm\nhttps://www.tutorialspoint.com/hibernate/index.htm\nhttps://www.tutorialspoint.com/swing/index.htm\nhttps://www.tutorialspoint.com/java_technology_tutorials.htm\nhttps://www.tutorialspoint.com/android/index.htm\nhttps://www.tutorialspoint.com/swift/index.htm\nhttps://www.tutorialspoint.com/ios/index.htm\nhttps://www.tutorialspoint.com/kotlin/index.htm\nhttps://www.tutorialspoint.com/react_native/index.htm\nhttps://www.tutorialspoint.com/xamarin/index.htm\nhttps://www.tutorialspoint.com/mobile_development_tutorials.htm\nhttps://www.tutorialspoint.com/mongodb/index.htm\nhttps://www.tutorialspoint.com/plsql/index.htm\nhttps://www.tutorialspoint.com/sql/index.htm\nhttps://www.tutorialspoint.com/db2/index.htm\nhttps://www.tutorialspoint.com/mysql/index.htm\nhttps://www.tutorialspoint.com/memcached/index.htm\nhttps://www.tutorialspoint.com/database_tutorials.htm\nhttps://www.tutorialspoint.com/asp.net/index.htm\nhttps://www.tutorialspoint.com/entity_framework/index.htm\nhttps://www.tutorialspoint.com/vb.net/index.htm\nhttps://www.tutorialspoint.com/ms_project/index.htm\nhttps://www.tutorialspoint.com/excel/index.htm\nhttps://www.tutorialspoint.com/word/index.htm\nhttps://www.tutorialspoint.com/microsoft_technologies_tutorials.htm\nhttps://www.tutorialspoint.com/big_data_analytics/index.htm\nhttps://www.tutorialspoint.com/hadoop/index.htm\nhttps://www.tutorialspoint.com/sas/index.htm\nhttps://www.tutorialspoint.com/qlikview/index.htm\nhttps://www.tutorialspoint.com/power_bi/index.htm\nhttps://www.tutorialspoint.com/tableau/index.htm\nhttps://www.tutorialspoint.com/big_data_tutorials.htm\nhttps://www.tutorialspoint.com/tutorialslibrary.htm\nhttps://www.tutorialspoint.com/codingground.htm\nhttps://www.tutorialspoint.com/coding_platform_for_websites.htm\nhttps://www.tutorialspoint.com/developers_best_practices/index.htm\nhttps://www.tutorialspoint.com/effective_resume_writing.htm\nhttps://www.tutorialspoint.com/computer_glossary.htm\nhttps://www.tutorialspoint.com/computer_whoiswho.htm\nhttps://www.tutorialspoint.com/questions_and_answers.htm\nhttps://www.tutorialspoint.com/multi_language_tutorials.htm\nhttps://itunes.apple.com/us/app/tutorials-point/id914891263?ls=1&mt=8\nhttps://play.google.com/store/apps/details?id=com.tutorialspoint.onlineviewer\nhttp://www.windowsphone.com/s?appid=91249671-7184-4ad6-8a5f-d11847946b09\n/about/index.htm\n/about/about_team.htm\n/about/about_careers.htm\n/about/about_privacy.htm\n/about/about_terms_of_use.htm\nhttps://www.tutorialspoint.com/articles/\nhttps://www.tutorialspoint.com/online_dev_tools.htm\nhttps://www.tutorialspoint.com/free_web_graphics.htm\nhttps://www.tutorialspoint.com/online_file_conversion.htm\nhttps://www.tutorialspoint.com/shared-tutorials.php\nhttps://www.tutorialspoint.com/netmeeting.php\nhttps://www.tutorialspoint.com/free_online_whiteboard.htm\nhttp://www.tutorialspoint.com\nhttps://www.facebook.com/tutorialspointindia\nhttps://plus.google.com/u/0/+tutorialspoint\nhttp://www.twitter.com/tutorialspoint\nhttp://www.linkedin.com/company/tutorialspoint\nhttps://www.youtube.com/channel/UCVLbzhxVTiTLiVKeGV7WEBg\nhttps://www.tutorialspoint.com/index.htm\n/about/about_privacy.htm#cookies\n/about/faq.htm\n/about/about_helping.htm\n/about/contact_us.htm" }, { "code": null, "e": 12131, "s": 11893, "text": "Lxml − This is a parsing library, high-performance, production-quality HTML and XML parsing library. If we want high-quality, maximum speed, then we have to use this library. It has many module by which we can extract data from web site." }, { "code": null, "e": 12173, "s": 12131, "text": "For installing we write in Command prompt" }, { "code": null, "e": 12190, "s": 12173, "text": "pip install lxml" }, { "code": null, "e": 12441, "s": 12190, "text": "from lxml import etree\nmy_root_elem = etree.Element('html')\netree.SubElement(my_root_elem, 'head')\netree.SubElement(my_root_elem, 'title')\netree.SubElement(my_root_elem, 'body')\nprint(etree.tostring(my_root_elem, pretty_print = True).decode(\"utf-8\"))" }, { "code": null, "e": 12481, "s": 12441, "text": "<html>\n<head/>\n<title/>\n<body/>\n</html>" }, { "code": null, "e": 12737, "s": 12481, "text": "Selenium − This is an automates browsers tool, it is also known as web-drivers. When we use any website,we observe that sometimes we have to wait for some time, for example when we click any button or scrolling the page, in this moment Selenium is needed." }, { "code": null, "e": 12781, "s": 12737, "text": "For installing selenium we use this command" }, { "code": null, "e": 12802, "s": 12781, "text": "pip install selenium" }, { "code": null, "e": 13033, "s": 12802, "text": "from selenium import webdriver\nmy_path_to_chromedriver ='/Users/Admin/Desktop/chromedriver'\nmy_browser = webdriver.Chrome(executable_path = my_path_to_chromedriver)\nmy_url = 'https://www.tutorialspoint.com/'\nmy_browser.get(my_url)" }, { "code": null, "e": 13269, "s": 13033, "text": "MechanicalSoup − This is another Python library for automating interaction with websites. By using this we can automatically store and send cookies, can follow redirects, and can follow links and submit forms. It doesn’t do JavaScript." }, { "code": null, "e": 13313, "s": 13269, "text": "For installing we can use following command" }, { "code": null, "e": 13340, "s": 13313, "text": "pip install MechanicalSoup" }, { "code": null, "e": 13633, "s": 13340, "text": "import mechanicalsoup\nmy_browser = mechanicalsoup.StatefulBrowser()\nmy_value = my_browser.open(\"https://www.tutorialspoint.com/\")\nprint(my_value)\nmy_val = my_browser.get_url()\nprint(my_val)\nmy_va = my_browser.follow_link(\"forms\")\nprint(my_va)\nmy_value1 = my_browser.get_url()\nprint(my_value1)" } ]
Interesting Ways to Select Pandas DataFrame Columns | by Casey Whorton | Towards Data Science
Manipulating pandas data frames is a common task during exploratory analysis or preprocessing in a Data Science project. Filtering and sub-setting the data is also common. Over time, I have found myself needing to select columns based on different criteria. I hope readers find this article as a reference. If you want to use the data I used to test out these methods of selecting columns from a pandas data frame, use the code snippet below to get the wine dataset into your IDE or a notebook. from sklearn.datasets import load_wineimport pandas as pdimport numpy as npimport reX = load_wine()df = pd.DataFrame(X.data, columns = X.feature_names)df.head() Now, depending on what you want to do, check out each one of the code snippets below and try for yourself! This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. df['hue'] Passing a list in the brackets lets you select multiple columns at the same time. df[['alcohol','hue']] Similar to the previous example, but here you can search over all the columns in the dataframe. df[df.columns[df.columns.isin(['alcohol','hue','NON-EXISTANT COLUMN'])]] Let’s say you know what columns you don’t want in the dataframe. Pass those as a list to the difference method and you’ll get back everything except them. df[df.columns.difference([‘alcohol’,’hue’])] Return a data frame that has columns that are not in a list that you want to search over. df[df.columns[~df.columns.isin(['alcohol','hue'])]] Data types include ‘float64’ and ‘object’ and are inferred from the columns passed to the dtypes method. By matching on columns that are the same data type, you’ll get a series of True/False. Use the values method to get just the True/False values and not the index. df.loc[:,(df.dtypes=='float64').values] If you have tons of columns in a data frame and their column names all have a similar substring that you are interested in, you can return the columns who’s names contain a substring. Here we want everything that has the “al” substring in it. df.loc[:,['al' in i for i in df.columns]] You could have hundreds of columns, so it might make sense to find columns that match a pattern. Searching for column names that match a wildcard can be done with the “search” function from the re package (see the link in the reference section for more details on using the regular expression package). df.loc[:,[True if re.search('flava+',column) else False for column in df.columns]] If you want to select columns with names that start with a certain string, you can use the startswith method and pass it in the columns spot for the data frame location. df.loc[:,df.columns.str.startswith('al')] Same as the last example, but finds columns with names that end a certain way. df.loc[:,df.columns.str.endswith('oids')] You can pick columns if the rows meet a condition. Here, if all the the values in a column is greater than 14, we return the column from the data frame. df.loc[:,[(df[col] > 14).all() for col in df.columns]] Here, if any of the the values in a column is greater than 14, we return the column from the data frame. df.loc[:,[(df[col] > 14).any() for col in df.columns]] Here, if the mean of all the values in a column meet a condition, return the column. df.loc[:,[(df[col].mean() > 7) for col in df.columns]] Thanks for checking this out and feel free to reference it often.
[ { "code": null, "e": 479, "s": 172, "text": "Manipulating pandas data frames is a common task during exploratory analysis or preprocessing in a Data Science project. Filtering and sub-setting the data is also common. Over time, I have found myself needing to select columns based on different criteria. I hope readers find this article as a reference." }, { "code": null, "e": 667, "s": 479, "text": "If you want to use the data I used to test out these methods of selecting columns from a pandas data frame, use the code snippet below to get the wine dataset into your IDE or a notebook." }, { "code": null, "e": 828, "s": 667, "text": "from sklearn.datasets import load_wineimport pandas as pdimport numpy as npimport reX = load_wine()df = pd.DataFrame(X.data, columns = X.feature_names)df.head()" }, { "code": null, "e": 935, "s": 828, "text": "Now, depending on what you want to do, check out each one of the code snippets below and try for yourself!" }, { "code": null, "e": 1083, "s": 935, "text": "This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series." }, { "code": null, "e": 1093, "s": 1083, "text": "df['hue']" }, { "code": null, "e": 1175, "s": 1093, "text": "Passing a list in the brackets lets you select multiple columns at the same time." }, { "code": null, "e": 1197, "s": 1175, "text": "df[['alcohol','hue']]" }, { "code": null, "e": 1293, "s": 1197, "text": "Similar to the previous example, but here you can search over all the columns in the dataframe." }, { "code": null, "e": 1366, "s": 1293, "text": "df[df.columns[df.columns.isin(['alcohol','hue','NON-EXISTANT COLUMN'])]]" }, { "code": null, "e": 1521, "s": 1366, "text": "Let’s say you know what columns you don’t want in the dataframe. Pass those as a list to the difference method and you’ll get back everything except them." }, { "code": null, "e": 1566, "s": 1521, "text": "df[df.columns.difference([‘alcohol’,’hue’])]" }, { "code": null, "e": 1656, "s": 1566, "text": "Return a data frame that has columns that are not in a list that you want to search over." }, { "code": null, "e": 1708, "s": 1656, "text": "df[df.columns[~df.columns.isin(['alcohol','hue'])]]" }, { "code": null, "e": 1975, "s": 1708, "text": "Data types include ‘float64’ and ‘object’ and are inferred from the columns passed to the dtypes method. By matching on columns that are the same data type, you’ll get a series of True/False. Use the values method to get just the True/False values and not the index." }, { "code": null, "e": 2015, "s": 1975, "text": "df.loc[:,(df.dtypes=='float64').values]" }, { "code": null, "e": 2258, "s": 2015, "text": "If you have tons of columns in a data frame and their column names all have a similar substring that you are interested in, you can return the columns who’s names contain a substring. Here we want everything that has the “al” substring in it." }, { "code": null, "e": 2300, "s": 2258, "text": "df.loc[:,['al' in i for i in df.columns]]" }, { "code": null, "e": 2603, "s": 2300, "text": "You could have hundreds of columns, so it might make sense to find columns that match a pattern. Searching for column names that match a wildcard can be done with the “search” function from the re package (see the link in the reference section for more details on using the regular expression package)." }, { "code": null, "e": 2686, "s": 2603, "text": "df.loc[:,[True if re.search('flava+',column) else False for column in df.columns]]" }, { "code": null, "e": 2856, "s": 2686, "text": "If you want to select columns with names that start with a certain string, you can use the startswith method and pass it in the columns spot for the data frame location." }, { "code": null, "e": 2898, "s": 2856, "text": "df.loc[:,df.columns.str.startswith('al')]" }, { "code": null, "e": 2977, "s": 2898, "text": "Same as the last example, but finds columns with names that end a certain way." }, { "code": null, "e": 3019, "s": 2977, "text": "df.loc[:,df.columns.str.endswith('oids')]" }, { "code": null, "e": 3172, "s": 3019, "text": "You can pick columns if the rows meet a condition. Here, if all the the values in a column is greater than 14, we return the column from the data frame." }, { "code": null, "e": 3227, "s": 3172, "text": "df.loc[:,[(df[col] > 14).all() for col in df.columns]]" }, { "code": null, "e": 3332, "s": 3227, "text": "Here, if any of the the values in a column is greater than 14, we return the column from the data frame." }, { "code": null, "e": 3387, "s": 3332, "text": "df.loc[:,[(df[col] > 14).any() for col in df.columns]]" }, { "code": null, "e": 3472, "s": 3387, "text": "Here, if the mean of all the values in a column meet a condition, return the column." }, { "code": null, "e": 3527, "s": 3472, "text": "df.loc[:,[(df[col].mean() > 7) for col in df.columns]]" } ]
Find all pairs (a, b) in an array such that a % b = k - GeeksforGeeks
01 Feb, 2022 Given an array with distinct elements, the task is to find the pairs in the array such that a % b = k, where k is a given integer. Examples : Input : arr[] = {2, 3, 5, 4, 7} k = 3 Output : (7, 4), (3, 4), (3, 5), (3, 7) 7 % 4 = 3 3 % 4 = 3 3 % 5 = 3 3 % 7 = 3 A Naive Solution is to make all pairs one by one and check their modulo is equal to k or not. If equals to k, then print that pair. C++ Java Python3 C# PHP Javascript // C++ implementation to find such pairs#include <bits/stdc++.h>using namespace std; // Function to find pair such that (a % b = k)bool printPairs(int arr[], int n, int k){ bool isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { cout << "(" << arr[i] << ", " << arr[j] << ")" << " "; isPairFound = true; } } } return isPairFound;} // Driver programint main(){ int arr[] = { 2, 3, 5, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; if (printPairs(arr, n, k) == false) cout << "No such pair exists"; return 0;} // Java implementation to find such pairs class Test { // method to find pair such that (a % b = k) static boolean printPairs(int arr[], int n, int k) { boolean isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { System.out.print("(" + arr[i] + ", " + arr[j] + ")" + " "); isPairFound = true; } } } return isPairFound; } // Driver method public static void main(String args[]) { int arr[] = { 2, 3, 5, 4, 7 }; int k = 3; if (printPairs(arr, arr.length, k) == false) System.out.println("No such pair exists"); }} # Python3 implementation to find such pairs # Function to find pair such that (a % b = k)def printPairs(arr, n, k): isPairFound = True # Consider each and every pair for i in range(0, n): for j in range(0, n): # Print if their modulo equals to k if (i != j and arr[i] % arr[j] == k): print("(", arr[i], ", ", arr[j], ")", sep = "", end = " ") isPairFound = True return isPairFound # Driver Codearr = [2, 3, 5, 4, 7]n = len(arr)k = 3if (printPairs(arr, n, k) == False): print("No such pair exists") # This article is contributed by Smitha Dinesh Semwal. // C# implementation to find such pairusing System; public class GFG { // method to find pair such that (a % b = k) static bool printPairs(int[] arr, int n, int k) { bool isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { Console.Write("(" + arr[i] + ", " + arr[j] + ")" + " "); isPairFound = true; } } } return isPairFound; } // Driver method public static void Main() { int[] arr = { 2, 3, 5, 4, 7 }; int k = 3; if (printPairs(arr, arr.Length, k) == false) Console.WriteLine("No such pair exists"); }} // This code is contributed by Sam007 <?php// PHP implementation to// find such pairs // Function to find pair// such that (a % b = k)function printPairs($arr, $n, $k){ $isPairFound = true; // Consider each and every pair for ($i = 0; $i < $n; $i++) { for ( $j = 0; $j < $n; $j++) { // Print if their modulo // equals to k if ($i != $j && $arr[$i] % $arr[$j] == $k) { echo "(" , $arr[$i] , ", ", $arr[$j] , ")", " "; $isPairFound = true; } } } return $isPairFound;} // Driver Code$arr = array(2, 3, 5, 4, 7);$n = sizeof($arr);$k = 3; if (printPairs($arr, $n, $k) == false) echo "No such pair exists"; // This code is contributed by ajit?> <script> // Javascript implementation to find such pair // method to find pair such that (a % b = k) function printPairs(arr, n, k) { let isPairFound = true; // Consider each and every pair for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { document.write("(" + arr[i] + ", " + arr[j] + ")" + " "); isPairFound = true; } } } return isPairFound; } let arr = [ 2, 3, 5, 4, 7 ]; let k = 3; if (printPairs(arr, arr.length, k) == false) document.write("No such pair exists"); </script> Output: (3, 5) (3, 4) (3, 7) (7, 4) Time Complexity : O(n2)An Efficient solution is based on below observations : If k itself is present in arr[], then k forms a pair with all elements arr[i] where k < arr[i]. For all such arr[i], we have k % arr[i] = k.For all elements greater than or equal to k, we use the following fact. If k itself is present in arr[], then k forms a pair with all elements arr[i] where k < arr[i]. For all such arr[i], we have k % arr[i] = k. For all elements greater than or equal to k, we use the following fact. If arr[i] % arr[j] = k, ==> arr[i] = x * arr[j] + k ==> (arr[i] - k) = x * arr[j] We find all divisors of (arr[i] - k) and see if they are present in arr[]. To quickly check if an element is present in the array, we use hashing. C++ Java Python3 C# Javascript // C++ program to find all pairs such that// a % b = k.#include <bits/stdc++.h>using namespace std; // Utility function to find the divisors of// n and store in vector v[]vector<int> findDivisors(int n){ vector<int> v; // Vector is used to store the divisors for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.push_back(i); else { v.push_back(i); v.push_back(n / i); } } } return v;} // Function to find pairs such that (a%b = k)bool printPairs(int arr[], int n, int k){ // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. unordered_map<int, bool> occ; for (int i = 0; i < n; i++) occ[arr[i]] = true; bool isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] && k < arr[i]) { cout << "(" << k << ", " << arr[i] << ") "; isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) vector<int> v = findDivisors(arr[i] - k); // Check for each divisor i.e. arr[i] % b = k // or not, if yes then print that pair. for (int j = 0; j < v.size(); j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) { cout << "(" << arr[i] << ", " << v[j] << ") "; isPairFound = true; } } // Clear vector v.clear(); } } return isPairFound;} // Driver programint main(){ int arr[] = { 3, 1, 2, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; if (printPairs(arr, n, k) == false) cout << "No such pair exists"; return 0;} // Java program to find all pairs such that// a % b = k. import java.util.HashMap;import java.util.Vector; class Test { // Utility method to find the divisors of // n and store in vector v[] static Vector<Integer> findDivisors(int n) { Vector<Integer> v = new Vector<>(); // Vector is used to store the divisors for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.add(i); else { v.add(i); v.add(n / i); } } } return v; } // method to find pairs such that (a%b = k) static boolean printPairs(int arr[], int n, int k) { // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. HashMap<Integer, Boolean> occ = new HashMap<>(); for (int i = 0; i < n; i++) occ.put(arr[i], true); boolean isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ.get(k) && k < arr[i]) { System.out.print("(" + k + ", " + arr[i] + ") "); isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) Vector<Integer> v = findDivisors(arr[i] - k); // Check for each divisor i.e. arr[i] % b = k // or not, if yes then print that pair. for (int j = 0; j < v.size(); j++) { if (arr[i] % v.get(j) == k && arr[i] != v.get(j) && occ.get(v.get(j))) { System.out.print("(" + arr[i] + ", " + v.get(j) + ") "); isPairFound = true; } } // Clear vector v.clear(); } } return isPairFound; } // Driver method public static void main(String args[]) { int arr[] = { 3, 1, 2, 5, 4 }; int k = 2; if (printPairs(arr, arr.length, k) == false) System.out.println("No such pair exists"); }} # Python3 program to find all pairs# such that a % b = k. # Utility function to find the divisors# of n and store in vector v[]import math as mt def findDivisors(n): v = [] # Vector is used to store the divisors for i in range(1, mt.floor(n**(.5)) + 1): if (n % i == 0): # If n is a square number, push # only one occurrence if (n / i == i): v.append(i) else: v.append(i) v.append(n // i) return v # Function to find pairs such that (a%b = k)def printPairs(arr, n, k): # Store all the elements in the map # to use map as hash for finding elements # in O(1) time. occ = dict() for i in range(n): occ[arr[i]] = True isPairFound = False for i in range(n): # Print all the pairs with (a, b) as # (k, numbers greater than k) as # k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] and k < arr[i]): print("(", k, ",", arr[i], ")", end = " ") isPairFound = True # Now check for the current element as 'a' # how many b exists such that a%b = k if (arr[i] >= k): # find all the divisors of (arr[i]-k) v = findDivisors(arr[i] - k) # Check for each divisor i.e. arr[i] % b = k # or not, if yes then print that pair. for j in range(len(v)): if (arr[i] % v[j] == k and arr[i] != v[j] and occ[v[j]]): print("(", arr[i], ",", v[j], ")", end = " ") isPairFound = True return isPairFound # Driver Codearr = [3, 1, 2, 5, 4]n = len(arr)k = 2 if (printPairs(arr, n, k) == False): print("No such pair exists") # This code is contributed by mohit kumar // C# program to find all pairs// such that a % b = k.using System;using System.Collections.Generic; class GFG{// Utility method to find the divisors// of n and store in vector v[]public static List<int> findDivisors(int n){ List<int> v = new List<int>(); // Vector is used to store // the divisors for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { // If n is a square number, // push only one occurrence if (n / i == i) { v.Add(i); } else { v.Add(i); v.Add(n / i); } } } return v;} // method to find pairs such// that (a%b = k)public static bool printPairs(int[] arr, int n, int k){ // Store all the elements in the // map to use map as hash for // finding elements in O(1) time. Dictionary<int, bool> occ = new Dictionary<int, bool>(); for (int i = 0; i < n; i++) { occ[arr[i]] = true; } bool isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] && k < arr[i]) { Console.Write("(" + k + ", " + arr[i] + ") "); isPairFound = true; } // Now check for the current element // as 'a' how many b exists such that // a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) List<int> v = findDivisors(arr[i] - k); // Check for each divisor i.e. // arr[i] % b = k or not, if // yes then print that pair. for (int j = 0; j < v.Count; j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) { Console.Write("(" + arr[i] + ", " + v[j] + ") "); isPairFound = true; } } // Clear vector v.Clear(); } } return isPairFound;} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {3, 1, 2, 5, 4}; int k = 2; if (printPairs(arr, arr.Length, k) == false) { Console.WriteLine("No such pair exists"); }}} // This code is contributed by Shrikant13 <script> // JavaScript program to find all pairs such that// a % b = k. // Utility method to find the divisors of // n and store in vector v[] function findDivisors(n) { let v = []; // Vector is used to store the divisors for (let i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.push(i); else { v.push(i); v.push(Math.floor(n / i)); } } } return v; } // method to find pairs such that (a%b = k) function printPairs(arr,n,k) { // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. let occ = new Map(); for (let i = 0; i < n; i++) occ.set(arr[i], true); let isPairFound = false; for (let i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ.get(k) && k < arr[i]) { document.write("(" + k + ", " + arr[i] + ") "); isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) let v = findDivisors(arr[i] - k); // Check for each divisor // i.e. arr[i] % b = k // or not, if yes then // print that pair. for (let j = 0; j < v.length; j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ.get(v[j])) { document.write("(" + arr[i] + ", " + v[j] + ") "); isPairFound = true; } } // Clear vector v=[]; } } return isPairFound; } // Driver method let arr=[3, 1, 2, 5, 4 ]; let k = 2; if (printPairs(arr, arr.length, k) == false) document.write("No such pair exists"); // This code is contributed by unknown2108 </script> Output: (2, 3) (2, 5) (5, 3) (2, 4) Time Complexity: O(n* sqrt(max)) where max is the maximum element in the array.Reference: https://stackoverflow.com/questions/12732939/find-pairs-in-an-array-such-that-ab-k-where-k-is-a-given-integer This article is contributed by Sahil Chhabra. 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. Sam007 jit_t shrikanth13 mohit kumar 29 Akanksha_Rai nidhi_biet suresh07 unknown2108 debbunny98 sumitgumber28 simmytarika5 Modular Arithmetic Arrays Hash Arrays Hash Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Introduction to Arrays Multidimensional Arrays in Java Linear Search Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Hashing | Set 2 (Separate Chaining) Counting frequencies of array elements
[ { "code": null, "e": 24787, "s": 24759, "text": "\n01 Feb, 2022" }, { "code": null, "e": 24918, "s": 24787, "text": "Given an array with distinct elements, the task is to find the pairs in the array such that a % b = k, where k is a given integer." }, { "code": null, "e": 24930, "s": 24918, "text": "Examples : " }, { "code": null, "e": 25068, "s": 24930, "text": "Input : arr[] = {2, 3, 5, 4, 7} \n k = 3\nOutput : (7, 4), (3, 4), (3, 5), (3, 7)\n7 % 4 = 3\n3 % 4 = 3\n3 % 5 = 3\n3 % 7 = 3" }, { "code": null, "e": 25202, "s": 25068, "text": "A Naive Solution is to make all pairs one by one and check their modulo is equal to k or not. If equals to k, then print that pair. " }, { "code": null, "e": 25206, "s": 25202, "text": "C++" }, { "code": null, "e": 25211, "s": 25206, "text": "Java" }, { "code": null, "e": 25219, "s": 25211, "text": "Python3" }, { "code": null, "e": 25222, "s": 25219, "text": "C#" }, { "code": null, "e": 25226, "s": 25222, "text": "PHP" }, { "code": null, "e": 25237, "s": 25226, "text": "Javascript" }, { "code": "// C++ implementation to find such pairs#include <bits/stdc++.h>using namespace std; // Function to find pair such that (a % b = k)bool printPairs(int arr[], int n, int k){ bool isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { cout << \"(\" << arr[i] << \", \" << arr[j] << \")\" << \" \"; isPairFound = true; } } } return isPairFound;} // Driver programint main(){ int arr[] = { 2, 3, 5, 4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; if (printPairs(arr, n, k) == false) cout << \"No such pair exists\"; return 0;}", "e": 26049, "s": 25237, "text": null }, { "code": "// Java implementation to find such pairs class Test { // method to find pair such that (a % b = k) static boolean printPairs(int arr[], int n, int k) { boolean isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { System.out.print(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \" \"); isPairFound = true; } } } return isPairFound; } // Driver method public static void main(String args[]) { int arr[] = { 2, 3, 5, 4, 7 }; int k = 3; if (printPairs(arr, arr.length, k) == false) System.out.println(\"No such pair exists\"); }}", "e": 26932, "s": 26049, "text": null }, { "code": "# Python3 implementation to find such pairs # Function to find pair such that (a % b = k)def printPairs(arr, n, k): isPairFound = True # Consider each and every pair for i in range(0, n): for j in range(0, n): # Print if their modulo equals to k if (i != j and arr[i] % arr[j] == k): print(\"(\", arr[i], \", \", arr[j], \")\", sep = \"\", end = \" \") isPairFound = True return isPairFound # Driver Codearr = [2, 3, 5, 4, 7]n = len(arr)k = 3if (printPairs(arr, n, k) == False): print(\"No such pair exists\") # This article is contributed by Smitha Dinesh Semwal.", "e": 27633, "s": 26932, "text": null }, { "code": "// C# implementation to find such pairusing System; public class GFG { // method to find pair such that (a % b = k) static bool printPairs(int[] arr, int n, int k) { bool isPairFound = true; // Consider each and every pair for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { Console.Write(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \" \"); isPairFound = true; } } } return isPairFound; } // Driver method public static void Main() { int[] arr = { 2, 3, 5, 4, 7 }; int k = 3; if (printPairs(arr, arr.Length, k) == false) Console.WriteLine(\"No such pair exists\"); }} // This code is contributed by Sam007", "e": 28573, "s": 27633, "text": null }, { "code": "<?php// PHP implementation to// find such pairs // Function to find pair// such that (a % b = k)function printPairs($arr, $n, $k){ $isPairFound = true; // Consider each and every pair for ($i = 0; $i < $n; $i++) { for ( $j = 0; $j < $n; $j++) { // Print if their modulo // equals to k if ($i != $j && $arr[$i] % $arr[$j] == $k) { echo \"(\" , $arr[$i] , \", \", $arr[$j] , \")\", \" \"; $isPairFound = true; } } } return $isPairFound;} // Driver Code$arr = array(2, 3, 5, 4, 7);$n = sizeof($arr);$k = 3; if (printPairs($arr, $n, $k) == false) echo \"No such pair exists\"; // This code is contributed by ajit?>", "e": 29352, "s": 28573, "text": null }, { "code": "<script> // Javascript implementation to find such pair // method to find pair such that (a % b = k) function printPairs(arr, n, k) { let isPairFound = true; // Consider each and every pair for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { // Print if their modulo equals to k if (i != j && arr[i] % arr[j] == k) { document.write(\"(\" + arr[i] + \", \" + arr[j] + \")\" + \" \"); isPairFound = true; } } } return isPairFound; } let arr = [ 2, 3, 5, 4, 7 ]; let k = 3; if (printPairs(arr, arr.length, k) == false) document.write(\"No such pair exists\"); </script>", "e": 30129, "s": 29352, "text": null }, { "code": null, "e": 30139, "s": 30129, "text": "Output: " }, { "code": null, "e": 30167, "s": 30139, "text": "(3, 5) (3, 4) (3, 7) (7, 4)" }, { "code": null, "e": 30246, "s": 30167, "text": "Time Complexity : O(n2)An Efficient solution is based on below observations : " }, { "code": null, "e": 30458, "s": 30246, "text": "If k itself is present in arr[], then k forms a pair with all elements arr[i] where k < arr[i]. For all such arr[i], we have k % arr[i] = k.For all elements greater than or equal to k, we use the following fact." }, { "code": null, "e": 30599, "s": 30458, "text": "If k itself is present in arr[], then k forms a pair with all elements arr[i] where k < arr[i]. For all such arr[i], we have k % arr[i] = k." }, { "code": null, "e": 30671, "s": 30599, "text": "For all elements greater than or equal to k, we use the following fact." }, { "code": null, "e": 30842, "s": 30671, "text": " If arr[i] % arr[j] = k, \n ==> arr[i] = x * arr[j] + k\n ==> (arr[i] - k) = x * arr[j]\n We find all divisors of (arr[i] - k)\n and see if they are present in arr[]." }, { "code": null, "e": 30915, "s": 30842, "text": "To quickly check if an element is present in the array, we use hashing. " }, { "code": null, "e": 30919, "s": 30915, "text": "C++" }, { "code": null, "e": 30924, "s": 30919, "text": "Java" }, { "code": null, "e": 30932, "s": 30924, "text": "Python3" }, { "code": null, "e": 30935, "s": 30932, "text": "C#" }, { "code": null, "e": 30946, "s": 30935, "text": "Javascript" }, { "code": "// C++ program to find all pairs such that// a % b = k.#include <bits/stdc++.h>using namespace std; // Utility function to find the divisors of// n and store in vector v[]vector<int> findDivisors(int n){ vector<int> v; // Vector is used to store the divisors for (int i = 1; i <= sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.push_back(i); else { v.push_back(i); v.push_back(n / i); } } } return v;} // Function to find pairs such that (a%b = k)bool printPairs(int arr[], int n, int k){ // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. unordered_map<int, bool> occ; for (int i = 0; i < n; i++) occ[arr[i]] = true; bool isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] && k < arr[i]) { cout << \"(\" << k << \", \" << arr[i] << \") \"; isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) vector<int> v = findDivisors(arr[i] - k); // Check for each divisor i.e. arr[i] % b = k // or not, if yes then print that pair. for (int j = 0; j < v.size(); j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) { cout << \"(\" << arr[i] << \", \" << v[j] << \") \"; isPairFound = true; } } // Clear vector v.clear(); } } return isPairFound;} // Driver programint main(){ int arr[] = { 3, 1, 2, 5, 4 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 2; if (printPairs(arr, n, k) == false) cout << \"No such pair exists\"; return 0;}", "e": 33059, "s": 30946, "text": null }, { "code": "// Java program to find all pairs such that// a % b = k. import java.util.HashMap;import java.util.Vector; class Test { // Utility method to find the divisors of // n and store in vector v[] static Vector<Integer> findDivisors(int n) { Vector<Integer> v = new Vector<>(); // Vector is used to store the divisors for (int i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.add(i); else { v.add(i); v.add(n / i); } } } return v; } // method to find pairs such that (a%b = k) static boolean printPairs(int arr[], int n, int k) { // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. HashMap<Integer, Boolean> occ = new HashMap<>(); for (int i = 0; i < n; i++) occ.put(arr[i], true); boolean isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ.get(k) && k < arr[i]) { System.out.print(\"(\" + k + \", \" + arr[i] + \") \"); isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) Vector<Integer> v = findDivisors(arr[i] - k); // Check for each divisor i.e. arr[i] % b = k // or not, if yes then print that pair. for (int j = 0; j < v.size(); j++) { if (arr[i] % v.get(j) == k && arr[i] != v.get(j) && occ.get(v.get(j))) { System.out.print(\"(\" + arr[i] + \", \" + v.get(j) + \") \"); isPairFound = true; } } // Clear vector v.clear(); } } return isPairFound; } // Driver method public static void main(String args[]) { int arr[] = { 3, 1, 2, 5, 4 }; int k = 2; if (printPairs(arr, arr.length, k) == false) System.out.println(\"No such pair exists\"); }}", "e": 35552, "s": 33059, "text": null }, { "code": "# Python3 program to find all pairs# such that a % b = k. # Utility function to find the divisors# of n and store in vector v[]import math as mt def findDivisors(n): v = [] # Vector is used to store the divisors for i in range(1, mt.floor(n**(.5)) + 1): if (n % i == 0): # If n is a square number, push # only one occurrence if (n / i == i): v.append(i) else: v.append(i) v.append(n // i) return v # Function to find pairs such that (a%b = k)def printPairs(arr, n, k): # Store all the elements in the map # to use map as hash for finding elements # in O(1) time. occ = dict() for i in range(n): occ[arr[i]] = True isPairFound = False for i in range(n): # Print all the pairs with (a, b) as # (k, numbers greater than k) as # k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] and k < arr[i]): print(\"(\", k, \",\", arr[i], \")\", end = \" \") isPairFound = True # Now check for the current element as 'a' # how many b exists such that a%b = k if (arr[i] >= k): # find all the divisors of (arr[i]-k) v = findDivisors(arr[i] - k) # Check for each divisor i.e. arr[i] % b = k # or not, if yes then print that pair. for j in range(len(v)): if (arr[i] % v[j] == k and arr[i] != v[j] and occ[v[j]]): print(\"(\", arr[i], \",\", v[j], \")\", end = \" \") isPairFound = True return isPairFound # Driver Codearr = [3, 1, 2, 5, 4]n = len(arr)k = 2 if (printPairs(arr, n, k) == False): print(\"No such pair exists\") # This code is contributed by mohit kumar", "e": 37434, "s": 35552, "text": null }, { "code": "// C# program to find all pairs// such that a % b = k.using System;using System.Collections.Generic; class GFG{// Utility method to find the divisors// of n and store in vector v[]public static List<int> findDivisors(int n){ List<int> v = new List<int>(); // Vector is used to store // the divisors for (int i = 1; i <= Math.Sqrt(n); i++) { if (n % i == 0) { // If n is a square number, // push only one occurrence if (n / i == i) { v.Add(i); } else { v.Add(i); v.Add(n / i); } } } return v;} // method to find pairs such// that (a%b = k)public static bool printPairs(int[] arr, int n, int k){ // Store all the elements in the // map to use map as hash for // finding elements in O(1) time. Dictionary<int, bool> occ = new Dictionary<int, bool>(); for (int i = 0; i < n; i++) { occ[arr[i]] = true; } bool isPairFound = false; for (int i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ[k] && k < arr[i]) { Console.Write(\"(\" + k + \", \" + arr[i] + \") \"); isPairFound = true; } // Now check for the current element // as 'a' how many b exists such that // a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) List<int> v = findDivisors(arr[i] - k); // Check for each divisor i.e. // arr[i] % b = k or not, if // yes then print that pair. for (int j = 0; j < v.Count; j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ[v[j]]) { Console.Write(\"(\" + arr[i] + \", \" + v[j] + \") \"); isPairFound = true; } } // Clear vector v.Clear(); } } return isPairFound;} // Driver Codepublic static void Main(string[] args){ int[] arr = new int[] {3, 1, 2, 5, 4}; int k = 2; if (printPairs(arr, arr.Length, k) == false) { Console.WriteLine(\"No such pair exists\"); }}} // This code is contributed by Shrikant13", "e": 39946, "s": 37434, "text": null }, { "code": "<script> // JavaScript program to find all pairs such that// a % b = k. // Utility method to find the divisors of // n and store in vector v[] function findDivisors(n) { let v = []; // Vector is used to store the divisors for (let i = 1; i <= Math.sqrt(n); i++) { if (n % i == 0) { // If n is a square number, push // only one occurrence if (n / i == i) v.push(i); else { v.push(i); v.push(Math.floor(n / i)); } } } return v; } // method to find pairs such that (a%b = k) function printPairs(arr,n,k) { // Store all the elements in the map // to use map as hash for finding elements // in O(1) time. let occ = new Map(); for (let i = 0; i < n; i++) occ.set(arr[i], true); let isPairFound = false; for (let i = 0; i < n; i++) { // Print all the pairs with (a, b) as // (k, numbers greater than k) as // k % (num (> k)) = k i.e. 2%4 = 2 if (occ.get(k) && k < arr[i]) { document.write(\"(\" + k + \", \" + arr[i] + \") \"); isPairFound = true; } // Now check for the current element as 'a' // how many b exists such that a%b = k if (arr[i] >= k) { // find all the divisors of (arr[i]-k) let v = findDivisors(arr[i] - k); // Check for each divisor // i.e. arr[i] % b = k // or not, if yes then // print that pair. for (let j = 0; j < v.length; j++) { if (arr[i] % v[j] == k && arr[i] != v[j] && occ.get(v[j])) { document.write(\"(\" + arr[i] + \", \" + v[j] + \") \"); isPairFound = true; } } // Clear vector v=[]; } } return isPairFound; } // Driver method let arr=[3, 1, 2, 5, 4 ]; let k = 2; if (printPairs(arr, arr.length, k) == false) document.write(\"No such pair exists\"); // This code is contributed by unknown2108 </script>", "e": 42408, "s": 39946, "text": null }, { "code": null, "e": 42418, "s": 42408, "text": "Output: " }, { "code": null, "e": 42446, "s": 42418, "text": "(2, 3) (2, 5) (5, 3) (2, 4)" }, { "code": null, "e": 42646, "s": 42446, "text": "Time Complexity: O(n* sqrt(max)) where max is the maximum element in the array.Reference: https://stackoverflow.com/questions/12732939/find-pairs-in-an-array-such-that-ab-k-where-k-is-a-given-integer" }, { "code": null, "e": 43068, "s": 42646, "text": "This article is contributed by Sahil Chhabra. 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": 43075, "s": 43068, "text": "Sam007" }, { "code": null, "e": 43081, "s": 43075, "text": "jit_t" }, { "code": null, "e": 43093, "s": 43081, "text": "shrikanth13" }, { "code": null, "e": 43108, "s": 43093, "text": "mohit kumar 29" }, { "code": null, "e": 43121, "s": 43108, "text": "Akanksha_Rai" }, { "code": null, "e": 43132, "s": 43121, "text": "nidhi_biet" }, { "code": null, "e": 43141, "s": 43132, "text": "suresh07" }, { "code": null, "e": 43153, "s": 43141, "text": "unknown2108" }, { "code": null, "e": 43164, "s": 43153, "text": "debbunny98" }, { "code": null, "e": 43178, "s": 43164, "text": "sumitgumber28" }, { "code": null, "e": 43191, "s": 43178, "text": "simmytarika5" }, { "code": null, "e": 43210, "s": 43191, "text": "Modular Arithmetic" }, { "code": null, "e": 43217, "s": 43210, "text": "Arrays" }, { "code": null, "e": 43222, "s": 43217, "text": "Hash" }, { "code": null, "e": 43229, "s": 43222, "text": "Arrays" }, { "code": null, "e": 43234, "s": 43229, "text": "Hash" }, { "code": null, "e": 43253, "s": 43234, "text": "Modular Arithmetic" }, { "code": null, "e": 43351, "s": 43253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43360, "s": 43351, "text": "Comments" }, { "code": null, "e": 43373, "s": 43360, "text": "Old Comments" }, { "code": null, "e": 43421, "s": 43373, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 43465, "s": 43421, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 43488, "s": 43465, "text": "Introduction to Arrays" }, { "code": null, "e": 43520, "s": 43488, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 43534, "s": 43520, "text": "Linear Search" }, { "code": null, "e": 43570, "s": 43534, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 43601, "s": 43570, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 43635, "s": 43601, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 43671, "s": 43635, "text": "Hashing | Set 2 (Separate Chaining)" } ]
Hands on Churn Prediction with R and comparison of Different Models for Churn Prediction | by Aashiq Reza | Towards Data Science
What is Churn ? Churn rate, when applied to a customer base, refers to the proportion of contractual customers or subscribers who leave a supplier during a given time period.(wikipedia) Why Churn Prediction is important? Churn is directly related to the profitability of a company. The more some can learn about customer behaviors, the more profit can be gained. This also helps identifying and improving areas or fields where customer service is lacking. The data was collected from IBM. Firstly load the libraries required and the data and take a look on the data. library(tidyverse)library(caret)library(repr)library(caTools)library(rpart)library(rpart.plot)library(ggpubr)# input the data and take a look on the variablesdata <- read.csv("telco.csv")glimpse(data)data <- data[complete.cases(data),] # removing na's About the Data: In this data, all the rows represents different customer and each column represents their attributes. The column Churn indicates customers leaving on the last month. Customers’ subscription to the services — phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies. Account informations of each customer — contract, payment method, paperless billing, monthly charges, and total charges. Demographic informations — gender, age range, and if they have partners and dependents Data Wrangling: Terms like “No internet service” and “No phone service” should be changed to “No” for convenience. Terms like “No internet service” and “No phone service” should be changed to “No” for convenience. data <- data.frame(lapply(data, function(x) { gsub("No internet service", "No", x)}))data <- data.frame(lapply(data, function(x) { gsub("No phone service", "No", x)})) 2. SeniorCitizen responds in 1 and 0, which is changed to “Yes” or “No”. data$SeniorCitizen <- as.factor(ifelse(data$SeniorCitizen==1, 'YES', 'NO')) 3. Convert double type variables into numeric type and store them in a variable as a data frame. num_columns <- c("tenure", "MonthlyCharges", "TotalCharges")data[num_columns] <- sapply(data[num_columns], as.numeric)data_int <- data[,c("tenure", "MonthlyCharges", "TotalCharges")]data_int <- data.frame(scale(data_int)) 4. Tenure is in months. We should convert it into years. data <- mutate(data, tenure_year = tenure)data$tenure_year[data$tenure_year >=0 & data$tenure_year <= 12] <- '0-1 year'data$tenure_year[data$tenure_year > 12 & data$tenure_year <= 24] <- '1-2 years'data$tenure_year[data$tenure_year > 24 & data$tenure_year <= 36] <- '2-3 years'data$tenure_year[data$tenure_year > 36 & data$tenure_year <= 48] <- '3-4 years'data$tenure_year[data$tenure_year > 48 & data$tenure_year <= 60] <- '4-5 years'data$tenure_year[data$tenure_year > 60 & data$tenure_year <= 72] <- '5-6 years'data$tenure_year <- as.factor(data$tenure_year) 5. Prepare the final data for analysis excluding selected variables which we don’t need throughout the analsis process. data$tenure_year <- as.factor(data$tenure_year)data_req <- data[,-c(1,6,19,20)]x <- data.frame(sapply(data_req,function(x) data.frame(model.matrix(~x-1,data =data_req))[,-1]))x <- na.omit(x) # omit the NA'sdata_int <- na.omit(data_int) # omit the NA'sdata_final <- cbind(x, data_int) Correlation plot between the numeric variables: Correlation plot between the numeric variables: nv <- sapply(data_int, is.numeric)cormat <- cor(data_int[,nv])ggcorrplot::ggcorrplot(cormat, title = "Correlation of Numeric Variables") 2. Churn percentage tells around 26.58% of the customer left during last month. churn <- data %>% group_by(Churn) %>% summarise(Count = n())%>% mutate(percentage = prop.table(Count)*100)ggplot(churn, aes(reorder(Churn, -percentage), percentage), fill = Churn)+ geom_col(fill = c("green", "red"))+ geom_text(aes(label = sprintf("%.2f%%", percentage)))+ xlab("Churn") + ylab("Percent")+ ggtitle("Churn Percentage") 3. Bar plots to show churn rate in categorical variables. fig1 <- ggarrange(ggplot(data, aes(x=gender,fill=Churn))+ geom_bar() , ggplot(data, aes(x=SeniorCitizen,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=Partner,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=Dependents,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=PhoneService,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=MultipleLines,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=InternetService,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=OnlineSecurity,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=OnlineBackup,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=DeviceProtection,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=TechSupport,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=StreamingTV,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=StreamingMovies,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=Contract,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=PaperlessBilling,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=PaymentMethod,fill=Churn))+geom_bar(position = 'fill')+theme_bw()+ rremove("x.text"), ncol = 3, nrow = 6, common.legend = TRUE, legend = "bottom")annotate_figure(fig1, bottom = text_grob("Churn Percentage in categorical variables", col = "blue", face = "bold", size = 14)) 4. Bar plot to show churn percentage in numeric variables. fig2 <- ggarrange( ggplot(data, aes(y= tenure, x = "", fill = Churn))+geom_boxplot() + xlab(" "), ggplot(data, aes(y= MonthlyCharges, x = "", fill = Churn)) +geom_boxplot() + xlab(" "), ggplot(data, aes(y= TotalCharges, x = "", fill = Churn)) +geom_boxplot() + xlab(" "), rremove("x.text"), ncol = 2, nrow = 2, common.legend = TRUE, legend = "bottom")annotate_figure(fig2, bottom = text_grob("Churn Percentage in numeric variables", col = "red", face = "bold", size = 14)) Split the data in train and test sets Split the data in train and test sets set.seed(123)split <- sample.split(data_final$Churn, SplitRatio = 0.70)train <- data_final[split,]test <- data_final[!(split),] 2. Calculate the baseline accuray prop.table(table(train$Churn)) 3. Fitting the model using glm() function glm <- glm(Churn ~., data = train, family = "binomial")summary(glm) 4. Measuring accuracy pred <- predict(glm, data = train, type = "response")# confusion matrix on training setglmtab1 <- table(train$Churn, pred >= 0.5)acc_glm_train <- (3275+708)/nrow(train)# observations on the test setpredtest <- predict(glm, newdata = test, type = "response")glmtab2 <- table(test$Churn, predtest >= 0.5)acc_glm_test <- (1382+307)/nrow(test) Accuracy = 0.80 5. Important Variables Fitting the model Fitting the model fit_rf <- randomForest(Churn ~ ., data=train, proximity=FALSE,importance = FALSE)fit_rf 2. Calculating accuracy predrf <- predict(fit_rf, data = "train", type = "response")rftab <- table(predrf, train$Churn)acc_rf_train <- (3248+694)/nrow(train)acc_rf_train Accuracy = 0.80 3. Error and important variables plot plot(fit_rf)varImpPlot(rf) Fit the model Fit the model rpart <- rpart(Churn ~. , data = train, method = "class", control = rpart.control((cp = 0.05)))summary(rpart) 2. Calculatuing accuracy rpred <- predict(rpart, data = train, type = "class")dtab1 <- table(rpred, train$Churn)acc_rpart_train <- (3380+522)/nrow(train)rpredt <- predict(rpart, newdata = test, type = "class")dtab2 <- table(rpredt, test$Churn)acc_rpredt_test <- (1435+218)/nrow(test) Accuracy = 0.78 3. Important variables AUC for all three models Reference for this code: rstudio-pubs. library(pROC)glm.roc <- roc(response = test$Churn, predictor = as.numeric(predtest))rpart.roc <- roc(response = train$Churn, predictor = as.numeric(predrf))rf.roc <- roc(response = test$Churn, predictor = as.numeric(rpredt))plot(glm.roc, legacy.axes = TRUE, print.auc.y = 1.0, print.auc = TRUE)plot(rpart.roc, col = "blue", add = TRUE, print.auc.y = 0.65, print.auc = TRUE)plot(rf.roc, col = "red" , add = TRUE, print.auc.y = 0.85, print.auc = TRUE)legend("bottom", c("Random Forest", "Decision Tree", "Logistic"), lty = c(1,1), lwd = c(2, 2), col = c("red", "blue", "black"), cex = 0.75) Conclusion: Comparing accuracy and AUC value, Logistic Model performs better than Random Forest and Decision Tree to predict churn in this particular dataset. Tenure, Contract, PaperlessBilling, InternetService are of the most important features. Some features like gender, partner etc have no impact on churn. Other Stories: Time Series Forecasting in RAn Approach To Make Comparison of ARIMA and NNAR models For Forecasting Price of Commodities.Market share prediction in R Time Series Forecasting in R An Approach To Make Comparison of ARIMA and NNAR models For Forecasting Price of Commodities. Market share prediction in R
[ { "code": null, "e": 188, "s": 172, "text": "What is Churn ?" }, { "code": null, "e": 358, "s": 188, "text": "Churn rate, when applied to a customer base, refers to the proportion of contractual customers or subscribers who leave a supplier during a given time period.(wikipedia)" }, { "code": null, "e": 393, "s": 358, "text": "Why Churn Prediction is important?" }, { "code": null, "e": 628, "s": 393, "text": "Churn is directly related to the profitability of a company. The more some can learn about customer behaviors, the more profit can be gained. This also helps identifying and improving areas or fields where customer service is lacking." }, { "code": null, "e": 739, "s": 628, "text": "The data was collected from IBM. Firstly load the libraries required and the data and take a look on the data." }, { "code": null, "e": 991, "s": 739, "text": "library(tidyverse)library(caret)library(repr)library(caTools)library(rpart)library(rpart.plot)library(ggpubr)# input the data and take a look on the variablesdata <- read.csv(\"telco.csv\")glimpse(data)data <- data[complete.cases(data),] # removing na's" }, { "code": null, "e": 1007, "s": 991, "text": "About the Data:" }, { "code": null, "e": 1109, "s": 1007, "text": "In this data, all the rows represents different customer and each column represents their attributes." }, { "code": null, "e": 1173, "s": 1109, "text": "The column Churn indicates customers leaving on the last month." }, { "code": null, "e": 1342, "s": 1173, "text": "Customers’ subscription to the services — phone, multiple lines, internet, online security, online backup, device protection, tech support, and streaming TV and movies." }, { "code": null, "e": 1463, "s": 1342, "text": "Account informations of each customer — contract, payment method, paperless billing, monthly charges, and total charges." }, { "code": null, "e": 1550, "s": 1463, "text": "Demographic informations — gender, age range, and if they have partners and dependents" }, { "code": null, "e": 1566, "s": 1550, "text": "Data Wrangling:" }, { "code": null, "e": 1665, "s": 1566, "text": "Terms like “No internet service” and “No phone service” should be changed to “No” for convenience." }, { "code": null, "e": 1764, "s": 1665, "text": "Terms like “No internet service” and “No phone service” should be changed to “No” for convenience." }, { "code": null, "e": 1934, "s": 1764, "text": "data <- data.frame(lapply(data, function(x) { gsub(\"No internet service\", \"No\", x)}))data <- data.frame(lapply(data, function(x) { gsub(\"No phone service\", \"No\", x)}))" }, { "code": null, "e": 2007, "s": 1934, "text": "2. SeniorCitizen responds in 1 and 0, which is changed to “Yes” or “No”." }, { "code": null, "e": 2083, "s": 2007, "text": "data$SeniorCitizen <- as.factor(ifelse(data$SeniorCitizen==1, 'YES', 'NO'))" }, { "code": null, "e": 2180, "s": 2083, "text": "3. Convert double type variables into numeric type and store them in a variable as a data frame." }, { "code": null, "e": 2402, "s": 2180, "text": "num_columns <- c(\"tenure\", \"MonthlyCharges\", \"TotalCharges\")data[num_columns] <- sapply(data[num_columns], as.numeric)data_int <- data[,c(\"tenure\", \"MonthlyCharges\", \"TotalCharges\")]data_int <- data.frame(scale(data_int))" }, { "code": null, "e": 2459, "s": 2402, "text": "4. Tenure is in months. We should convert it into years." }, { "code": null, "e": 3021, "s": 2459, "text": "data <- mutate(data, tenure_year = tenure)data$tenure_year[data$tenure_year >=0 & data$tenure_year <= 12] <- '0-1 year'data$tenure_year[data$tenure_year > 12 & data$tenure_year <= 24] <- '1-2 years'data$tenure_year[data$tenure_year > 24 & data$tenure_year <= 36] <- '2-3 years'data$tenure_year[data$tenure_year > 36 & data$tenure_year <= 48] <- '3-4 years'data$tenure_year[data$tenure_year > 48 & data$tenure_year <= 60] <- '4-5 years'data$tenure_year[data$tenure_year > 60 & data$tenure_year <= 72] <- '5-6 years'data$tenure_year <- as.factor(data$tenure_year)" }, { "code": null, "e": 3141, "s": 3021, "text": "5. Prepare the final data for analysis excluding selected variables which we don’t need throughout the analsis process." }, { "code": null, "e": 3425, "s": 3141, "text": "data$tenure_year <- as.factor(data$tenure_year)data_req <- data[,-c(1,6,19,20)]x <- data.frame(sapply(data_req,function(x) data.frame(model.matrix(~x-1,data =data_req))[,-1]))x <- na.omit(x) # omit the NA'sdata_int <- na.omit(data_int) # omit the NA'sdata_final <- cbind(x, data_int)" }, { "code": null, "e": 3473, "s": 3425, "text": "Correlation plot between the numeric variables:" }, { "code": null, "e": 3521, "s": 3473, "text": "Correlation plot between the numeric variables:" }, { "code": null, "e": 3658, "s": 3521, "text": "nv <- sapply(data_int, is.numeric)cormat <- cor(data_int[,nv])ggcorrplot::ggcorrplot(cormat, title = \"Correlation of Numeric Variables\")" }, { "code": null, "e": 3738, "s": 3658, "text": "2. Churn percentage tells around 26.58% of the customer left during last month." }, { "code": null, "e": 4083, "s": 3738, "text": "churn <- data %>% group_by(Churn) %>% summarise(Count = n())%>% mutate(percentage = prop.table(Count)*100)ggplot(churn, aes(reorder(Churn, -percentage), percentage), fill = Churn)+ geom_col(fill = c(\"green\", \"red\"))+ geom_text(aes(label = sprintf(\"%.2f%%\", percentage)))+ xlab(\"Churn\") + ylab(\"Percent\")+ ggtitle(\"Churn Percentage\")" }, { "code": null, "e": 4141, "s": 4083, "text": "3. Bar plots to show churn rate in categorical variables." }, { "code": null, "e": 5725, "s": 4141, "text": "fig1 <- ggarrange(ggplot(data, aes(x=gender,fill=Churn))+ geom_bar() , ggplot(data, aes(x=SeniorCitizen,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=Partner,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=Dependents,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=PhoneService,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=MultipleLines,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=InternetService,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=OnlineSecurity,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=OnlineBackup,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=DeviceProtection,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=TechSupport,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=StreamingTV,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=StreamingMovies,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=Contract,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=PaperlessBilling,fill=Churn))+ geom_bar(position = 'fill'), ggplot(data, aes(x=PaymentMethod,fill=Churn))+geom_bar(position = 'fill')+theme_bw()+ rremove(\"x.text\"), ncol = 3, nrow = 6, common.legend = TRUE, legend = \"bottom\")annotate_figure(fig1, bottom = text_grob(\"Churn Percentage in categorical variables\", col = \"blue\", face = \"bold\", size = 14))" }, { "code": null, "e": 5784, "s": 5725, "text": "4. Bar plot to show churn percentage in numeric variables." }, { "code": null, "e": 6339, "s": 5784, "text": "fig2 <- ggarrange( ggplot(data, aes(y= tenure, x = \"\", fill = Churn))+geom_boxplot() + xlab(\" \"), ggplot(data, aes(y= MonthlyCharges, x = \"\", fill = Churn)) +geom_boxplot() + xlab(\" \"), ggplot(data, aes(y= TotalCharges, x = \"\", fill = Churn)) +geom_boxplot() + xlab(\" \"), rremove(\"x.text\"), ncol = 2, nrow = 2, common.legend = TRUE, legend = \"bottom\")annotate_figure(fig2, bottom = text_grob(\"Churn Percentage in numeric variables\", col = \"red\", face = \"bold\", size = 14))" }, { "code": null, "e": 6377, "s": 6339, "text": "Split the data in train and test sets" }, { "code": null, "e": 6415, "s": 6377, "text": "Split the data in train and test sets" }, { "code": null, "e": 6543, "s": 6415, "text": "set.seed(123)split <- sample.split(data_final$Churn, SplitRatio = 0.70)train <- data_final[split,]test <- data_final[!(split),]" }, { "code": null, "e": 6577, "s": 6543, "text": "2. Calculate the baseline accuray" }, { "code": null, "e": 6608, "s": 6577, "text": "prop.table(table(train$Churn))" }, { "code": null, "e": 6650, "s": 6608, "text": "3. Fitting the model using glm() function" }, { "code": null, "e": 6718, "s": 6650, "text": "glm <- glm(Churn ~., data = train, family = \"binomial\")summary(glm)" }, { "code": null, "e": 6740, "s": 6718, "text": "4. Measuring accuracy" }, { "code": null, "e": 7080, "s": 6740, "text": "pred <- predict(glm, data = train, type = \"response\")# confusion matrix on training setglmtab1 <- table(train$Churn, pred >= 0.5)acc_glm_train <- (3275+708)/nrow(train)# observations on the test setpredtest <- predict(glm, newdata = test, type = \"response\")glmtab2 <- table(test$Churn, predtest >= 0.5)acc_glm_test <- (1382+307)/nrow(test)" }, { "code": null, "e": 7096, "s": 7080, "text": "Accuracy = 0.80" }, { "code": null, "e": 7119, "s": 7096, "text": "5. Important Variables" }, { "code": null, "e": 7137, "s": 7119, "text": "Fitting the model" }, { "code": null, "e": 7155, "s": 7137, "text": "Fitting the model" }, { "code": null, "e": 7243, "s": 7155, "text": "fit_rf <- randomForest(Churn ~ ., data=train, proximity=FALSE,importance = FALSE)fit_rf" }, { "code": null, "e": 7267, "s": 7243, "text": "2. Calculating accuracy" }, { "code": null, "e": 7413, "s": 7267, "text": "predrf <- predict(fit_rf, data = \"train\", type = \"response\")rftab <- table(predrf, train$Churn)acc_rf_train <- (3248+694)/nrow(train)acc_rf_train" }, { "code": null, "e": 7429, "s": 7413, "text": "Accuracy = 0.80" }, { "code": null, "e": 7467, "s": 7429, "text": "3. Error and important variables plot" }, { "code": null, "e": 7494, "s": 7467, "text": "plot(fit_rf)varImpPlot(rf)" }, { "code": null, "e": 7508, "s": 7494, "text": "Fit the model" }, { "code": null, "e": 7522, "s": 7508, "text": "Fit the model" }, { "code": null, "e": 7632, "s": 7522, "text": "rpart <- rpart(Churn ~. , data = train, method = \"class\", control = rpart.control((cp = 0.05)))summary(rpart)" }, { "code": null, "e": 7657, "s": 7632, "text": "2. Calculatuing accuracy" }, { "code": null, "e": 7916, "s": 7657, "text": "rpred <- predict(rpart, data = train, type = \"class\")dtab1 <- table(rpred, train$Churn)acc_rpart_train <- (3380+522)/nrow(train)rpredt <- predict(rpart, newdata = test, type = \"class\")dtab2 <- table(rpredt, test$Churn)acc_rpredt_test <- (1435+218)/nrow(test)" }, { "code": null, "e": 7932, "s": 7916, "text": "Accuracy = 0.78" }, { "code": null, "e": 7955, "s": 7932, "text": "3. Important variables" }, { "code": null, "e": 7980, "s": 7955, "text": "AUC for all three models" }, { "code": null, "e": 8019, "s": 7980, "text": "Reference for this code: rstudio-pubs." }, { "code": null, "e": 8619, "s": 8019, "text": "library(pROC)glm.roc <- roc(response = test$Churn, predictor = as.numeric(predtest))rpart.roc <- roc(response = train$Churn, predictor = as.numeric(predrf))rf.roc <- roc(response = test$Churn, predictor = as.numeric(rpredt))plot(glm.roc, legacy.axes = TRUE, print.auc.y = 1.0, print.auc = TRUE)plot(rpart.roc, col = \"blue\", add = TRUE, print.auc.y = 0.65, print.auc = TRUE)plot(rf.roc, col = \"red\" , add = TRUE, print.auc.y = 0.85, print.auc = TRUE)legend(\"bottom\", c(\"Random Forest\", \"Decision Tree\", \"Logistic\"), lty = c(1,1), lwd = c(2, 2), col = c(\"red\", \"blue\", \"black\"), cex = 0.75)" }, { "code": null, "e": 8631, "s": 8619, "text": "Conclusion:" }, { "code": null, "e": 8778, "s": 8631, "text": "Comparing accuracy and AUC value, Logistic Model performs better than Random Forest and Decision Tree to predict churn in this particular dataset." }, { "code": null, "e": 8866, "s": 8778, "text": "Tenure, Contract, PaperlessBilling, InternetService are of the most important features." }, { "code": null, "e": 8930, "s": 8866, "text": "Some features like gender, partner etc have no impact on churn." }, { "code": null, "e": 8945, "s": 8930, "text": "Other Stories:" }, { "code": null, "e": 9095, "s": 8945, "text": "Time Series Forecasting in RAn Approach To Make Comparison of ARIMA and NNAR models For Forecasting Price of Commodities.Market share prediction in R" }, { "code": null, "e": 9124, "s": 9095, "text": "Time Series Forecasting in R" }, { "code": null, "e": 9218, "s": 9124, "text": "An Approach To Make Comparison of ARIMA and NNAR models For Forecasting Price of Commodities." } ]
Buffer array() methods in Java with Examples - GeeksforGeeks
28 Jun, 2019 The array() method of java.nio.Buffer class is used to return the array that backs the taken buffer.This method is intended to allow array-backed buffers to be passed to native code more efficiently. Concrete subclasses provide more strongly-typed return values for this method. Modifications to this buffer’s content will cause the returned array’s content to be modified, and vice versa. Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array. Syntax: public abstract Object array() Return Value: This method returns the array that backs this buffer. Exception: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only. Below are the examples to illustrate the array() method: Example 1: // Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast // value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // getting array that backs this buffer // using array() method byte[] arr = (byte[])bb1.array(); // print the array System.out.print("array is : ["); for (int i = 0; i < arr.length; i++) System.out.print(" " + arr[i]); System.out.print(" ]"); } catch (ReadOnlyBufferException e) { System.out.println("Exception throws: " + e); } }} array is : [ 20 30 40 50 ] Example 2: // Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast // value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); // Typecasting Read only ByteBuffer // into Read-only Buffer Buffer buffer = (Buffer)bb1; // getting array that backs this buffer // using array() method byte[] arr = (byte[])buffer.array(); // print the array System.out.print("array is : ["); for (int i = 0; i < arr.length; i++) System.out.print(" " + arr[i]); System.out.print(" ]"); } catch (ReadOnlyBufferException e) { System.out.println("buffer is backed by " + "an array but is read-only"); System.out.println("Exception throws: " + e); } }} buffer is backed by an array but is read-only Exception throws: java.nio.ReadOnlyBufferException Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#array– Java-Buffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java Collections in Java
[ { "code": null, "e": 24167, "s": 24139, "text": "\n28 Jun, 2019" }, { "code": null, "e": 24446, "s": 24167, "text": "The array() method of java.nio.Buffer class is used to return the array that backs the taken buffer.This method is intended to allow array-backed buffers to be passed to native code more efficiently. Concrete subclasses provide more strongly-typed return values for this method." }, { "code": null, "e": 24681, "s": 24446, "text": "Modifications to this buffer’s content will cause the returned array’s content to be modified, and vice versa. Invoke the hasArray method before invoking this method in order to ensure that this buffer has an accessible backing array." }, { "code": null, "e": 24689, "s": 24681, "text": "Syntax:" }, { "code": null, "e": 24720, "s": 24689, "text": "public abstract Object array()" }, { "code": null, "e": 24788, "s": 24720, "text": "Return Value: This method returns the array that backs this buffer." }, { "code": null, "e": 24902, "s": 24788, "text": "Exception: This method throws the ReadOnlyBufferException, If this buffer is backed by an array but is read-only." }, { "code": null, "e": 24959, "s": 24902, "text": "Below are the examples to illustrate the array() method:" }, { "code": null, "e": 24970, "s": 24959, "text": "Example 1:" }, { "code": "// Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast // value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // getting array that backs this buffer // using array() method byte[] arr = (byte[])bb1.array(); // print the array System.out.print(\"array is : [\"); for (int i = 0; i < arr.length; i++) System.out.print(\" \" + arr[i]); System.out.print(\" ]\"); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception throws: \" + e); } }}", "e": 26184, "s": 24970, "text": null }, { "code": null, "e": 26212, "s": 26184, "text": "array is : [ 20 30 40 50 ]\n" }, { "code": null, "e": 26223, "s": 26212, "text": "Example 2:" }, { "code": "// Java program to demonstrate// array() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int to byte typecast // value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // Creating a read-only copy of ByteBuffer // using asReadOnlyBuffer() method ByteBuffer bb1 = bb.asReadOnlyBuffer(); // Typecasting Read only ByteBuffer // into Read-only Buffer Buffer buffer = (Buffer)bb1; // getting array that backs this buffer // using array() method byte[] arr = (byte[])buffer.array(); // print the array System.out.print(\"array is : [\"); for (int i = 0; i < arr.length; i++) System.out.print(\" \" + arr[i]); System.out.print(\" ]\"); } catch (ReadOnlyBufferException e) { System.out.println(\"buffer is backed by \" + \"an array but is read-only\"); System.out.println(\"Exception throws: \" + e); } }}", "e": 27716, "s": 26223, "text": null }, { "code": null, "e": 27814, "s": 27716, "text": "buffer is backed by an array but is read-only\nException throws: java.nio.ReadOnlyBufferException\n" }, { "code": null, "e": 27895, "s": 27814, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#array–" }, { "code": null, "e": 27907, "s": 27895, "text": "Java-Buffer" }, { "code": null, "e": 27922, "s": 27907, "text": "Java-Functions" }, { "code": null, "e": 27939, "s": 27922, "text": "Java-NIO package" }, { "code": null, "e": 27944, "s": 27939, "text": "Java" }, { "code": null, "e": 27949, "s": 27944, "text": "Java" }, { "code": null, "e": 28047, "s": 27949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28056, "s": 28047, "text": "Comments" }, { "code": null, "e": 28069, "s": 28056, "text": "Old Comments" }, { "code": null, "e": 28120, "s": 28069, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28150, "s": 28120, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28181, "s": 28150, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28213, "s": 28181, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28232, "s": 28213, "text": "Interfaces in Java" }, { "code": null, "e": 28250, "s": 28232, "text": "ArrayList in Java" }, { "code": null, "e": 28282, "s": 28250, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28302, "s": 28282, "text": "Stack Class in Java" }, { "code": null, "e": 28326, "s": 28302, "text": "Singleton Class in Java" } ]
Kickstarter Projects Walk-Through — Simple Data Exploration in Python | by Franz B. | Towards Data Science
This article analyses a dataset of roughly 380.000 Kickstarter projects. I will lead you through a simple data exploration with Python to reveal interesting insights in Kickstarter projects and what attributes are important when it comes to examining the success (or failure) of a certain project. In general, we will have a look at basic data visualisation and feature engineering with Python. Kickstarter is one of the most renown platforms for promoting (mostly) creative, smart and visionary ideas and concepts. Each project seeks funding that the Kickstarter-Crowd can provide if they support the idea and would like to see it succeed. However, there are many projects that fail, even though the initial idea might have been convincing. Why is that? This article tries to dive into attributes related to each project and to reveal patterns, insights and anything of interest related to Kickstarter projects. The dataset contains 378.661 projects from Kickstarter and twelve initial attributes related to each project. Let’s have a look at what information we got about each project: namePretty obvious, the name of the respective project. E.g. “Daily Brew Coffee”main_categorythe main category the project falls in. E.g. “Poetry”, ”Food”, “Music” and many morecategorya more precise description of the main category. Basically, a subgroup of main_category (see 2.). E.g. “Drinks” which would be a subgroup of “Food” from the main_category attribute.currencythe currency of the project (e.g. USD or GBP)launchedthe launch date for the project. This will be important when we analyze timeframes later ondeadlinethe deadline for the project. Just as the launch date, the deadline will become important just as the launch dateusd_pledged_realamount of USD the project realised at the deadlineusd_goal_realamount of USD the project asked for initiallybackersthe number of supporters that actually invested in the projectcountrycountry of origin of the projectIDproject IDstateWas the project successful at the end of the day? state is a categorical variable divided into the levels successful, failed, live, cancelled, undefined and suspended. For the sake of clarity, we will only look at whether a project was successful or failed (hence, we will remove all projects that are not classified as one of the two). Projects that failed or were successful make up around 88% of all projects. namePretty obvious, the name of the respective project. E.g. “Daily Brew Coffee” main_categorythe main category the project falls in. E.g. “Poetry”, ”Food”, “Music” and many more categorya more precise description of the main category. Basically, a subgroup of main_category (see 2.). E.g. “Drinks” which would be a subgroup of “Food” from the main_category attribute. currencythe currency of the project (e.g. USD or GBP) launchedthe launch date for the project. This will be important when we analyze timeframes later on deadlinethe deadline for the project. Just as the launch date, the deadline will become important just as the launch date usd_pledged_realamount of USD the project realised at the deadline usd_goal_realamount of USD the project asked for initially backersthe number of supporters that actually invested in the project countrycountry of origin of the project IDproject ID stateWas the project successful at the end of the day? state is a categorical variable divided into the levels successful, failed, live, cancelled, undefined and suspended. For the sake of clarity, we will only look at whether a project was successful or failed (hence, we will remove all projects that are not classified as one of the two). Projects that failed or were successful make up around 88% of all projects. Let’s quickly remove all projects that do not have failed or successful as their state. #return only successful and failed projects. This makes things more clear later ondata_kick = data_kick.loc[data_kick['state'].isin( ['successful', 'failed'])] Let’s first have a look at the datatype of all attributes to get a better understanding of the data and see if everything’s in order. data_kick.info()ID 378661 non-null int64name 378657 non-null objectcategory 378661 non-null objectmain_category 378661 non-null objectcurrency 378661 non-null objectdeadline 378661 non-null objectgoal 378661 non-null float64launched 378661 non-null objectpledged 378661 non-null float64state 378661 non-null objectbackers 378661 non-null int64country 378661 non-null objectusd pledged 374864 non-null float64usd_pledged_real 378661 non-null float64usd_goal_real 378661 non-null float64 It can be seen that all attributes tend to be in the exact data format — either floats (hence numeric) or objects (hence categorical). The only two attributes that are not in the desired format are our two time attributes: launched and deadline. We will take care of these in a bit. But let’s get an understanding of the dataset first by analysing the amount pledged vs. the initial goal the project had. Let’s have a look at the relationship between a project’s goal and the actual amount pledged. It is quite obvious that a project is labelled as successful ifamount pledged ≥ goal and unsuccessful if amount pledged < goal. The following graph visualizes both the goal and amount pledged for each project and the individual state of the project (only failed and successful projects are displayed). #define colors (darkgreen for successful projects and darkred for failed onescolors = ('darkgreen','darkred')#create a plot using seaborn, adjust data to millionsax = sns.scatterplot(data_kick.usd_pledged_real/1e6, data_kick.usd_goal_real/1e6, hue=data_kick.state, palette=colors)#add blue line to better visualize the border between failed and successful projectssns.lineplot(x=(0,50), y=(0,50), color='darkblue')#set the axes from -1 to their maximum (-1 looks better than 0 actually)ax.set(ylim=(-1,None), xlim=(-1,None))#set labels and titleax.set(xlabel='Amount Pledged in Millions', ylabel='Goal in Millions', title= 'Goal vs. Pledged') Intuitively, projects that pledged more than/as much as their goal are successful and displayed green and failed projects are marked red. Have a look at the blue line intersecting the origin: successful projects are always underneath the line while failed projects are above it. This makes sense, doesn’t it? By the way, you can observe that the project with the highest amount pledged collected roughly around 20 Million USD and the project with the highest goal was looking for more than 160 Million USD (and failed). Time for a closer look. Let’s zoom in a little to get a better understanding by changing both axes to a range from zero to 20 Million: #we are using the same code as above expect for the axis limits, that are set from 0 Millions (-1 in the code) to 20 Millionsax.set(ylim=(-1,20), xlim=(-1,20) This zoom-in allows a more intuitive approach: The blue line is now intersecting the origin at a 45° angle since we adjusted the axes accordingly to the same range. As mentioned before, every data point (hence project) underneath the line succeeded, whereas every data point above it failed. Interestingly, the graph suggests that unsuccessful projects usually fail without coming even close to their goal, meaning that they “do not move horizontally towards the blue line but stay at x~0”. This leads to the conclusion that Kickstarter is an “all or nothing” platform. If you don’t make it, you probably didn’t even come close. On the other hand, many successful projects exceed their stated goal by far and pledge a multiple of their initial goal. How did the relationship between the amount pledged and the goal develop over time? Let us look at the development of goals and pledges over the entire time frame grouped by years. We use the following code to get the accumulated amount for both goals and pledges for each year. #we choose the desired grouping intervall ('launched year') and the two variables pledge and goal that we are interested in and sum them up over the years.data_kick_groupby_year = data_kick.groupby('launched_year')['usd_pledged_real', 'usd_goal_real'].sum()#let's use this variable to plot the data over time:ax = sns.lineplot(x=data_kick_groupby_year_sum.index, y= data_kick_groupby_year_sum.usd_pledged_real/1e9, linewidth= 4, label= 'USD Pledged', color= 'darkgreen')sns.lineplot(x=data_kick_groupby_year_sum.index, y= data_kick_groupby_year_sum.usd_goal_real/1e9, linewidth= 4,label='USD Goal', color= 'darkred')#set labels and titleax.set(xlabel='Launch Year', ylabel='USD in Billion', title='Comparison Pledged vs Goal over Time') We obtain this graph: The graph shows both the accumulated amount of goals and pledges for all projects of the respective year. E.g., in 2013, the sum of all financial goals of all launched projects was a bit higher than 1 Billion USD. It can be seen that the accumulated amount of the total goal sharply increases in 2013 and has its peak in 2015 before it slowly decreases. On the other hand, the accumulated amount of pledges for each year steadily decreases but rather linearly. It actually decreased slightly from 2015 to 2017. The reason for the sharp increase in the goal value is quite obvious, isn’t it? The number of projects dramatically increased as can be seen here: data_kick['launched_year'].value_counts()2015 652722014 593062016 492922017 434192013 411012012 384782011 240482010 95772009 1179 More projects, more goals. However, this is just one component contributing to the increase in accumulated goals. Not only more projects launched over the years, but the average goal per project also increased over the years as well, as shown here: #we group again. This time we take the average though:data_kick_groupby_year_avg = data_kick.groupby('launched_year')['usd_pledged_real', 'usd_goal_real'].mean()print(data_kick_groupby_year_avg)launched_year usd_pledged_real usd_goal_real 2009 2375.535335 6799.5074302010 3041.302897 13270.0626472011 4256.161398 9715.9570622012 8247.532875 17862.7388382013 11326.171820 24946.1649292014 8466.032884 47346.9420482015 10058.201943 70094.5137352016 12847.626664 52879.1357522017 13564.594251 39073.175276 The average goal increases over time (from ca. 10,000 USD in 2011 to ca. 53,000 USD in 2016 followed by a sharp drop in 2017). Hence, not only has the number of projects increased, the average goal per project increased as well. The combination of these factors boosted the accumulated goal graph over time. Now, enough of time. Let’s have a look at names! Another aspect that might influence the outcome of a project is its name. We would expect shorter, concise names to be more appealing to (potential) investors than long and blurry phrases. For example, a name like “ Circa Vitae requests crowd fundage to record our full length album... TO VINYL!!!” is less catchy than “Day X” (the first project indeed failed and the latter succeeded). Does the data support this hypothesis? Let’s feature engineer a little and create a new column containing the string length of a project’s name. data_kick['name_length'] = data_kick['name'].str.len() We now saved the string length of each project’s name in name_length. Let’s have a look what the column looks like. data_kick.loc[:,['name','name_length']].head(5)name name_length0 The Songs of Adelaide & Abullah 31.01 Greeting From Earth: ZGAC Arts Capsule For ET 45.02 Where is Hank? 14.03 ToshiCapital Rekordz Needs Help to Complete Album 49.04 Community Film Project: The Art of Neighborhoo... 58.0 Let’s create a scatterplot to show the relationship between name_length and the amount usd_pledged_real. #create scatterplot for pledged amount and name lengthax = sns.scatterplot(data_kick.usd_pledged_real/1e6, data_kick.name_length, hue=data_kick.state, palette=colors)#set labels accordinglyax.set(xlabel='Amount Pledged in Millions', ylabel='Character Length of Project Name', title= 'The Importance of Choosing the Right Name') Interestingly, if a project’s name is exceeding 60 characters, the pledged amount is distributed around 0 and (more or less) all projects seem to fail. Let us have a look at the goal of these projects compared to the <60 projects and check the following hypothesis: Could it be that >60 character projects do have explicitly high goal values that they aim to collect? To check this hypothesis let’s look at the average goal for name_length≥60 vs. goal for name_length<60. Let’s have a look at this subgroup of projects that have more than 60 characters in terms of their goal size and their project state: #create a variable for all data points above a name length of 60data_kick_60_up = data_kick.loc[data_kick.name_length >= 60, ['state','usd_goal_real']]#create a variable for the data points below a name length of 60data_kick_60_down = data_kick.loc[data_kick.name_length < 60, ['state','usd_goal_real']]#compare the median of both groups. We see that the above 60 group actually has a higher median than the below 60 group.print(data_kick_60_up['usd_goal_real'].median() > data_kick_60_down['usd_goal_real'].median())True We can see that the median (and mean as well) is higher for the ≥60 group regarding their goal (Boolean returns “True”). Hence, we cannot conclude that projects with a name length of ≥60 simply have lower goal values. On the contrary, they actually have higher goals compared to the projects that have names that are <60 characters (on average). This might account for their failure. Isn’t that something! As mentioned earlier, the most intuitive explanation for the “success-segmentation” based on the project’s name length is that long names have the tendency to sound unprofessional, not on point and not as committed (obviously this is just a personal opinion). Hence, they pledge less and fail. As mentioned before, all variables are of the right type — except for the time variable(s). Luckily, Pandas allows us to quickly change date variables to actual dates: data_kick['launched'] = pd.to_datetime(data_kick['launched'],format='%Y-%m-%d %H:%M:%S')data_kick['deadline'] = pd.to_datetime(data_kick['deadline'],format='%Y-%m-%d %H:%M:%S') If you check data_kick.info() now, you will see that launched and deadline have the right data type. Now that we have converted the time variables to the correct format, let’s have a closer look at them. In particular, we have two interesting time columns: The exact date when the project was launched and secondly the deadline for each project. Now what? Maybe the date the project was launched influences its success, maybe the time between the launch and deadline also affect the outcome of the project. One could argue that the longer the span between launch and deadline, the more time there is to get noticed and collect money. Hence, the longer the span, the higher the chances for success. In addition, the month (or even hour) the project was launched might influence its outcome. But does the data support these hypotheses? Let’s have a look at the launch times first. We can extract the respective hour when the project was launched by the following code: data_kick['launched_hour'] = data_kick.launched.apply(lambda x: x.hour)data_kick['launched_month'] = data_kick.launched.apply(lambda x: x.month) We just created two new columns containing the month and the hour of the project’s launch respectively. Let us see if these new attributes contain patterns that help us understand whether a project is successful or not. Let’s visualize the hour of the day and the success of the project: #extract launched hour and state for all states 'successful' and append the same for all states 'failed'.data_kick = data_kick.loc[data_kick.state == 'successful',['launched_hour', 'state']].append(data_kick.loc[data_kick.state == 'failed', ['launched_hour', 'state']])#plot the dataax = sns.countplot(x=extracted_levels_hour.launched_hour, hue = extracted_levels_hour.state)#set labels and titleax.set(xlabel='Launched Hour', ylabel='Number of Projects', title= 'Hour the Project was Launched') There are a few interesting things to observe here: In general, there are more projects launched either in the early morning (between 0 and 6 am) and more projects launched in the late afternoon/evening (between 4 and 23 pm) compared to the time between 7 am and 3 pm.The ratio between successful and failed projects varies over the time of the day. We can see that the ratio between failed and successful projects is almost 1 (a bit less actually) for projects launched between 2 and 3 pm. In contrary, the ratio for projects launched after 8 pm is much worse (in other words: by far more projects failed than succeeded). In general, there are more projects launched either in the early morning (between 0 and 6 am) and more projects launched in the late afternoon/evening (between 4 and 23 pm) compared to the time between 7 am and 3 pm. The ratio between successful and failed projects varies over the time of the day. We can see that the ratio between failed and successful projects is almost 1 (a bit less actually) for projects launched between 2 and 3 pm. In contrary, the ratio for projects launched after 8 pm is much worse (in other words: by far more projects failed than succeeded). Let’s have a look whether the month the project was launched reveals anything about its state: #plot the datasns.countplot(x=data_kick.launched_hour, hue = data_kick.state)#set labels and titleax.set(xlabel='Month of the Year', ylabel='Number of Projects', title= 'Month the Project was Launched') Compared to the hour of the day, the months do not seem to reveal any surprising insights. However, note that there are by far fewer projects launched in December compared to all other months. Finally, let us look at the span between launched and deadline. We can obtain this span easily by subtracting launched from deadline (this is a useful feature of the date_time transformation we have done earlier). In the code below, we take the difference between launched and deadline and extract the days immediately (‘timedelta64[D]’): data_kick['project_time'] = (data_kick['deadline'] -data_kick['launched']).astype('timedelta64[D]').astype(int)data_kick['project_time'].head(5)0 581 592 443 294 55 You can see that our new column project_time measures the span between launch and deadline in days. For example, the first project in the dataset ([0]) was on Kickstarter for almost two months (58 days). Before we visualize the span for a project, let us bin the results. The maximum of data_kick[‘project_time’] is at 91, so instead of getting 91 different results, we could bin the data by week to get a more intuitive overview. Let us first write a function that allows us to effectively bin data: def discretizer(data, binning_values, labels): """ Input: data series that should be discretized bininningvalues: enter numerical array of binning cuts labels: enter string array of names for binsOutput: gives you a list of binned data """ data = pd.cut(data, bins=binning_values, labels=labels) return data Let’s parse in project_time and bin it by weeks: #save the binned data as new columndata_kick["project_time_weeks"] =#call the discretizer funtiondiscretizer(#first thing we pass is the column we want to be discretized, project_time in this casedata_kick['project_time'],#next, we create a list with the different binning intervals (starting at 0 and then going in steps of 7 until the maximum value of project_time (+7)list(range(0,max(data_kick['project_time'])+7,7)),#last but not least, we need to label the bins. We number them by creating a list from 1 (first week) to the last week depending on the maximum value of project_timelist(range(1,max(list(range(0,max(data_kick['project_time'])//7+2)))))) So what does the new column, project_time_weeks look like? #print first 5 rows of both columns:data_kick[['project_time', 'project_time_weeks']].head(5)#resulting in:project_time project_time_weeks 34 5 19 3 29 5 27 4 14 2 We can see that the days were successfully binned by weeks. E.g. 19 days are converted to week 3. Now, finally, let’s have a luck whether the time between launch and deadline affects the success of a project: #plot the datasns.countplot(x=data_kick.project_time_discret, hue = data_reduced.state, palette=colors) We instantly notice that most projects are put on Kickstarter for about 5 weeks and almost all projects are live between 1 and 9 weeks (so a bit more than 2 months). The proportion between successful and failed projects varies over time: Projects with a short run time (1–4 weeks) succeed relatively more often compared to projects that are launched with a medium to long run time (5–13 weeks). This insight could support the hypothesis that project are not more likely to succeed the longer they are live as one might have assumed beforehand (-> the longer a project is live, the more people have the chance to see it over time, the more likely it will succeed. This does not seem to be true). Now we take a look at the role of backers that support each project. In general, we would expect that a high number of backers contribute positively to the likelihood of success for a specific project. But is this really the case? Let us visualize the number of backers, amount pledged and the state of the project. ax = sns.scatterplot(x=data_kick.backers, y=data_kick.usd_pledged_real/1e6, hue=data_kick.state, palette=colors)#we set the xlim to 100,000 backers to get a better overviewax.set(ylim=(-1,None), xlim=(-1,100000))#set labels and titleax.set(xlabel='Number of Backers', ylabel='USD Pledged in Million', title= 'Backer vs Pledge') The code results in the following graph: This result isn’t surprising, is it? We can clearly see that the number of backers correlates with the success of a project. Most projects that fail also have a (relatively) smaller number of backers. However, let’s go further: Not only the absolute number of backers per project is interesting but the average amount spent by each backer per project. In order to get this attribute, we need to divide the amount pledged by the number of actual backers. Let’s do that quickly. #divide usd_pledged_real by number of backers (note that a Zerodivisionerror will occur if we divide by zero resulting in a NaN. We replace these with 0data_kick['backer_ratio'] = (data_kick['usd_pledged_real']//data_kick['backers']).fillna(0)#set label and titleax.set(xlabel='Pledge/Backer Ratio (funding per backer)', ylabel='USD Pledged in Million', title= 'Backer Ratio vs Pledge') Looking at the backer ratio (hence the sum of the amount pledged divided by the total number of backers) we can see that most successful projects have a relatively low backer ratio, meaning that each backer contributes a relatively small amount. According to the graph, this amount varies between shortly above 0 USD and up to around 700 USD. We can see that most projects that have relatively high backer ratios (<2,000 USD) failed. Now that we have looked at time frames, names, backers and many other details, it is time to stop our little walkthrough here. There are still plenty of possible insights and patterns to reveal but I leave this up to you ;-) 6. Conclusion This introductory post about basic Data Visualization in Python revealed some interesting facts about Kickstarter projects. Let’s summarize: Projects that fail, most of the times fail miserably. They “cannot move towards the blue line” as discussed in part 3. It’s all in or nothing ;-).The number and average goal of projects increased sharply over time (at least until 2015) whereas the provided pledges only slowly increase.Names play a big role. In case you want to launch a project, make sure you keep its name precise and short. “Tenacious Exclusive Scott Tolleson Uncle Argh NOIR Mini Qee” may sound funny (it actually doesn’t) but won’t get you anywhere.Try to launch your project between 12 and 4 pm and do NOT launch in December (Ok, I am not 100% serious about that one). Projects that fail, most of the times fail miserably. They “cannot move towards the blue line” as discussed in part 3. It’s all in or nothing ;-). The number and average goal of projects increased sharply over time (at least until 2015) whereas the provided pledges only slowly increase. Names play a big role. In case you want to launch a project, make sure you keep its name precise and short. “Tenacious Exclusive Scott Tolleson Uncle Argh NOIR Mini Qee” may sound funny (it actually doesn’t) but won’t get you anywhere. Try to launch your project between 12 and 4 pm and do NOT launch in December (Ok, I am not 100% serious about that one). I hope you enjoyed this read. I appreciate any kind of feedback, (constructive) criticism or other recommendations. Thanks!
[ { "code": null, "e": 566, "s": 171, "text": "This article analyses a dataset of roughly 380.000 Kickstarter projects. I will lead you through a simple data exploration with Python to reveal interesting insights in Kickstarter projects and what attributes are important when it comes to examining the success (or failure) of a certain project. In general, we will have a look at basic data visualisation and feature engineering with Python." }, { "code": null, "e": 1084, "s": 566, "text": "Kickstarter is one of the most renown platforms for promoting (mostly) creative, smart and visionary ideas and concepts. Each project seeks funding that the Kickstarter-Crowd can provide if they support the idea and would like to see it succeed. However, there are many projects that fail, even though the initial idea might have been convincing. Why is that? This article tries to dive into attributes related to each project and to reveal patterns, insights and anything of interest related to Kickstarter projects." }, { "code": null, "e": 1259, "s": 1084, "text": "The dataset contains 378.661 projects from Kickstarter and twelve initial attributes related to each project. Let’s have a look at what information we got about each project:" }, { "code": null, "e": 2560, "s": 1259, "text": "namePretty obvious, the name of the respective project. E.g. “Daily Brew Coffee”main_categorythe main category the project falls in. E.g. “Poetry”, ”Food”, “Music” and many morecategorya more precise description of the main category. Basically, a subgroup of main_category (see 2.). E.g. “Drinks” which would be a subgroup of “Food” from the main_category attribute.currencythe currency of the project (e.g. USD or GBP)launchedthe launch date for the project. This will be important when we analyze timeframes later ondeadlinethe deadline for the project. Just as the launch date, the deadline will become important just as the launch dateusd_pledged_realamount of USD the project realised at the deadlineusd_goal_realamount of USD the project asked for initiallybackersthe number of supporters that actually invested in the projectcountrycountry of origin of the projectIDproject IDstateWas the project successful at the end of the day? state is a categorical variable divided into the levels successful, failed, live, cancelled, undefined and suspended. For the sake of clarity, we will only look at whether a project was successful or failed (hence, we will remove all projects that are not classified as one of the two). Projects that failed or were successful make up around 88% of all projects." }, { "code": null, "e": 2641, "s": 2560, "text": "namePretty obvious, the name of the respective project. E.g. “Daily Brew Coffee”" }, { "code": null, "e": 2739, "s": 2641, "text": "main_categorythe main category the project falls in. E.g. “Poetry”, ”Food”, “Music” and many more" }, { "code": null, "e": 2929, "s": 2739, "text": "categorya more precise description of the main category. Basically, a subgroup of main_category (see 2.). E.g. “Drinks” which would be a subgroup of “Food” from the main_category attribute." }, { "code": null, "e": 2983, "s": 2929, "text": "currencythe currency of the project (e.g. USD or GBP)" }, { "code": null, "e": 3083, "s": 2983, "text": "launchedthe launch date for the project. This will be important when we analyze timeframes later on" }, { "code": null, "e": 3205, "s": 3083, "text": "deadlinethe deadline for the project. Just as the launch date, the deadline will become important just as the launch date" }, { "code": null, "e": 3272, "s": 3205, "text": "usd_pledged_realamount of USD the project realised at the deadline" }, { "code": null, "e": 3331, "s": 3272, "text": "usd_goal_realamount of USD the project asked for initially" }, { "code": null, "e": 3401, "s": 3331, "text": "backersthe number of supporters that actually invested in the project" }, { "code": null, "e": 3441, "s": 3401, "text": "countrycountry of origin of the project" }, { "code": null, "e": 3454, "s": 3441, "text": "IDproject ID" }, { "code": null, "e": 3872, "s": 3454, "text": "stateWas the project successful at the end of the day? state is a categorical variable divided into the levels successful, failed, live, cancelled, undefined and suspended. For the sake of clarity, we will only look at whether a project was successful or failed (hence, we will remove all projects that are not classified as one of the two). Projects that failed or were successful make up around 88% of all projects." }, { "code": null, "e": 3960, "s": 3872, "text": "Let’s quickly remove all projects that do not have failed or successful as their state." }, { "code": null, "e": 4131, "s": 3960, "text": "#return only successful and failed projects. This makes things more clear later ondata_kick = data_kick.loc[data_kick['state'].isin( ['successful', 'failed'])]" }, { "code": null, "e": 4265, "s": 4131, "text": "Let’s first have a look at the datatype of all attributes to get a better understanding of the data and see if everything’s in order." }, { "code": null, "e": 4915, "s": 4265, "text": "data_kick.info()ID 378661 non-null int64name 378657 non-null objectcategory 378661 non-null objectmain_category 378661 non-null objectcurrency 378661 non-null objectdeadline 378661 non-null objectgoal 378661 non-null float64launched 378661 non-null objectpledged 378661 non-null float64state 378661 non-null objectbackers 378661 non-null int64country 378661 non-null objectusd pledged 374864 non-null float64usd_pledged_real 378661 non-null float64usd_goal_real 378661 non-null float64" }, { "code": null, "e": 5320, "s": 4915, "text": "It can be seen that all attributes tend to be in the exact data format — either floats (hence numeric) or objects (hence categorical). The only two attributes that are not in the desired format are our two time attributes: launched and deadline. We will take care of these in a bit. But let’s get an understanding of the dataset first by analysing the amount pledged vs. the initial goal the project had." }, { "code": null, "e": 5716, "s": 5320, "text": "Let’s have a look at the relationship between a project’s goal and the actual amount pledged. It is quite obvious that a project is labelled as successful ifamount pledged ≥ goal and unsuccessful if amount pledged < goal. The following graph visualizes both the goal and amount pledged for each project and the individual state of the project (only failed and successful projects are displayed)." }, { "code": null, "e": 6359, "s": 5716, "text": "#define colors (darkgreen for successful projects and darkred for failed onescolors = ('darkgreen','darkred')#create a plot using seaborn, adjust data to millionsax = sns.scatterplot(data_kick.usd_pledged_real/1e6, data_kick.usd_goal_real/1e6, hue=data_kick.state, palette=colors)#add blue line to better visualize the border between failed and successful projectssns.lineplot(x=(0,50), y=(0,50), color='darkblue')#set the axes from -1 to their maximum (-1 looks better than 0 actually)ax.set(ylim=(-1,None), xlim=(-1,None))#set labels and titleax.set(xlabel='Amount Pledged in Millions', ylabel='Goal in Millions', title= 'Goal vs. Pledged')" }, { "code": null, "e": 6903, "s": 6359, "text": "Intuitively, projects that pledged more than/as much as their goal are successful and displayed green and failed projects are marked red. Have a look at the blue line intersecting the origin: successful projects are always underneath the line while failed projects are above it. This makes sense, doesn’t it? By the way, you can observe that the project with the highest amount pledged collected roughly around 20 Million USD and the project with the highest goal was looking for more than 160 Million USD (and failed). Time for a closer look." }, { "code": null, "e": 7014, "s": 6903, "text": "Let’s zoom in a little to get a better understanding by changing both axes to a range from zero to 20 Million:" }, { "code": null, "e": 7173, "s": 7014, "text": "#we are using the same code as above expect for the axis limits, that are set from 0 Millions (-1 in the code) to 20 Millionsax.set(ylim=(-1,20), xlim=(-1,20)" }, { "code": null, "e": 7465, "s": 7173, "text": "This zoom-in allows a more intuitive approach: The blue line is now intersecting the origin at a 45° angle since we adjusted the axes accordingly to the same range. As mentioned before, every data point (hence project) underneath the line succeeded, whereas every data point above it failed." }, { "code": null, "e": 7923, "s": 7465, "text": "Interestingly, the graph suggests that unsuccessful projects usually fail without coming even close to their goal, meaning that they “do not move horizontally towards the blue line but stay at x~0”. This leads to the conclusion that Kickstarter is an “all or nothing” platform. If you don’t make it, you probably didn’t even come close. On the other hand, many successful projects exceed their stated goal by far and pledge a multiple of their initial goal." }, { "code": null, "e": 8202, "s": 7923, "text": "How did the relationship between the amount pledged and the goal develop over time? Let us look at the development of goals and pledges over the entire time frame grouped by years. We use the following code to get the accumulated amount for both goals and pledges for each year." }, { "code": null, "e": 8939, "s": 8202, "text": "#we choose the desired grouping intervall ('launched year') and the two variables pledge and goal that we are interested in and sum them up over the years.data_kick_groupby_year = data_kick.groupby('launched_year')['usd_pledged_real', 'usd_goal_real'].sum()#let's use this variable to plot the data over time:ax = sns.lineplot(x=data_kick_groupby_year_sum.index, y= data_kick_groupby_year_sum.usd_pledged_real/1e9, linewidth= 4, label= 'USD Pledged', color= 'darkgreen')sns.lineplot(x=data_kick_groupby_year_sum.index, y= data_kick_groupby_year_sum.usd_goal_real/1e9, linewidth= 4,label='USD Goal', color= 'darkred')#set labels and titleax.set(xlabel='Launch Year', ylabel='USD in Billion', title='Comparison Pledged vs Goal over Time')" }, { "code": null, "e": 8961, "s": 8939, "text": "We obtain this graph:" }, { "code": null, "e": 9175, "s": 8961, "text": "The graph shows both the accumulated amount of goals and pledges for all projects of the respective year. E.g., in 2013, the sum of all financial goals of all launched projects was a bit higher than 1 Billion USD." }, { "code": null, "e": 9472, "s": 9175, "text": "It can be seen that the accumulated amount of the total goal sharply increases in 2013 and has its peak in 2015 before it slowly decreases. On the other hand, the accumulated amount of pledges for each year steadily decreases but rather linearly. It actually decreased slightly from 2015 to 2017." }, { "code": null, "e": 9619, "s": 9472, "text": "The reason for the sharp increase in the goal value is quite obvious, isn’t it? The number of projects dramatically increased as can be seen here:" }, { "code": null, "e": 9778, "s": 9619, "text": "data_kick['launched_year'].value_counts()2015 652722014 593062016 492922017 434192013 411012012 384782011 240482010 95772009 1179" }, { "code": null, "e": 10027, "s": 9778, "text": "More projects, more goals. However, this is just one component contributing to the increase in accumulated goals. Not only more projects launched over the years, but the average goal per project also increased over the years as well, as shown here:" }, { "code": null, "e": 10685, "s": 10027, "text": "#we group again. This time we take the average though:data_kick_groupby_year_avg = data_kick.groupby('launched_year')['usd_pledged_real', 'usd_goal_real'].mean()print(data_kick_groupby_year_avg)launched_year usd_pledged_real usd_goal_real 2009 2375.535335 6799.5074302010 3041.302897 13270.0626472011 4256.161398 9715.9570622012 8247.532875 17862.7388382013 11326.171820 24946.1649292014 8466.032884 47346.9420482015 10058.201943 70094.5137352016 12847.626664 52879.1357522017 13564.594251 39073.175276" }, { "code": null, "e": 11042, "s": 10685, "text": "The average goal increases over time (from ca. 10,000 USD in 2011 to ca. 53,000 USD in 2016 followed by a sharp drop in 2017). Hence, not only has the number of projects increased, the average goal per project increased as well. The combination of these factors boosted the accumulated goal graph over time. Now, enough of time. Let’s have a look at names!" }, { "code": null, "e": 11231, "s": 11042, "text": "Another aspect that might influence the outcome of a project is its name. We would expect shorter, concise names to be more appealing to (potential) investors than long and blurry phrases." }, { "code": null, "e": 11574, "s": 11231, "text": "For example, a name like “ Circa Vitae requests crowd fundage to record our full length album... TO VINYL!!!” is less catchy than “Day X” (the first project indeed failed and the latter succeeded). Does the data support this hypothesis? Let’s feature engineer a little and create a new column containing the string length of a project’s name." }, { "code": null, "e": 11629, "s": 11574, "text": "data_kick['name_length'] = data_kick['name'].str.len()" }, { "code": null, "e": 11745, "s": 11629, "text": "We now saved the string length of each project’s name in name_length. Let’s have a look what the column looks like." }, { "code": null, "e": 12183, "s": 11745, "text": "data_kick.loc[:,['name','name_length']].head(5)name name_length0 The Songs of Adelaide & Abullah 31.01 Greeting From Earth: ZGAC Arts Capsule For ET 45.02 Where is Hank? 14.03 ToshiCapital Rekordz Needs Help to Complete Album 49.04 Community Film Project: The Art of Neighborhoo... 58.0" }, { "code": null, "e": 12288, "s": 12183, "text": "Let’s create a scatterplot to show the relationship between name_length and the amount usd_pledged_real." }, { "code": null, "e": 12616, "s": 12288, "text": "#create scatterplot for pledged amount and name lengthax = sns.scatterplot(data_kick.usd_pledged_real/1e6, data_kick.name_length, hue=data_kick.state, palette=colors)#set labels accordinglyax.set(xlabel='Amount Pledged in Millions', ylabel='Character Length of Project Name', title= 'The Importance of Choosing the Right Name')" }, { "code": null, "e": 12882, "s": 12616, "text": "Interestingly, if a project’s name is exceeding 60 characters, the pledged amount is distributed around 0 and (more or less) all projects seem to fail. Let us have a look at the goal of these projects compared to the <60 projects and check the following hypothesis:" }, { "code": null, "e": 13088, "s": 12882, "text": "Could it be that >60 character projects do have explicitly high goal values that they aim to collect? To check this hypothesis let’s look at the average goal for name_length≥60 vs. goal for name_length<60." }, { "code": null, "e": 13222, "s": 13088, "text": "Let’s have a look at this subgroup of projects that have more than 60 characters in terms of their goal size and their project state:" }, { "code": null, "e": 13744, "s": 13222, "text": "#create a variable for all data points above a name length of 60data_kick_60_up = data_kick.loc[data_kick.name_length >= 60, ['state','usd_goal_real']]#create a variable for the data points below a name length of 60data_kick_60_down = data_kick.loc[data_kick.name_length < 60, ['state','usd_goal_real']]#compare the median of both groups. We see that the above 60 group actually has a higher median than the below 60 group.print(data_kick_60_up['usd_goal_real'].median() > data_kick_60_down['usd_goal_real'].median())True" }, { "code": null, "e": 14150, "s": 13744, "text": "We can see that the median (and mean as well) is higher for the ≥60 group regarding their goal (Boolean returns “True”). Hence, we cannot conclude that projects with a name length of ≥60 simply have lower goal values. On the contrary, they actually have higher goals compared to the projects that have names that are <60 characters (on average). This might account for their failure. Isn’t that something!" }, { "code": null, "e": 14444, "s": 14150, "text": "As mentioned earlier, the most intuitive explanation for the “success-segmentation” based on the project’s name length is that long names have the tendency to sound unprofessional, not on point and not as committed (obviously this is just a personal opinion). Hence, they pledge less and fail." }, { "code": null, "e": 14612, "s": 14444, "text": "As mentioned before, all variables are of the right type — except for the time variable(s). Luckily, Pandas allows us to quickly change date variables to actual dates:" }, { "code": null, "e": 14789, "s": 14612, "text": "data_kick['launched'] = pd.to_datetime(data_kick['launched'],format='%Y-%m-%d %H:%M:%S')data_kick['deadline'] = pd.to_datetime(data_kick['deadline'],format='%Y-%m-%d %H:%M:%S')" }, { "code": null, "e": 15145, "s": 14789, "text": "If you check data_kick.info() now, you will see that launched and deadline have the right data type. Now that we have converted the time variables to the correct format, let’s have a closer look at them. In particular, we have two interesting time columns: The exact date when the project was launched and secondly the deadline for each project. Now what?" }, { "code": null, "e": 15668, "s": 15145, "text": "Maybe the date the project was launched influences its success, maybe the time between the launch and deadline also affect the outcome of the project. One could argue that the longer the span between launch and deadline, the more time there is to get noticed and collect money. Hence, the longer the span, the higher the chances for success. In addition, the month (or even hour) the project was launched might influence its outcome. But does the data support these hypotheses? Let’s have a look at the launch times first." }, { "code": null, "e": 15756, "s": 15668, "text": "We can extract the respective hour when the project was launched by the following code:" }, { "code": null, "e": 15952, "s": 15756, "text": "data_kick['launched_hour'] = data_kick.launched.apply(lambda x: x.hour)data_kick['launched_month'] = data_kick.launched.apply(lambda x: x.month)" }, { "code": null, "e": 16240, "s": 15952, "text": "We just created two new columns containing the month and the hour of the project’s launch respectively. Let us see if these new attributes contain patterns that help us understand whether a project is successful or not. Let’s visualize the hour of the day and the success of the project:" }, { "code": null, "e": 16752, "s": 16240, "text": "#extract launched hour and state for all states 'successful' and append the same for all states 'failed'.data_kick = data_kick.loc[data_kick.state == 'successful',['launched_hour', 'state']].append(data_kick.loc[data_kick.state == 'failed', ['launched_hour', 'state']])#plot the dataax = sns.countplot(x=extracted_levels_hour.launched_hour, hue = extracted_levels_hour.state)#set labels and titleax.set(xlabel='Launched Hour', ylabel='Number of Projects', title= 'Hour the Project was Launched')" }, { "code": null, "e": 16804, "s": 16752, "text": "There are a few interesting things to observe here:" }, { "code": null, "e": 17375, "s": 16804, "text": "In general, there are more projects launched either in the early morning (between 0 and 6 am) and more projects launched in the late afternoon/evening (between 4 and 23 pm) compared to the time between 7 am and 3 pm.The ratio between successful and failed projects varies over the time of the day. We can see that the ratio between failed and successful projects is almost 1 (a bit less actually) for projects launched between 2 and 3 pm. In contrary, the ratio for projects launched after 8 pm is much worse (in other words: by far more projects failed than succeeded)." }, { "code": null, "e": 17592, "s": 17375, "text": "In general, there are more projects launched either in the early morning (between 0 and 6 am) and more projects launched in the late afternoon/evening (between 4 and 23 pm) compared to the time between 7 am and 3 pm." }, { "code": null, "e": 17947, "s": 17592, "text": "The ratio between successful and failed projects varies over the time of the day. We can see that the ratio between failed and successful projects is almost 1 (a bit less actually) for projects launched between 2 and 3 pm. In contrary, the ratio for projects launched after 8 pm is much worse (in other words: by far more projects failed than succeeded)." }, { "code": null, "e": 18042, "s": 17947, "text": "Let’s have a look whether the month the project was launched reveals anything about its state:" }, { "code": null, "e": 18259, "s": 18042, "text": "#plot the datasns.countplot(x=data_kick.launched_hour, hue = data_kick.state)#set labels and titleax.set(xlabel='Month of the Year', ylabel='Number of Projects', title= 'Month the Project was Launched')" }, { "code": null, "e": 18452, "s": 18259, "text": "Compared to the hour of the day, the months do not seem to reveal any surprising insights. However, note that there are by far fewer projects launched in December compared to all other months." }, { "code": null, "e": 18791, "s": 18452, "text": "Finally, let us look at the span between launched and deadline. We can obtain this span easily by subtracting launched from deadline (this is a useful feature of the date_time transformation we have done earlier). In the code below, we take the difference between launched and deadline and extract the days immediately (‘timedelta64[D]’):" }, { "code": null, "e": 18972, "s": 18791, "text": "data_kick['project_time'] = (data_kick['deadline'] -data_kick['launched']).astype('timedelta64[D]').astype(int)data_kick['project_time'].head(5)0 581 592 443 294 55" }, { "code": null, "e": 19473, "s": 18972, "text": "You can see that our new column project_time measures the span between launch and deadline in days. For example, the first project in the dataset ([0]) was on Kickstarter for almost two months (58 days). Before we visualize the span for a project, let us bin the results. The maximum of data_kick[‘project_time’] is at 91, so instead of getting 91 different results, we could bin the data by week to get a more intuitive overview. Let us first write a function that allows us to effectively bin data:" }, { "code": null, "e": 19802, "s": 19473, "text": "def discretizer(data, binning_values, labels): \"\"\" Input: data series that should be discretized bininningvalues: enter numerical array of binning cuts labels: enter string array of names for binsOutput: gives you a list of binned data \"\"\" data = pd.cut(data, bins=binning_values, labels=labels) return data" }, { "code": null, "e": 19851, "s": 19802, "text": "Let’s parse in project_time and bin it by weeks:" }, { "code": null, "e": 20509, "s": 19851, "text": "#save the binned data as new columndata_kick[\"project_time_weeks\"] =#call the discretizer funtiondiscretizer(#first thing we pass is the column we want to be discretized, project_time in this casedata_kick['project_time'],#next, we create a list with the different binning intervals (starting at 0 and then going in steps of 7 until the maximum value of project_time (+7)list(range(0,max(data_kick['project_time'])+7,7)),#last but not least, we need to label the bins. We number them by creating a list from 1 (first week) to the last week depending on the maximum value of project_timelist(range(1,max(list(range(0,max(data_kick['project_time'])//7+2))))))" }, { "code": null, "e": 20568, "s": 20509, "text": "So what does the new column, project_time_weeks look like?" }, { "code": null, "e": 20863, "s": 20568, "text": "#print first 5 rows of both columns:data_kick[['project_time', 'project_time_weeks']].head(5)#resulting in:project_time project_time_weeks 34 5 19 3 29 5 27 4 14 2" }, { "code": null, "e": 21072, "s": 20863, "text": "We can see that the days were successfully binned by weeks. E.g. 19 days are converted to week 3. Now, finally, let’s have a luck whether the time between launch and deadline affects the success of a project:" }, { "code": null, "e": 21190, "s": 21072, "text": "#plot the datasns.countplot(x=data_kick.project_time_discret, hue = data_reduced.state, palette=colors)" }, { "code": null, "e": 21356, "s": 21190, "text": "We instantly notice that most projects are put on Kickstarter for about 5 weeks and almost all projects are live between 1 and 9 weeks (so a bit more than 2 months)." }, { "code": null, "e": 21885, "s": 21356, "text": "The proportion between successful and failed projects varies over time: Projects with a short run time (1–4 weeks) succeed relatively more often compared to projects that are launched with a medium to long run time (5–13 weeks). This insight could support the hypothesis that project are not more likely to succeed the longer they are live as one might have assumed beforehand (-> the longer a project is live, the more people have the chance to see it over time, the more likely it will succeed. This does not seem to be true)." }, { "code": null, "e": 22116, "s": 21885, "text": "Now we take a look at the role of backers that support each project. In general, we would expect that a high number of backers contribute positively to the likelihood of success for a specific project. But is this really the case?" }, { "code": null, "e": 22201, "s": 22116, "text": "Let us visualize the number of backers, amount pledged and the state of the project." }, { "code": null, "e": 22529, "s": 22201, "text": "ax = sns.scatterplot(x=data_kick.backers, y=data_kick.usd_pledged_real/1e6, hue=data_kick.state, palette=colors)#we set the xlim to 100,000 backers to get a better overviewax.set(ylim=(-1,None), xlim=(-1,100000))#set labels and titleax.set(xlabel='Number of Backers', ylabel='USD Pledged in Million', title= 'Backer vs Pledge')" }, { "code": null, "e": 22570, "s": 22529, "text": "The code results in the following graph:" }, { "code": null, "e": 23047, "s": 22570, "text": "This result isn’t surprising, is it? We can clearly see that the number of backers correlates with the success of a project. Most projects that fail also have a (relatively) smaller number of backers. However, let’s go further: Not only the absolute number of backers per project is interesting but the average amount spent by each backer per project. In order to get this attribute, we need to divide the amount pledged by the number of actual backers. Let’s do that quickly." }, { "code": null, "e": 23434, "s": 23047, "text": "#divide usd_pledged_real by number of backers (note that a Zerodivisionerror will occur if we divide by zero resulting in a NaN. We replace these with 0data_kick['backer_ratio'] = (data_kick['usd_pledged_real']//data_kick['backers']).fillna(0)#set label and titleax.set(xlabel='Pledge/Backer Ratio (funding per backer)', ylabel='USD Pledged in Million', title= 'Backer Ratio vs Pledge')" }, { "code": null, "e": 23868, "s": 23434, "text": "Looking at the backer ratio (hence the sum of the amount pledged divided by the total number of backers) we can see that most successful projects have a relatively low backer ratio, meaning that each backer contributes a relatively small amount. According to the graph, this amount varies between shortly above 0 USD and up to around 700 USD. We can see that most projects that have relatively high backer ratios (<2,000 USD) failed." }, { "code": null, "e": 24093, "s": 23868, "text": "Now that we have looked at time frames, names, backers and many other details, it is time to stop our little walkthrough here. There are still plenty of possible insights and patterns to reveal but I leave this up to you ;-)" }, { "code": null, "e": 24107, "s": 24093, "text": "6. Conclusion" }, { "code": null, "e": 24248, "s": 24107, "text": "This introductory post about basic Data Visualization in Python revealed some interesting facts about Kickstarter projects. Let’s summarize:" }, { "code": null, "e": 24890, "s": 24248, "text": "Projects that fail, most of the times fail miserably. They “cannot move towards the blue line” as discussed in part 3. It’s all in or nothing ;-).The number and average goal of projects increased sharply over time (at least until 2015) whereas the provided pledges only slowly increase.Names play a big role. In case you want to launch a project, make sure you keep its name precise and short. “Tenacious Exclusive Scott Tolleson Uncle Argh NOIR Mini Qee” may sound funny (it actually doesn’t) but won’t get you anywhere.Try to launch your project between 12 and 4 pm and do NOT launch in December (Ok, I am not 100% serious about that one)." }, { "code": null, "e": 25037, "s": 24890, "text": "Projects that fail, most of the times fail miserably. They “cannot move towards the blue line” as discussed in part 3. It’s all in or nothing ;-)." }, { "code": null, "e": 25178, "s": 25037, "text": "The number and average goal of projects increased sharply over time (at least until 2015) whereas the provided pledges only slowly increase." }, { "code": null, "e": 25414, "s": 25178, "text": "Names play a big role. In case you want to launch a project, make sure you keep its name precise and short. “Tenacious Exclusive Scott Tolleson Uncle Argh NOIR Mini Qee” may sound funny (it actually doesn’t) but won’t get you anywhere." }, { "code": null, "e": 25535, "s": 25414, "text": "Try to launch your project between 12 and 4 pm and do NOT launch in December (Ok, I am not 100% serious about that one)." } ]
How can I insert default value in MySQL ENUM data type?
We can do it with the help of the DEFAULT attribute of the ENUM data type. The DEFAULT attribute causes an ENUM data type to have a default value when a value is not specified. In other words, we can say that INSERT statement does not have to include a value for this field because if it does not include then the value following DEFAULT will be inserted. Functions are not allowed in the DEFAULT expression. For ENUM data type the DEFAULT values include NULL and empty string (‘’). mysql> Create table enum123(Rollno INT, Name Varchar(20), result ENUM('Pass','Fail') DEFAULT 'Fail'); Query OK, 0 rows affected (0.12 sec) mysql> Insert into enum123(Rollno, Name) Values(25, 'Raman'); Query OK, 1 row affected (0.13 sec) We have not inserted any value in ‘result’ column hence it will pick the word following DEFAULT as the value. In this case by default value ‘fail’ would be inserted. mysql> Select * from enum123; +---------+--------+--------+ | Rollno | Name | result | +---------+--------+--------+ | 25 | Raman | Fail | +---------+--------+--------+ 1 row in set (0.00 sec)
[ { "code": null, "e": 1545, "s": 1062, "text": "We can do it with the help of the DEFAULT attribute of the ENUM data type. The DEFAULT attribute causes an ENUM data type to have a default value when a value is not specified. In other words, we can say that INSERT statement does not have to include a value for this field because if it does not include then the value following DEFAULT will be inserted. Functions are not allowed in the DEFAULT expression. For ENUM data type the DEFAULT values include NULL and empty string (‘’)." }, { "code": null, "e": 1783, "s": 1545, "text": "mysql> Create table enum123(Rollno INT, Name Varchar(20), result ENUM('Pass','Fail') DEFAULT 'Fail');\nQuery OK, 0 rows affected (0.12 sec)\n\nmysql> Insert into enum123(Rollno, Name) Values(25, 'Raman');\nQuery OK, 1 row affected (0.13 sec)" }, { "code": null, "e": 1949, "s": 1783, "text": "We have not inserted any value in ‘result’ column hence it will pick the word following DEFAULT as the value. In this case by default value ‘fail’ would be inserted." }, { "code": null, "e": 2153, "s": 1949, "text": "mysql> Select * from enum123;\n+---------+--------+--------+\n| Rollno | Name | result |\n+---------+--------+--------+\n| 25 | Raman | Fail |\n+---------+--------+--------+\n1 row in set (0.00 sec)" } ]
React ES6 Spread Operator
The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object. const numbersOne = [1, 2, 3]; const numbersTwo = [4, 5, 6]; const numbersCombined = [...numbersOne, ...numbersTwo]; Try it Yourself » The spread operator is often used in combination with destructuring. Assign the first and second items from numbers to variables and put the rest in an array: const numbers = [1, 2, 3, 4, 5, 6]; const [one, two, ...rest] = numbers; Try it Yourself » We can use the spread operator with objects too: Combine these two objects: const myVehicle = { brand: 'Ford', model: 'Mustang', color: 'red' } const updateMyVehicle = { type: 'car', year: 2021, color: 'yellow' } const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle} Try it Yourself » Notice the properties that did not match were combined, but the property that did match, color, was overwritten by the last object that was passed, updateMyVehicle. The resulting color is now yellow. Use the spread operator to combine the following arrays. const arrayOne = ['a', 'b', 'c']; const arrayTwo = [1, 2, 3]; const arraysCombined = []; Start the Exercise We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: [email protected] Your message has been sent to W3Schools.
[ { "code": null, "e": 136, "s": 0, "text": "The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object." }, { "code": null, "e": 252, "s": 136, "text": "const numbersOne = [1, 2, 3];\nconst numbersTwo = [4, 5, 6];\nconst numbersCombined = [...numbersOne, ...numbersTwo];" }, { "code": null, "e": 272, "s": 252, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 341, "s": 272, "text": "The spread operator is often used in combination with destructuring." }, { "code": null, "e": 431, "s": 341, "text": "Assign the first and second items from numbers to variables and put the rest in an array:" }, { "code": null, "e": 505, "s": 431, "text": "const numbers = [1, 2, 3, 4, 5, 6];\n\nconst [one, two, ...rest] = numbers;" }, { "code": null, "e": 525, "s": 505, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 574, "s": 525, "text": "We can use the spread operator with objects too:" }, { "code": null, "e": 601, "s": 574, "text": "Combine these two objects:" }, { "code": null, "e": 813, "s": 601, "text": "const myVehicle = {\n brand: 'Ford',\n model: 'Mustang',\n color: 'red'\n}\n\nconst updateMyVehicle = {\n type: 'car',\n year: 2021, \n color: 'yellow'\n}\n\nconst myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}" }, { "code": null, "e": 833, "s": 813, "text": "\nTry it Yourself »\n" }, { "code": null, "e": 1033, "s": 833, "text": "Notice the properties that did not match were combined, but the property that did match, color, was overwritten by the last object that was passed, updateMyVehicle. The resulting color is now yellow." }, { "code": null, "e": 1090, "s": 1033, "text": "Use the spread operator to combine the following arrays." }, { "code": null, "e": 1180, "s": 1090, "text": "const arrayOne = ['a', 'b', 'c'];\nconst arrayTwo = [1, 2, 3];\nconst arraysCombined = [];\n" }, { "code": null, "e": 1199, "s": 1180, "text": "Start the Exercise" }, { "code": null, "e": 1232, "s": 1199, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1274, "s": 1232, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1381, "s": 1274, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1400, "s": 1381, "text": "[email protected]" } ]
How to Make a Login and Sign Up Application in MIT App Inventor using Firebase? - GeeksforGeeks
06 Jun, 2021 Prerequisite: Welcome to The Modern Android App Development Hello geeks, today we are going to make a very basic level login and sign up the application using MIT App Inventor and we will learn that how we can connect MIT App Inventor to Firebase and store data which we have collected from the user. And using that data we can detect that username and password of the user exist on our database or not. MIT App Inventor: MIT App Inventor is an intuitive, visual programming environment that allows everyone even children to build fully functional apps for smartphones and tablets. Firebase: Firebase is an open-source platform(real-time database) developed by Google so that developers can use it to store the data of applications and implement their work easily. So, after knowing about these basic terminologies firstly we will see how to add a project on firebase so that we can collect data of our application in that project. Step 1: Open the portal https://firebase.google.com/ and create or open your account. Step 2: After creating an account click on go to console, and such a screen will appear. Step 3: Click on Add project > give your project a name > click on continue > click on create project. Step 4: Such screen will appear so select real-time database from the sidebar Step 5: After selecting a real-time database new screen will appear. Click on create database > next > enable. Step 6: On-screen different options will appear so click on rules so that we can make changes to them as per our requirement. After that use the following code. { "rules": { ".read": true, ".write": true } } After using the following code click on publish. And we are done with our work on firebase. Step 1: Open the portal http://ai2.appinventor.mit.edu/ and create a new project. Name it according to your convenience. Step 2: While designing your application follow the following steps. Step 2.1: Select Vertical arrangement from the palette and add other components to it as shown below. Step 2.2: Now go to properties of VerticalArrangement1 and uncheck the property visible from it. And then the screen will become blank. Step 2.3: Drag a new Vertical Arrangement from the palette and design it as shown below. Step 2.4: Now go to properties of VerticalArrangement2 and uncheck the property visible > go to properties of VerticalArrangement1 and check property visible. Note: Do not forget to add Firebase from the palette to VerticalArrangement1 as we have to use firebase to store data from here. Step 3: Go to blocks, where we have to write the logic for our application. Use the logic as shown below. Now we are also done with the MIT App Inventor designing and blocks part, now let us see that how we can connect Firebase(our real-time database) to MIT App Inventor. Connecting Firebase with MIT App Inventor. Step 1: Go to your Firebase Realtime Database and copy the link as shown below Step 2: Select FirebaseDB1 in MIT App inventor and in its properties paste the link which we copied above. Congratulations! You have successfully made the login and signup application using Firebase. And here is the output of our application. Output: When the user clicks on sign up its data is sent to Firebase where we can check that while the user logs in then the data exists in our database or not if data exist then login is successful otherwise “Incorrect Username or password” message is displayed. Here you can see that when the user clicked on the sign-up button data came to our Real-time Database(firebase). Hence, we made an application which uses firebase for realtime updation of data and user can easily login through it. Android-Misc Android Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Retrofit with Kotlin Coroutine in Android Android Listview in Java with Example How to Read Data from SQLite Database in Android? How to Change the Background Color After Clicking the Button in Android? Flutter - Custom Bottom Navigation Bar MVP (Model View Presenter) Architecture Pattern in Android with Example How to Add Image to Drawable Folder in Android Studio? How to Post Data to API using Retrofit in Android? Fragment Lifecycle in Android How to Save Data to the Firebase Realtime Database in Android?
[ { "code": null, "e": 25036, "s": 25008, "text": "\n06 Jun, 2021" }, { "code": null, "e": 25096, "s": 25036, "text": "Prerequisite: Welcome to The Modern Android App Development" }, { "code": null, "e": 25440, "s": 25096, "text": "Hello geeks, today we are going to make a very basic level login and sign up the application using MIT App Inventor and we will learn that how we can connect MIT App Inventor to Firebase and store data which we have collected from the user. And using that data we can detect that username and password of the user exist on our database or not." }, { "code": null, "e": 25620, "s": 25440, "text": "MIT App Inventor: MIT App Inventor is an intuitive, visual programming environment that allows everyone even children to build fully functional apps for smartphones and tablets. " }, { "code": null, "e": 25803, "s": 25620, "text": "Firebase: Firebase is an open-source platform(real-time database) developed by Google so that developers can use it to store the data of applications and implement their work easily." }, { "code": null, "e": 25970, "s": 25803, "text": "So, after knowing about these basic terminologies firstly we will see how to add a project on firebase so that we can collect data of our application in that project." }, { "code": null, "e": 26056, "s": 25970, "text": "Step 1: Open the portal https://firebase.google.com/ and create or open your account." }, { "code": null, "e": 26145, "s": 26056, "text": "Step 2: After creating an account click on go to console, and such a screen will appear." }, { "code": null, "e": 26249, "s": 26145, "text": "Step 3: Click on Add project > give your project a name > click on continue > click on create project. " }, { "code": null, "e": 26327, "s": 26249, "text": "Step 4: Such screen will appear so select real-time database from the sidebar" }, { "code": null, "e": 26438, "s": 26327, "text": "Step 5: After selecting a real-time database new screen will appear. Click on create database > next > enable." }, { "code": null, "e": 26599, "s": 26438, "text": "Step 6: On-screen different options will appear so click on rules so that we can make changes to them as per our requirement. After that use the following code." }, { "code": null, "e": 26656, "s": 26599, "text": "{\n \"rules\": \n {\n \".read\": true,\n \".write\": true\n }\n}" }, { "code": null, "e": 26748, "s": 26656, "text": "After using the following code click on publish. And we are done with our work on firebase." }, { "code": null, "e": 26869, "s": 26748, "text": "Step 1: Open the portal http://ai2.appinventor.mit.edu/ and create a new project. Name it according to your convenience." }, { "code": null, "e": 26938, "s": 26869, "text": "Step 2: While designing your application follow the following steps." }, { "code": null, "e": 27040, "s": 26938, "text": "Step 2.1: Select Vertical arrangement from the palette and add other components to it as shown below." }, { "code": null, "e": 27176, "s": 27040, "text": "Step 2.2: Now go to properties of VerticalArrangement1 and uncheck the property visible from it. And then the screen will become blank." }, { "code": null, "e": 27265, "s": 27176, "text": "Step 2.3: Drag a new Vertical Arrangement from the palette and design it as shown below." }, { "code": null, "e": 27424, "s": 27265, "text": "Step 2.4: Now go to properties of VerticalArrangement2 and uncheck the property visible > go to properties of VerticalArrangement1 and check property visible." }, { "code": null, "e": 27553, "s": 27424, "text": "Note: Do not forget to add Firebase from the palette to VerticalArrangement1 as we have to use firebase to store data from here." }, { "code": null, "e": 27659, "s": 27553, "text": "Step 3: Go to blocks, where we have to write the logic for our application. Use the logic as shown below." }, { "code": null, "e": 27869, "s": 27659, "text": "Now we are also done with the MIT App Inventor designing and blocks part, now let us see that how we can connect Firebase(our real-time database) to MIT App Inventor. Connecting Firebase with MIT App Inventor." }, { "code": null, "e": 27948, "s": 27869, "text": "Step 1: Go to your Firebase Realtime Database and copy the link as shown below" }, { "code": null, "e": 28055, "s": 27948, "text": "Step 2: Select FirebaseDB1 in MIT App inventor and in its properties paste the link which we copied above." }, { "code": null, "e": 28191, "s": 28055, "text": "Congratulations! You have successfully made the login and signup application using Firebase. And here is the output of our application." }, { "code": null, "e": 28199, "s": 28191, "text": "Output:" }, { "code": null, "e": 28568, "s": 28199, "text": "When the user clicks on sign up its data is sent to Firebase where we can check that while the user logs in then the data exists in our database or not if data exist then login is successful otherwise “Incorrect Username or password” message is displayed. Here you can see that when the user clicked on the sign-up button data came to our Real-time Database(firebase)." }, { "code": null, "e": 28686, "s": 28568, "text": "Hence, we made an application which uses firebase for realtime updation of data and user can easily login through it." }, { "code": null, "e": 28699, "s": 28686, "text": "Android-Misc" }, { "code": null, "e": 28707, "s": 28699, "text": "Android" }, { "code": null, "e": 28715, "s": 28707, "text": "Android" }, { "code": null, "e": 28813, "s": 28715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28822, "s": 28813, "text": "Comments" }, { "code": null, "e": 28835, "s": 28822, "text": "Old Comments" }, { "code": null, "e": 28877, "s": 28835, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 28915, "s": 28877, "text": "Android Listview in Java with Example" }, { "code": null, "e": 28965, "s": 28915, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29038, "s": 28965, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 29077, "s": 29038, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29149, "s": 29077, "text": "MVP (Model View Presenter) Architecture Pattern in Android with Example" }, { "code": null, "e": 29204, "s": 29149, "text": "How to Add Image to Drawable Folder in Android Studio?" }, { "code": null, "e": 29255, "s": 29204, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 29285, "s": 29255, "text": "Fragment Lifecycle in Android" } ]
HTML <time> Tag - GeeksforGeeks
17 Mar, 2022 The <time> tag is used to display the human-readable date/time. It can also be used to encode dates and times in a machine-readable form. The main advantage for users is that they can offer to add birthday reminders or scheduled events in their calendar’s and search engines can produce smarter search results. Syntax: <time attribute> Time... </time> Attributes: This tag contains an optional attribute datetime which is used to define the date/time in a machine-readable form of the <time> element.Example: HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><time> Tag</h2> <p>I Wake up at <time>6.00</time> in every morning.</p> <p>Jawahar lal Nehru birthday is celebrated on <time datatime="2018--11-14 12:00">children's day.</time> </p> </body></html> Output: Supported Browsers: Google Chrome 6.0 and above Internet Explorer 9.0 and above Firefox 4.0 and above Opera 11.1 and above Safari 5.0 and above Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. arorakashish0911 shubhamyadav4 clintra jochenhansoul HTML-Tags Technical Scripter 2018 HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ? CSS to put icon inside an input element in a form HTML Cheat Sheet - A Basic Guide to HTML
[ { "code": null, "e": 24317, "s": 24289, "text": "\n17 Mar, 2022" }, { "code": null, "e": 24628, "s": 24317, "text": "The <time> tag is used to display the human-readable date/time. It can also be used to encode dates and times in a machine-readable form. The main advantage for users is that they can offer to add birthday reminders or scheduled events in their calendar’s and search engines can produce smarter search results." }, { "code": null, "e": 24637, "s": 24628, "text": "Syntax: " }, { "code": null, "e": 24670, "s": 24637, "text": "<time attribute> Time... </time>" }, { "code": null, "e": 24828, "s": 24670, "text": "Attributes: This tag contains an optional attribute datetime which is used to define the date/time in a machine-readable form of the <time> element.Example: " }, { "code": null, "e": 24833, "s": 24828, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><time> Tag</h2> <p>I Wake up at <time>6.00</time> in every morning.</p> <p>Jawahar lal Nehru birthday is celebrated on <time datatime=\"2018--11-14 12:00\">children's day.</time> </p> </body></html>", "e": 25151, "s": 24833, "text": null }, { "code": null, "e": 25161, "s": 25151, "text": "Output: " }, { "code": null, "e": 25181, "s": 25161, "text": "Supported Browsers:" }, { "code": null, "e": 25209, "s": 25181, "text": "Google Chrome 6.0 and above" }, { "code": null, "e": 25241, "s": 25209, "text": "Internet Explorer 9.0 and above" }, { "code": null, "e": 25263, "s": 25241, "text": "Firefox 4.0 and above" }, { "code": null, "e": 25284, "s": 25263, "text": "Opera 11.1 and above" }, { "code": null, "e": 25305, "s": 25284, "text": "Safari 5.0 and above" }, { "code": null, "e": 25442, "s": 25305, "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": 25459, "s": 25442, "text": "arorakashish0911" }, { "code": null, "e": 25473, "s": 25459, "text": "shubhamyadav4" }, { "code": null, "e": 25481, "s": 25473, "text": "clintra" }, { "code": null, "e": 25495, "s": 25481, "text": "jochenhansoul" }, { "code": null, "e": 25505, "s": 25495, "text": "HTML-Tags" }, { "code": null, "e": 25529, "s": 25505, "text": "Technical Scripter 2018" }, { "code": null, "e": 25534, "s": 25529, "text": "HTML" }, { "code": null, "e": 25539, "s": 25534, "text": "HTML" }, { "code": null, "e": 25637, "s": 25539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25687, "s": 25637, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 25749, "s": 25687, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 25797, "s": 25749, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 25857, "s": 25797, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 25910, "s": 25857, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 25971, "s": 25910, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 25995, "s": 25971, "text": "REST API (Introduction)" }, { "code": null, "e": 26045, "s": 25995, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26095, "s": 26045, "text": "CSS to put icon inside an input element in a form" } ]
Area of a Hexagon - GeeksforGeeks
07 Nov, 2021 A hexagon is a 6-sided, 2-dimensional geometric figure. The total of the internal angles of any hexagon is 720°. A regular hexagon has 6 rotational symmetries and 6 reflection symmetries. All internal angles are 120 degrees. Examples : Input: 4 Output: 41.5692 Input: 6 Output: 93.5307 Number of vertices: 6 Number of edges: 6 Internal angle: 120° Area = (3 √3(n)2 ) / 2 How does the formula work? There are mainly 6 equilateral triangles of side n and area of an equilateral triangle is (sqrt(3)/4) * n * n. Since in hexagon, there are total 6 equilateral triangles with side n, are of the hexagon becomes (3*sqrt(3)/2) * n * n C++ Java Python3 C# PHP Javascript // CPP program to find // area of a Hexagon#include <iostream>#include <math.h>using namespace std; // function for calculating// area of the hexagon.double hexagonArea(double s){ return ((3 * sqrt(3) * (s * s)) / 2); } // Driver Codeint main(){ // Length of a side double s = 4; cout << "Area : " << hexagonArea(s); return 0;} class GFG { // Create a function for calculating // the area of the hexagon. public static double hexagonArea(double s) { return ((3 * Math.sqrt(3) * (s * s)) / 2); } // Driver Code public static void main(String[] args) { // Length of a side double s = 4; System.out.print("Area: " + hexagonArea(s) ); }} # Python3 program to find# area of a Hexagonimport math # Function for calculating # area of the hexagon.def hexagonArea(s): return ((3 * math.sqrt(3) * (s * s)) / 2); # Driver code if __name__ == "__main__" : # length of a side. s = 4 print("Area:","{0:.4f}" . format(hexagonArea(s))) # This code is contributed by Naman_Garg // C# program to find// area of a Hexagonusing System; class GFG { // Create a function for calculating // the area of the hexagon. public static double hexagonArea(double s) { return ((3 * Math.Sqrt(3) * (s * s)) / 2); } // Driver Code public static void Main() { // Length of a side double s = 4; Console.WriteLine("Area: " + hexagonArea(s) ); }} // This code is contributed by vt_m. <?php// PHP program to find // area of a Hexagon // function for calculating// area of the hexagon.function hexagonArea( $s){ return ((3 * sqrt(3) * ($s * $s)) / 2); } // Driver Code // Length of a side $s = 4; echo("Area : ");echo(hexagonArea($s)); // This code is contributed by vt_m.?> <script> // Javascript program to find // area of a Hexagon // function for calculating // area of the hexagon. function hexagonArea(s) { return ((3 * Math.sqrt(3) * (s * s)) / 2); } // Driver Code // Length of a side let s = 4; document.write("Area : " + hexagonArea(s)); // This code is contributed by Mayank Tyagi</script> Output : Area: 41.5692 vt_m jit_t Naman_Garg mayanktyagi1709 area-volume-programs Geometric School Programming Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Closest Pair of Points | O(nlogn) Implementation Given n line segments, find if any two segments intersect Convex Hull | Set 2 (Graham Scan) Equation of circle when three points on the circle are given Polygon Clipping | Sutherland–Hodgman Algorithm Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java Interfaces in Java
[ { "code": null, "e": 24869, "s": 24841, "text": "\n07 Nov, 2021" }, { "code": null, "e": 25096, "s": 24869, "text": "A hexagon is a 6-sided, 2-dimensional geometric figure. The total of the internal angles of any hexagon is 720°. A regular hexagon has 6 rotational symmetries and 6 reflection symmetries. All internal angles are 120 degrees. " }, { "code": null, "e": 25109, "s": 25096, "text": "Examples : " }, { "code": null, "e": 25160, "s": 25109, "text": "Input: 4\nOutput: 41.5692\n\nInput: 6\nOutput: 93.5307" }, { "code": null, "e": 25249, "s": 25164, "text": "Number of vertices: 6 Number of edges: 6 Internal angle: 120° Area = (3 √3(n)2 ) / 2" }, { "code": null, "e": 25508, "s": 25249, "text": "How does the formula work? There are mainly 6 equilateral triangles of side n and area of an equilateral triangle is (sqrt(3)/4) * n * n. Since in hexagon, there are total 6 equilateral triangles with side n, are of the hexagon becomes (3*sqrt(3)/2) * n * n " }, { "code": null, "e": 25512, "s": 25508, "text": "C++" }, { "code": null, "e": 25517, "s": 25512, "text": "Java" }, { "code": null, "e": 25525, "s": 25517, "text": "Python3" }, { "code": null, "e": 25528, "s": 25525, "text": "C#" }, { "code": null, "e": 25532, "s": 25528, "text": "PHP" }, { "code": null, "e": 25543, "s": 25532, "text": "Javascript" }, { "code": "// CPP program to find // area of a Hexagon#include <iostream>#include <math.h>using namespace std; // function for calculating// area of the hexagon.double hexagonArea(double s){ return ((3 * sqrt(3) * (s * s)) / 2); } // Driver Codeint main(){ // Length of a side double s = 4; cout << \"Area : \" << hexagonArea(s); return 0;}", "e": 25914, "s": 25543, "text": null }, { "code": "class GFG { // Create a function for calculating // the area of the hexagon. public static double hexagonArea(double s) { return ((3 * Math.sqrt(3) * (s * s)) / 2); } // Driver Code public static void main(String[] args) { // Length of a side double s = 4; System.out.print(\"Area: \" + hexagonArea(s) ); }}", "e": 26342, "s": 25914, "text": null }, { "code": "# Python3 program to find# area of a Hexagonimport math # Function for calculating # area of the hexagon.def hexagonArea(s): return ((3 * math.sqrt(3) * (s * s)) / 2); # Driver code if __name__ == \"__main__\" : # length of a side. s = 4 print(\"Area:\",\"{0:.4f}\" . format(hexagonArea(s))) # This code is contributed by Naman_Garg", "e": 26728, "s": 26342, "text": null }, { "code": "// C# program to find// area of a Hexagonusing System; class GFG { // Create a function for calculating // the area of the hexagon. public static double hexagonArea(double s) { return ((3 * Math.Sqrt(3) * (s * s)) / 2); } // Driver Code public static void Main() { // Length of a side double s = 4; Console.WriteLine(\"Area: \" + hexagonArea(s) ); }} // This code is contributed by vt_m.", "e": 27245, "s": 26728, "text": null }, { "code": "<?php// PHP program to find // area of a Hexagon // function for calculating// area of the hexagon.function hexagonArea( $s){ return ((3 * sqrt(3) * ($s * $s)) / 2); } // Driver Code // Length of a side $s = 4; echo(\"Area : \");echo(hexagonArea($s)); // This code is contributed by vt_m.?>", "e": 27553, "s": 27245, "text": null }, { "code": "<script> // Javascript program to find // area of a Hexagon // function for calculating // area of the hexagon. function hexagonArea(s) { return ((3 * Math.sqrt(3) * (s * s)) / 2); } // Driver Code // Length of a side let s = 4; document.write(\"Area : \" + hexagonArea(s)); // This code is contributed by Mayank Tyagi</script>", "e": 27928, "s": 27553, "text": null }, { "code": null, "e": 27939, "s": 27928, "text": "Output : " }, { "code": null, "e": 27953, "s": 27939, "text": "Area: 41.5692" }, { "code": null, "e": 27960, "s": 27955, "text": "vt_m" }, { "code": null, "e": 27966, "s": 27960, "text": "jit_t" }, { "code": null, "e": 27977, "s": 27966, "text": "Naman_Garg" }, { "code": null, "e": 27993, "s": 27977, "text": "mayanktyagi1709" }, { "code": null, "e": 28014, "s": 27993, "text": "area-volume-programs" }, { "code": null, "e": 28024, "s": 28014, "text": "Geometric" }, { "code": null, "e": 28043, "s": 28024, "text": "School Programming" }, { "code": null, "e": 28053, "s": 28043, "text": "Geometric" }, { "code": null, "e": 28151, "s": 28053, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28160, "s": 28151, "text": "Comments" }, { "code": null, "e": 28173, "s": 28160, "text": "Old Comments" }, { "code": null, "e": 28222, "s": 28173, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 28280, "s": 28222, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28314, "s": 28280, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 28375, "s": 28314, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 28423, "s": 28375, "text": "Polygon Clipping | Sutherland–Hodgman Algorithm" }, { "code": null, "e": 28441, "s": 28423, "text": "Python Dictionary" }, { "code": null, "e": 28457, "s": 28441, "text": "Arrays in C/C++" }, { "code": null, "e": 28476, "s": 28457, "text": "Inheritance in C++" }, { "code": null, "e": 28501, "s": 28476, "text": "Reverse a string in Java" } ]
Find Second largest element in an array - GeeksforGeeks
27 Feb, 2022 Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array. Example: Input: arr[] = {12, 35, 1, 10, 34, 1} Output: The second largest element is 34. Explanation: The largest element of the array is 35 and the second largest element is 34 Input: arr[] = {10, 5, 10} Output: The second largest element is 5. Explanation: The largest element of the array is 10 and the second largest element is 5 Input: arr[] = {10, 10, 10} Output: The second largest does not exist. Explanation: Largest element of the array is 10 there is no second largest element Simple Solution Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array. C++14 Java Python3 C# Javascript // C++ program to find second largest// element in an array #include <bits/stdc++.h>using namespace std; /* Function to print the second largest elements */void print2largest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(" Invalid Input "); return; } // sort the array sort(arr, arr + arr_size); // start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { printf("The second largest element is %d\n", arr[i]); return; } } printf("There is no second largest element\n");} /* Driver program to test above function */int main(){ int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print2largest(arr, n); return 0;} // Java program to find second largest// element in an arrayimport java.util.*;class GFG{ // Function to print the// second largest elementsstatic void print2largest(int arr[], int arr_size){ int i, first, second; // There should be // atleast two elements if (arr_size < 2) { System.out.printf(" Invalid Input "); return; } // Sort the array Arrays.sort(arr); // Start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // If the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { System.out.printf("The second largest " + "element is %d\n", arr[i]); return; } } System.out.printf("There is no second " + "largest element\n");} // Driver codepublic static void main(String[] args){ int arr[] = {12, 35, 1, 10, 34, 1}; int n = arr.length; print2largest(arr, n);}} // This code is contributed by gauravrajput1 # Python3 program to find second# largest element in an array # Function to print the# second largest elementsdef print2largest(arr, arr_size): # There should be # atleast two elements if (arr_size < 2): print(" Invalid Input ") return # Sort the array arr.sort # Start from second last # element as the largest # element is at last for i in range(arr_size-2, -1, -1): # If the element is not # equal to largest element if (arr[i] != arr[arr_size - 1]) : print("The second largest element is", arr[i]) return print("There is no second largest element") # Driver codearr = [12, 35, 1, 10, 34, 1]n = len(arr)print2largest(arr, n) # This code is contributed by divyeshrabadiya07 // C# program to find second largest// element in an arrayusing System; class GFG{ // Function to print the// second largest elementsstatic void print2largest(int []arr, int arr_size){ int i; // There should be // atleast two elements if (arr_size < 2) { Console.Write(" Invalid Input "); return; } // Sort the array Array.Sort(arr); // Start from second last element // as the largest element is at last for(i = arr_size - 2; i >= 0; i--) { // If the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { Console.Write("The second largest " + "element is {0}\n", arr[i]); return; } } Console.Write("There is no second " + "largest element\n");} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 35, 1, 10, 34, 1 }; int n = arr.Length; print2largest(arr, n);}} // This code is contributed by Amit Katiyar <script> // Javascript program to find second largest// element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i, first, second; // There should be atleast two elements if (arr_size < 2) { document.write(" Invalid Input "); return; } // sort the array arr.sort(); // start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { document.write("The second largest element is " + arr[i]); return; } } document.write("There is no second largest element<br>"); } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); // This code is contributed by Surbhi Tyagi </script> The second largest element is 34 Complexity Analysis: Time Complexity: O(n log n). Time required to sort the array is O(n log n). Auxiliary space: O(1). As no extra space is required. Better Solution: Approach: The approach is to traverse the array twice. In the first traversal find the maximum element. In the second traversal find the greatest element in the remaining excluding the previous greatest. C++14 Java Python3 C# Javascript // C++ program to find the second largest element in the array#include <iostream>using namespace std; int secondLargest(int arr[], int n) { int largest = 0, secondLargest = -1; // finding the largest element in the array for (int i = 1; i < n; i++) { if (arr[i] > arr[largest]) largest = i; } // finding the largest element in the array excluding // the largest element calculated above for (int i = 0; i < n; i++) { if (arr[i] != arr[largest]) { // first change the value of second largest // as soon as the next element is found if (secondLargest == -1) secondLargest = i; else if (arr[i] > arr[secondLargest]) secondLargest = i; } } return secondLargest;} int main() { int arr[] = {10, 12, 20, 4}; int n = sizeof(arr)/sizeof(arr[0]); int second_Largest = secondLargest(arr, n); if (second_Largest == -1) cout << "Second largest didn't exit\n"; else cout << "Second largest : " << arr[second_Largest];} // Java program to find second largest// element in an arrayclass GFG{ // Function to print the second largest elementsstatic void print2largest(int arr[], int arr_size){ int i, first, second; // There should be atleast two elements if (arr_size < 2) { System.out.printf(" Invalid Input "); return; } int largest = second = Integer.MIN_VALUE; // Find the largest element for(i = 0; i < arr_size; i++) { largest = Math.max(largest, arr[i]); } // Find the second largest element for(i = 0; i < arr_size; i++) { if (arr[i] != largest) second = Math.max(second, arr[i]); } if (second == Integer.MIN_VALUE) System.out.printf("There is no second " + "largest element\n"); else System.out.printf("The second largest " + "element is %d\n", second);} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = arr.length; print2largest(arr, n);}} // This code is contributed by Amit Katiyar # Python3 program to find# second largest element# in an array # Function to print# second largest elementsdef print2largest(arr, arr_size): # There should be atleast # two elements if (arr_size < 2): print(" Invalid Input "); return; largest = second = -2454635434; # Find the largest element for i in range(0, arr_size): largest = max(largest, arr[i]); # Find the second largest element for i in range(0, arr_size): if (arr[i] != largest): second = max(second, arr[i]); if (second == -2454635434): print("There is no second " + "largest element"); else: print("The second largest " + "element is \n", second); # Driver codeif __name__ == '__main__': arr = [12, 35, 1, 10, 34, 1]; n = len(arr); print2largest(arr, n); # This code is contributed by shikhasingrajput // C# program to find second largest// element in an arrayusing System; class GFG{ // Function to print the second largest elementsstatic void print2largest(int []arr, int arr_size){ // int first; int i, second; // There should be atleast two elements if (arr_size < 2) { Console.Write(" Invalid Input "); return; } int largest = second = int.MinValue; // Find the largest element for(i = 0; i < arr_size; i++) { largest = Math.Max(largest, arr[i]); } // Find the second largest element for(i = 0; i < arr_size; i++) { if (arr[i] != largest) second = Math.Max(second, arr[i]); } if (second == int.MinValue) Console.Write("There is no second " + "largest element\n"); else Console.Write("The second largest " + "element is {0}\n", second);} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 35, 1, 10, 34, 1 }; int n = arr.Length; print2largest(arr, n);}} // This code is contributed by Amit Katiyar <script> // Javascript program to find second largest// element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i; let largest = second = -2454635434; // There should be atleast two elements if (arr_size < 2) { document.write(" Invalid Input "); return; } // finding the largest element for (i = 0;i<arr_size;i++){ if (arr[i]>largest){ largest = arr[i]; } } // Now find the second largest element for (i = 0 ;i<arr_size;i++){ if (arr[i]>second && arr[i]<largest){ second = arr[i]; } } if (second == -2454635434){ document.write("There is no second largest element<br>"); } else{ document.write("The second largest element is " + second); return; } } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); </script> Second largest : 12 Complexity Analysis: Time Complexity: O(n). Two traversals of the array is needed. Auxiliary space: O(1). As no extra space is required. Efficient Solution Approach: Find the second largest element in a single traversal. Below is the complete algorithm for doing this: 1) Initialize the first as 0(i.e, index of arr[0] element 2) Start traversing the array from array[1], a) If the current element in array say arr[i] is greater than first. Then update first and second as, second = first first = arr[i] b) If the current element is in between first and second, then update second to store the value of current variable as second = arr[i] 3) Return the value stored in second. C C++ Java Python3 C# PHP Javascript // C program to find second largest// element in an array #include <limits.h>#include <stdio.h> /* Function to print the second largest elements */void print2largest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(" Invalid Input "); return; } first = second = INT_MIN; for (i = 0; i < arr_size; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == INT_MIN) printf("There is no second largest element\n"); else printf("The second largest element is %d", second);} /* Driver program to test above function */int main(){ int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print2largest(arr, n); return 0;} // C++ program to find the second largest element #include <iostream>using namespace std; // returns the index of second largest// if second largest didn't exist return -1int secondLargest(int arr[], int n) { int first = 0, second = -1; for (int i = 1; i < n; i++) { if (arr[i] > arr[first]) { second = first; first = i; } else if (arr[i] < arr[first]) { if (second == -1 || arr[second] < arr[i]) second = i; } } return second;} int main() { int arr[] = {10, 12, 20, 4}; int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0])); if (index == -1) cout << "Second Largest didn't exist"; else cout << "Second largest : " << arr[index];} // JAVA Code for Find Second largest// element in an arrayclass GFG { /* Function to print the second largest elements */ public static void print2largest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { System.out.print(" Invalid Input "); return; } first = second = Integer.MIN_VALUE; for (i = 0; i < arr_size; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == Integer.MIN_VALUE) System.out.print("There is no second largest" + " element\n"); else System.out.print("The second largest element" + " is " + second); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = arr.length; print2largest(arr, n); }}// This code is contributed by Arnav Kr. Mandal. # Python program to# find second largest# element in an array # Function to print the# second largest elementsdef print2largest(arr, arr_size): # There should be atleast # two elements if (arr_size < 2): print(" Invalid Input ") return first = second = -2147483648 for i in range(arr_size): # If current element is # smaller than first # then update both # first and second if (arr[i] > first): second = first first = arr[i] # If arr[i] is in # between first and # second then update second elif (arr[i] > second and arr[i] != first): second = arr[i] if (second == -2147483648): print("There is no second largest element") else: print("The second largest element is", second) # Driver program to test# above functionarr = [12, 35, 1, 10, 34, 1]n = len(arr) print2largest(arr, n) # This code is contributed# by Anant Agarwal. // C# Code for Find Second largest// element in an arrayusing System; class GFG { // Function to print the // second largest elements public static void print2largest(int[] arr, int arr_size) { int i, first, second; // There should be atleast two elements if (arr_size < 2) { Console.WriteLine(" Invalid Input "); return; } first = second = int.MinValue; for (i = 0; i < arr_size; i++) { // If current element is smaller than // first then update both first and second if (arr[i] > first) { second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == int.MinValue) Console.Write("There is no second largest" + " element\n"); else Console.Write("The second largest element" + " is " + second); } // Driver Code public static void Main(String[] args) { int[] arr = { 12, 35, 1, 10, 34, 1 }; int n = arr.Length; print2largest(arr, n); }} // This code is contributed by Parashar. <?php// PHP program to find second largest// element in an array // Function to print the// second largest elementsfunction print2largest($arr, $arr_size){ // There should be atleast // two elements if ($arr_size < 2) { echo(" Invalid Input "); return; } $first = $second = PHP_INT_MIN; for ($i = 0; $i < $arr_size ; $i++) { // If current element is // smaller than first // then update both // first and second if ($arr[$i] > $first) { $second = $first; $first = $arr[$i]; } // If arr[i] is in // between first and // second then update // second else if ($arr[$i] > $second && $arr[$i] != $first) $second = $arr[$i]; } if ($second == PHP_INT_MIN) echo("There is no second largest element\n"); else echo("The second largest element is " . $second . "\n");} // Driver Code$arr = array(12, 35, 1, 10, 34, 1);$n = sizeof($arr);print2largest($arr, $n); // This code is contributed by Ajit.?> <script> // Javascript program to find second largest// element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i; let largest = second = -2454635434; // There should be atleast two elements if (arr_size < 2) { document.write(" Invalid Input "); return; } // finding the largest element for (i = 0 ;i<arr_size;i++){ if (arr[i]>largest){ second = largest ; largest = arr[i] } else if (arr[i]!=largest && arr[i]>second ){ second = arr[i]; } } if (second == -2454635434){ document.write("There is no second largest element<br>"); } else{ document.write("The second largest element is " + second); return; } } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); // This code is contributed by Shaswat Singh </script> Output: Second largest : 34 Complexity Analysis: Time Complexity: O(n). Only one traversal of the array is needed. Auxiliary space: O(1). As no extra space is required. Related Article: Smallest and second smallest element in an arrayThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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. Shubham Bansal 13 parashar jit_t HiteshParrru andrew1234 shivanisinghss2110 amit143katiyar GauravRajput1 shikhasingrajput divyeshrabadiya07 surbhityagi15 shaswatsingh1 itsvishal2417 healer26mastercoding mayank021 Accolite FactSet Hike Order-Statistics SAP Labs Zoho Arrays Zoho Accolite FactSet Hike SAP Labs Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Write a program to reverse an array or string Multidimensional Arrays in Java Introduction to Arrays
[ { "code": null, "e": 41194, "s": 41166, "text": "\n27 Feb, 2022" }, { "code": null, "e": 41334, "s": 41194, "text": "Given an array of integers, our task is to write a program that efficiently finds the second largest element present in the array. Example:" }, { "code": null, "e": 41820, "s": 41334, "text": "Input: arr[] = {12, 35, 1, 10, 34, 1}\nOutput: The second largest element is 34.\nExplanation: The largest element of the \narray is 35 and the second \nlargest element is 34\n\nInput: arr[] = {10, 5, 10}\nOutput: The second largest element is 5.\nExplanation: The largest element of \nthe array is 10 and the second \nlargest element is 5\n\nInput: arr[] = {10, 10, 10}\nOutput: The second largest does not exist.\nExplanation: Largest element of the array \nis 10 there is no second largest element" }, { "code": null, "e": 41996, "s": 41820, "text": "Simple Solution Approach: The idea is to sort the array in descending order and then return the second element which is not equal to the largest element from the sorted array." }, { "code": null, "e": 42002, "s": 41996, "text": "C++14" }, { "code": null, "e": 42007, "s": 42002, "text": "Java" }, { "code": null, "e": 42015, "s": 42007, "text": "Python3" }, { "code": null, "e": 42018, "s": 42015, "text": "C#" }, { "code": null, "e": 42029, "s": 42018, "text": "Javascript" }, { "code": "// C++ program to find second largest// element in an array #include <bits/stdc++.h>using namespace std; /* Function to print the second largest elements */void print2largest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(\" Invalid Input \"); return; } // sort the array sort(arr, arr + arr_size); // start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { printf(\"The second largest element is %d\\n\", arr[i]); return; } } printf(\"There is no second largest element\\n\");} /* Driver program to test above function */int main(){ int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print2largest(arr, n); return 0;}", "e": 42987, "s": 42029, "text": null }, { "code": "// Java program to find second largest// element in an arrayimport java.util.*;class GFG{ // Function to print the// second largest elementsstatic void print2largest(int arr[], int arr_size){ int i, first, second; // There should be // atleast two elements if (arr_size < 2) { System.out.printf(\" Invalid Input \"); return; } // Sort the array Arrays.sort(arr); // Start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // If the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { System.out.printf(\"The second largest \" + \"element is %d\\n\", arr[i]); return; } } System.out.printf(\"There is no second \" + \"largest element\\n\");} // Driver codepublic static void main(String[] args){ int arr[] = {12, 35, 1, 10, 34, 1}; int n = arr.length; print2largest(arr, n);}} // This code is contributed by gauravrajput1", "e": 43991, "s": 42987, "text": null }, { "code": "# Python3 program to find second# largest element in an array # Function to print the# second largest elementsdef print2largest(arr, arr_size): # There should be # atleast two elements if (arr_size < 2): print(\" Invalid Input \") return # Sort the array arr.sort # Start from second last # element as the largest # element is at last for i in range(arr_size-2, -1, -1): # If the element is not # equal to largest element if (arr[i] != arr[arr_size - 1]) : print(\"The second largest element is\", arr[i]) return print(\"There is no second largest element\") # Driver codearr = [12, 35, 1, 10, 34, 1]n = len(arr)print2largest(arr, n) # This code is contributed by divyeshrabadiya07", "e": 44763, "s": 43991, "text": null }, { "code": "// C# program to find second largest// element in an arrayusing System; class GFG{ // Function to print the// second largest elementsstatic void print2largest(int []arr, int arr_size){ int i; // There should be // atleast two elements if (arr_size < 2) { Console.Write(\" Invalid Input \"); return; } // Sort the array Array.Sort(arr); // Start from second last element // as the largest element is at last for(i = arr_size - 2; i >= 0; i--) { // If the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { Console.Write(\"The second largest \" + \"element is {0}\\n\", arr[i]); return; } } Console.Write(\"There is no second \" + \"largest element\\n\");} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 35, 1, 10, 34, 1 }; int n = arr.Length; print2largest(arr, n);}} // This code is contributed by Amit Katiyar", "e": 45735, "s": 44763, "text": null }, { "code": "<script> // Javascript program to find second largest// element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i, first, second; // There should be atleast two elements if (arr_size < 2) { document.write(\" Invalid Input \"); return; } // sort the array arr.sort(); // start from second last element // as the largest element is at last for (i = arr_size - 2; i >= 0; i--) { // if the element is not // equal to largest element if (arr[i] != arr[arr_size - 1]) { document.write(\"The second largest element is \" + arr[i]); return; } } document.write(\"There is no second largest element<br>\"); } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); // This code is contributed by Surbhi Tyagi </script>", "e": 46770, "s": 45735, "text": null }, { "code": null, "e": 46804, "s": 46770, "text": "The second largest element is 34\n" }, { "code": null, "e": 46825, "s": 46804, "text": "Complexity Analysis:" }, { "code": null, "e": 46901, "s": 46825, "text": "Time Complexity: O(n log n). Time required to sort the array is O(n log n)." }, { "code": null, "e": 46955, "s": 46901, "text": "Auxiliary space: O(1). As no extra space is required." }, { "code": null, "e": 47028, "s": 46955, "text": "Better Solution: Approach: The approach is to traverse the array twice. " }, { "code": null, "e": 47078, "s": 47028, "text": "In the first traversal find the maximum element. " }, { "code": null, "e": 47178, "s": 47078, "text": "In the second traversal find the greatest element in the remaining excluding the previous greatest." }, { "code": null, "e": 47184, "s": 47178, "text": "C++14" }, { "code": null, "e": 47189, "s": 47184, "text": "Java" }, { "code": null, "e": 47197, "s": 47189, "text": "Python3" }, { "code": null, "e": 47200, "s": 47197, "text": "C#" }, { "code": null, "e": 47211, "s": 47200, "text": "Javascript" }, { "code": "// C++ program to find the second largest element in the array#include <iostream>using namespace std; int secondLargest(int arr[], int n) { int largest = 0, secondLargest = -1; // finding the largest element in the array for (int i = 1; i < n; i++) { if (arr[i] > arr[largest]) largest = i; } // finding the largest element in the array excluding // the largest element calculated above for (int i = 0; i < n; i++) { if (arr[i] != arr[largest]) { // first change the value of second largest // as soon as the next element is found if (secondLargest == -1) secondLargest = i; else if (arr[i] > arr[secondLargest]) secondLargest = i; } } return secondLargest;} int main() { int arr[] = {10, 12, 20, 4}; int n = sizeof(arr)/sizeof(arr[0]); int second_Largest = secondLargest(arr, n); if (second_Largest == -1) cout << \"Second largest didn't exit\\n\"; else cout << \"Second largest : \" << arr[second_Largest];}", "e": 48282, "s": 47211, "text": null }, { "code": "// Java program to find second largest// element in an arrayclass GFG{ // Function to print the second largest elementsstatic void print2largest(int arr[], int arr_size){ int i, first, second; // There should be atleast two elements if (arr_size < 2) { System.out.printf(\" Invalid Input \"); return; } int largest = second = Integer.MIN_VALUE; // Find the largest element for(i = 0; i < arr_size; i++) { largest = Math.max(largest, arr[i]); } // Find the second largest element for(i = 0; i < arr_size; i++) { if (arr[i] != largest) second = Math.max(second, arr[i]); } if (second == Integer.MIN_VALUE) System.out.printf(\"There is no second \" + \"largest element\\n\"); else System.out.printf(\"The second largest \" + \"element is %d\\n\", second);} // Driver codepublic static void main(String[] args){ int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = arr.length; print2largest(arr, n);}} // This code is contributed by Amit Katiyar", "e": 49374, "s": 48282, "text": null }, { "code": "# Python3 program to find# second largest element# in an array # Function to print# second largest elementsdef print2largest(arr, arr_size): # There should be atleast # two elements if (arr_size < 2): print(\" Invalid Input \"); return; largest = second = -2454635434; # Find the largest element for i in range(0, arr_size): largest = max(largest, arr[i]); # Find the second largest element for i in range(0, arr_size): if (arr[i] != largest): second = max(second, arr[i]); if (second == -2454635434): print(\"There is no second \" + \"largest element\"); else: print(\"The second largest \" + \"element is \\n\", second); # Driver codeif __name__ == '__main__': arr = [12, 35, 1, 10, 34, 1]; n = len(arr); print2largest(arr, n); # This code is contributed by shikhasingrajput", "e": 50276, "s": 49374, "text": null }, { "code": "// C# program to find second largest// element in an arrayusing System; class GFG{ // Function to print the second largest elementsstatic void print2largest(int []arr, int arr_size){ // int first; int i, second; // There should be atleast two elements if (arr_size < 2) { Console.Write(\" Invalid Input \"); return; } int largest = second = int.MinValue; // Find the largest element for(i = 0; i < arr_size; i++) { largest = Math.Max(largest, arr[i]); } // Find the second largest element for(i = 0; i < arr_size; i++) { if (arr[i] != largest) second = Math.Max(second, arr[i]); } if (second == int.MinValue) Console.Write(\"There is no second \" + \"largest element\\n\"); else Console.Write(\"The second largest \" + \"element is {0}\\n\", second);} // Driver codepublic static void Main(String[] args){ int []arr = { 12, 35, 1, 10, 34, 1 }; int n = arr.Length; print2largest(arr, n);}} // This code is contributed by Amit Katiyar", "e": 51366, "s": 50276, "text": null }, { "code": "<script> // Javascript program to find second largest// element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i; let largest = second = -2454635434; // There should be atleast two elements if (arr_size < 2) { document.write(\" Invalid Input \"); return; } // finding the largest element for (i = 0;i<arr_size;i++){ if (arr[i]>largest){ largest = arr[i]; } } // Now find the second largest element for (i = 0 ;i<arr_size;i++){ if (arr[i]>second && arr[i]<largest){ second = arr[i]; } } if (second == -2454635434){ document.write(\"There is no second largest element<br>\"); } else{ document.write(\"The second largest element is \" + second); return; } } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); </script>", "e": 52505, "s": 51366, "text": null }, { "code": null, "e": 52525, "s": 52505, "text": "Second largest : 12" }, { "code": null, "e": 52546, "s": 52525, "text": "Complexity Analysis:" }, { "code": null, "e": 52608, "s": 52546, "text": "Time Complexity: O(n). Two traversals of the array is needed." }, { "code": null, "e": 52662, "s": 52608, "text": "Auxiliary space: O(1). As no extra space is required." }, { "code": null, "e": 52796, "s": 52662, "text": "Efficient Solution Approach: Find the second largest element in a single traversal. Below is the complete algorithm for doing this: " }, { "code": null, "e": 53240, "s": 52796, "text": "1) Initialize the first as 0(i.e, index of arr[0] element\n2) Start traversing the array from array[1],\n a) If the current element in array say arr[i] is greater\n than first. Then update first and second as,\n second = first\n first = arr[i]\n b) If the current element is in between first and second,\n then update second to store the value of current variable as\n second = arr[i]\n3) Return the value stored in second." }, { "code": null, "e": 53242, "s": 53240, "text": "C" }, { "code": null, "e": 53246, "s": 53242, "text": "C++" }, { "code": null, "e": 53251, "s": 53246, "text": "Java" }, { "code": null, "e": 53259, "s": 53251, "text": "Python3" }, { "code": null, "e": 53262, "s": 53259, "text": "C#" }, { "code": null, "e": 53266, "s": 53262, "text": "PHP" }, { "code": null, "e": 53277, "s": 53266, "text": "Javascript" }, { "code": "// C program to find second largest// element in an array #include <limits.h>#include <stdio.h> /* Function to print the second largest elements */void print2largest(int arr[], int arr_size){ int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { printf(\" Invalid Input \"); return; } first = second = INT_MIN; for (i = 0; i < arr_size; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == INT_MIN) printf(\"There is no second largest element\\n\"); else printf(\"The second largest element is %d\", second);} /* Driver program to test above function */int main(){ int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = sizeof(arr) / sizeof(arr[0]); print2largest(arr, n); return 0;}", "e": 54370, "s": 53277, "text": null }, { "code": "// C++ program to find the second largest element #include <iostream>using namespace std; // returns the index of second largest// if second largest didn't exist return -1int secondLargest(int arr[], int n) { int first = 0, second = -1; for (int i = 1; i < n; i++) { if (arr[i] > arr[first]) { second = first; first = i; } else if (arr[i] < arr[first]) { if (second == -1 || arr[second] < arr[i]) second = i; } } return second;} int main() { int arr[] = {10, 12, 20, 4}; int index = secondLargest(arr, sizeof(arr)/sizeof(arr[0])); if (index == -1) cout << \"Second Largest didn't exist\"; else cout << \"Second largest : \" << arr[index];}", "e": 55120, "s": 54370, "text": null }, { "code": "// JAVA Code for Find Second largest// element in an arrayclass GFG { /* Function to print the second largest elements */ public static void print2largest(int arr[], int arr_size) { int i, first, second; /* There should be atleast two elements */ if (arr_size < 2) { System.out.print(\" Invalid Input \"); return; } first = second = Integer.MIN_VALUE; for (i = 0; i < arr_size; i++) { /* If current element is greater than first then update both first and second */ if (arr[i] > first) { second = first; first = arr[i]; } /* If arr[i] is in between first and second then update second */ else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == Integer.MIN_VALUE) System.out.print(\"There is no second largest\" + \" element\\n\"); else System.out.print(\"The second largest element\" + \" is \" + second); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = { 12, 35, 1, 10, 34, 1 }; int n = arr.length; print2largest(arr, n); }}// This code is contributed by Arnav Kr. Mandal.", "e": 56535, "s": 55120, "text": null }, { "code": "# Python program to# find second largest# element in an array # Function to print the# second largest elementsdef print2largest(arr, arr_size): # There should be atleast # two elements if (arr_size < 2): print(\" Invalid Input \") return first = second = -2147483648 for i in range(arr_size): # If current element is # smaller than first # then update both # first and second if (arr[i] > first): second = first first = arr[i] # If arr[i] is in # between first and # second then update second elif (arr[i] > second and arr[i] != first): second = arr[i] if (second == -2147483648): print(\"There is no second largest element\") else: print(\"The second largest element is\", second) # Driver program to test# above functionarr = [12, 35, 1, 10, 34, 1]n = len(arr) print2largest(arr, n) # This code is contributed# by Anant Agarwal.", "e": 57576, "s": 56535, "text": null }, { "code": "// C# Code for Find Second largest// element in an arrayusing System; class GFG { // Function to print the // second largest elements public static void print2largest(int[] arr, int arr_size) { int i, first, second; // There should be atleast two elements if (arr_size < 2) { Console.WriteLine(\" Invalid Input \"); return; } first = second = int.MinValue; for (i = 0; i < arr_size; i++) { // If current element is smaller than // first then update both first and second if (arr[i] > first) { second = first; first = arr[i]; } // If arr[i] is in between first // and second then update second else if (arr[i] > second && arr[i] != first) second = arr[i]; } if (second == int.MinValue) Console.Write(\"There is no second largest\" + \" element\\n\"); else Console.Write(\"The second largest element\" + \" is \" + second); } // Driver Code public static void Main(String[] args) { int[] arr = { 12, 35, 1, 10, 34, 1 }; int n = arr.Length; print2largest(arr, n); }} // This code is contributed by Parashar.", "e": 58939, "s": 57576, "text": null }, { "code": "<?php// PHP program to find second largest// element in an array // Function to print the// second largest elementsfunction print2largest($arr, $arr_size){ // There should be atleast // two elements if ($arr_size < 2) { echo(\" Invalid Input \"); return; } $first = $second = PHP_INT_MIN; for ($i = 0; $i < $arr_size ; $i++) { // If current element is // smaller than first // then update both // first and second if ($arr[$i] > $first) { $second = $first; $first = $arr[$i]; } // If arr[i] is in // between first and // second then update // second else if ($arr[$i] > $second && $arr[$i] != $first) $second = $arr[$i]; } if ($second == PHP_INT_MIN) echo(\"There is no second largest element\\n\"); else echo(\"The second largest element is \" . $second . \"\\n\");} // Driver Code$arr = array(12, 35, 1, 10, 34, 1);$n = sizeof($arr);print2largest($arr, $n); // This code is contributed by Ajit.?>", "e": 60034, "s": 58939, "text": null }, { "code": "<script> // Javascript program to find second largest// element in an array // Function to print the second largest elements function print2largest(arr, arr_size) { let i; let largest = second = -2454635434; // There should be atleast two elements if (arr_size < 2) { document.write(\" Invalid Input \"); return; } // finding the largest element for (i = 0 ;i<arr_size;i++){ if (arr[i]>largest){ second = largest ; largest = arr[i] } else if (arr[i]!=largest && arr[i]>second ){ second = arr[i]; } } if (second == -2454635434){ document.write(\"There is no second largest element<br>\"); } else{ document.write(\"The second largest element is \" + second); return; } } // Driver program to test above function let arr= [ 12, 35, 1, 10, 34, 1 ]; let n = arr.length; print2largest(arr, n); // This code is contributed by Shaswat Singh </script>", "e": 61177, "s": 60034, "text": null }, { "code": null, "e": 61185, "s": 61177, "text": "Output:" }, { "code": null, "e": 61205, "s": 61185, "text": "Second largest : 34" }, { "code": null, "e": 61226, "s": 61205, "text": "Complexity Analysis:" }, { "code": null, "e": 61292, "s": 61226, "text": "Time Complexity: O(n). Only one traversal of the array is needed." }, { "code": null, "e": 61346, "s": 61292, "text": "Auxiliary space: O(1). As no extra space is required." }, { "code": null, "e": 61833, "s": 61346, "text": "Related Article: Smallest and second smallest element in an arrayThis article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 61851, "s": 61833, "text": "Shubham Bansal 13" }, { "code": null, "e": 61860, "s": 61851, "text": "parashar" }, { "code": null, "e": 61866, "s": 61860, "text": "jit_t" }, { "code": null, "e": 61879, "s": 61866, "text": "HiteshParrru" }, { "code": null, "e": 61890, "s": 61879, "text": "andrew1234" }, { "code": null, "e": 61909, "s": 61890, "text": "shivanisinghss2110" }, { "code": null, "e": 61924, "s": 61909, "text": "amit143katiyar" }, { "code": null, "e": 61938, "s": 61924, "text": "GauravRajput1" }, { "code": null, "e": 61955, "s": 61938, "text": "shikhasingrajput" }, { "code": null, "e": 61973, "s": 61955, "text": "divyeshrabadiya07" }, { "code": null, "e": 61987, "s": 61973, "text": "surbhityagi15" }, { "code": null, "e": 62001, "s": 61987, "text": "shaswatsingh1" }, { "code": null, "e": 62015, "s": 62001, "text": "itsvishal2417" }, { "code": null, "e": 62036, "s": 62015, "text": "healer26mastercoding" }, { "code": null, "e": 62046, "s": 62036, "text": "mayank021" }, { "code": null, "e": 62055, "s": 62046, "text": "Accolite" }, { "code": null, "e": 62063, "s": 62055, "text": "FactSet" }, { "code": null, "e": 62068, "s": 62063, "text": "Hike" }, { "code": null, "e": 62085, "s": 62068, "text": "Order-Statistics" }, { "code": null, "e": 62094, "s": 62085, "text": "SAP Labs" }, { "code": null, "e": 62099, "s": 62094, "text": "Zoho" }, { "code": null, "e": 62106, "s": 62099, "text": "Arrays" }, { "code": null, "e": 62111, "s": 62106, "text": "Zoho" }, { "code": null, "e": 62120, "s": 62111, "text": "Accolite" }, { "code": null, "e": 62128, "s": 62120, "text": "FactSet" }, { "code": null, "e": 62133, "s": 62128, "text": "Hike" }, { "code": null, "e": 62142, "s": 62133, "text": "SAP Labs" }, { "code": null, "e": 62149, "s": 62142, "text": "Arrays" }, { "code": null, "e": 62247, "s": 62149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 62256, "s": 62247, "text": "Comments" }, { "code": null, "e": 62269, "s": 62256, "text": "Old Comments" }, { "code": null, "e": 62284, "s": 62269, "text": "Arrays in Java" }, { "code": null, "e": 62300, "s": 62284, "text": "Arrays in C/C++" }, { "code": null, "e": 62327, "s": 62300, "text": "Program for array rotation" }, { "code": null, "e": 62375, "s": 62327, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 62419, "s": 62375, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 62451, "s": 62419, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 62497, "s": 62451, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 62529, "s": 62497, "text": "Multidimensional Arrays in Java" } ]
Difference between Cellpadding and Cellspacing
31 Jul, 2020 Cellpadding:Cellpadding specifies the space between the border of a table cell and its contents (i.e) it defines the whitespace between the cell edge and the content of the cell.Syntax:<table cellpadding="value" >.....</table> where, value determines the padding (space between the border of a table and its content) Cellpadding: Cellpadding specifies the space between the border of a table cell and its contents (i.e) it defines the whitespace between the cell edge and the content of the cell. Syntax: <table cellpadding="value" >.....</table> where, value determines the padding (space between the border of a table and its content) Cellspacing:Cellspacing specifies the space between cells (i.e) it defines the whitespace between the edges of the adjacent cells.Syntax:<table cellspacing="value" >.....</table> where, value determines the padding (space between adjacent cells) Cellspacing: Cellspacing specifies the space between cells (i.e) it defines the whitespace between the edges of the adjacent cells. Syntax: <table cellspacing="value" >.....</table> where, value determines the padding (space between adjacent cells) Example: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> span{ text-decoration-style: solid; width: 25px; font-size: x-large; color: blueviolet; } </style></head><body><table border="1" cellpadding="4" cellspacing="5"> <thead> <td><span>Name</span></td> <td><span>Age</span></td> </thead> <tbody> <tr> <td>Rani</td> <td>30</td> </tr> <tr> <td>Rajan</td> <td>35</td> </tr> <tr> <td>Akshaya</td> <td>17</td> </tr> <tr> <td>Ashick</td> <td>13</td> </tr> </tbody></table></body></html> Output: Difference between cellpadding and cellspacing: Cellpadding Cellspacing HTML-Basics HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Jul, 2020" }, { "code": null, "e": 371, "s": 53, "text": "Cellpadding:Cellpadding specifies the space between the border of a table cell and its contents (i.e) it defines the whitespace between the cell edge and the content of the cell.Syntax:<table cellpadding=\"value\" >.....</table>\nwhere, value determines the padding \n(space between the border of a table and its content)" }, { "code": null, "e": 384, "s": 371, "text": "Cellpadding:" }, { "code": null, "e": 551, "s": 384, "text": "Cellpadding specifies the space between the border of a table cell and its contents (i.e) it defines the whitespace between the cell edge and the content of the cell." }, { "code": null, "e": 559, "s": 551, "text": "Syntax:" }, { "code": null, "e": 692, "s": 559, "text": "<table cellpadding=\"value\" >.....</table>\nwhere, value determines the padding \n(space between the border of a table and its content)" }, { "code": null, "e": 939, "s": 692, "text": "Cellspacing:Cellspacing specifies the space between cells (i.e) it defines the whitespace between the edges of the adjacent cells.Syntax:<table cellspacing=\"value\" >.....</table>\nwhere, value determines the padding \n(space between adjacent cells)" }, { "code": null, "e": 952, "s": 939, "text": "Cellspacing:" }, { "code": null, "e": 1071, "s": 952, "text": "Cellspacing specifies the space between cells (i.e) it defines the whitespace between the edges of the adjacent cells." }, { "code": null, "e": 1079, "s": 1071, "text": "Syntax:" }, { "code": null, "e": 1189, "s": 1079, "text": "<table cellspacing=\"value\" >.....</table>\nwhere, value determines the padding \n(space between adjacent cells)" }, { "code": null, "e": 1198, "s": 1189, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Document</title> <style> span{ text-decoration-style: solid; width: 25px; font-size: x-large; color: blueviolet; } </style></head><body><table border=\"1\" cellpadding=\"4\" cellspacing=\"5\"> <thead> <td><span>Name</span></td> <td><span>Age</span></td> </thead> <tbody> <tr> <td>Rani</td> <td>30</td> </tr> <tr> <td>Rajan</td> <td>35</td> </tr> <tr> <td>Akshaya</td> <td>17</td> </tr> <tr> <td>Ashick</td> <td>13</td> </tr> </tbody></table></body></html>", "e": 1935, "s": 1198, "text": null }, { "code": null, "e": 1943, "s": 1935, "text": "Output:" }, { "code": null, "e": 1991, "s": 1943, "text": "Difference between cellpadding and cellspacing:" }, { "code": null, "e": 2003, "s": 1991, "text": "Cellpadding" }, { "code": null, "e": 2015, "s": 2003, "text": "Cellspacing" }, { "code": null, "e": 2027, "s": 2015, "text": "HTML-Basics" }, { "code": null, "e": 2032, "s": 2027, "text": "HTML" }, { "code": null, "e": 2049, "s": 2032, "text": "Web Technologies" }, { "code": null, "e": 2054, "s": 2049, "text": "HTML" } ]
How to set the RadioButton to Checked State in C#?
30 Jun, 2019 In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to set a value which represents the RadioButton control is checked using the Checked Property of the RadioButton.If the value of this property is set to true, then RadioButton is checked and if the value of this property is set to false, then RadioButton is not checked. The default value of this property is false. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set a value which represents the RadioButton is checked 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: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RadioButton control to set a value which represents the RadioButton control is checked.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set a value which represents the RadioButton control is checked programmatically with the help of given syntax: public bool Checked { get; set; } The value of this property is of System.Boolean type. The following steps show how to set the Checked property of the RadioButton dynamically: Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button RadioButton r1 = new RadioButton(); // Creating radio button RadioButton r1 = new RadioButton(); Step 2: After creating RadioButton, set the Checked property of the RadioButton provided by the RadioButton class.// Setting the Checked property of the radio button r1.Checked = true; // Setting the Checked property of the radio button r1.Checked = true; Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form this.Controls.Add(r1); 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 WindowsFormsApp24 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Post"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "Intern"; r1.Location = new Point(286, 40); r1.Checked = true; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "Team Leader"; r2.Location = new Point(356, 40); r2.Checked = false; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = "Software Engineer"; r3.Location = new Point(470, 40); r3.Checked = true; // Adding this label to the form this.Controls.Add(r3); }}}Output:Before setting the Checked property:After setting the Checked property: // Add this radio button to the form this.Controls.Add(r1); 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 WindowsFormsApp24 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Post"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = "Intern"; r1.Location = new Point(286, 40); r1.Checked = true; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = "Team Leader"; r2.Location = new Point(356, 40); r2.Checked = false; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = "Software Engineer"; r3.Location = new Point(470, 40); r3.Checked = true; // Adding this label to the form this.Controls.Add(r3); }}} Output: Before setting the Checked property: After setting the Checked property: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2019" }, { "code": null, "e": 675, "s": 28, "text": "In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender. In Windows Forms, you are allowed to set a value which represents the RadioButton control is checked using the Checked Property of the RadioButton.If the value of this property is set to true, then RadioButton is checked and if the value of this property is set to false, then RadioButton is not checked. The default value of this property is false. You can set this property in two different ways:" }, { "code": null, "e": 805, "s": 675, "text": "1. Design-Time: It is the easiest way to set a value which represents the RadioButton is checked as shown in the following steps:" }, { "code": null, "e": 921, "s": 805, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 1108, "s": 921, "text": "Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need." }, { "code": null, "e": 1268, "s": 1108, "text": "Step 3: After drag and drop you will go to the properties of the RadioButton control to set a value which represents the RadioButton control is checked.Output:" }, { "code": null, "e": 1276, "s": 1268, "text": "Output:" }, { "code": null, "e": 1476, "s": 1276, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set a value which represents the RadioButton control is checked programmatically with the help of given syntax:" }, { "code": null, "e": 1510, "s": 1476, "text": "public bool Checked { get; set; }" }, { "code": null, "e": 1653, "s": 1510, "text": "The value of this property is of System.Boolean type. The following steps show how to set the Checked property of the RadioButton dynamically:" }, { "code": null, "e": 1818, "s": 1653, "text": "Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 1880, "s": 1818, "text": "// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 2066, "s": 1880, "text": "Step 2: After creating RadioButton, set the Checked property of the RadioButton provided by the RadioButton class.// Setting the Checked property of the radio button\nr1.Checked = true;\n" }, { "code": null, "e": 2138, "s": 2066, "text": "// Setting the Checked property of the radio button\nr1.Checked = true;\n" }, { "code": null, "e": 4088, "s": 2138, "text": "Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form\nthis.Controls.Add(r1);\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 WindowsFormsApp24 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Post\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"Intern\"; r1.Location = new Point(286, 40); r1.Checked = true; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"Team Leader\"; r2.Location = new Point(356, 40); r2.Checked = false; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = \"Software Engineer\"; r3.Location = new Point(470, 40); r3.Checked = true; // Adding this label to the form this.Controls.Add(r3); }}}Output:Before setting the Checked property:After setting the Checked property:" }, { "code": null, "e": 4149, "s": 4088, "text": "// Add this radio button to the form\nthis.Controls.Add(r1);\n" }, { "code": null, "e": 4158, "s": 4149, "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 WindowsFormsApp24 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void RadioButton2_CheckedChanged(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Post\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.AutoSize = true; r1.Text = \"Intern\"; r1.Location = new Point(286, 40); r1.Checked = true; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.AutoSize = true; r2.Text = \"Team Leader\"; r2.Location = new Point(356, 40); r2.Checked = false; // Adding this label to the form this.Controls.Add(r2); // Creating and setting the // properties of the RadioButton RadioButton r3 = new RadioButton(); r3.AutoSize = true; r3.Text = \"Software Engineer\"; r3.Location = new Point(470, 40); r3.Checked = true; // Adding this label to the form this.Controls.Add(r3); }}}", "e": 5885, "s": 4158, "text": null }, { "code": null, "e": 5893, "s": 5885, "text": "Output:" }, { "code": null, "e": 5930, "s": 5893, "text": "Before setting the Checked property:" }, { "code": null, "e": 5966, "s": 5930, "text": "After setting the Checked property:" }, { "code": null, "e": 5969, "s": 5966, "text": "C#" } ]
Design a Learning System in Machine Learning
05 Apr, 2022 According to Arthur Samuel “Machine Learning enables a Machine to Automatically learn from Data, Improve performance from an Experience and predict things without explicitly programmed.” In Simple Words, When we fed the Training Data to Machine Learning Algorithm, this algorithm will produce a mathematical model and with the help of the mathematical model, the machine will make a prediction and take a decision without being explicitly programmed. Also, during training data, the more machine will work with it the more it will get experience and the more efficient result is produced. Example : In Driverless Car, the training data is fed to Algorithm like how to Drive Car in Highway, Busy and Narrow Street with factors like speed limit, parking, stop at signal etc. After that, a Logical and Mathematical model is created on the basis of that and after that, the car will work according to the logical model. Also, the more data the data is fed the more efficient output is produced. Designing a Learning System in Machine Learning : According to Tom Mitchell, “A computer program is said to be learning from experience (E), with respect to some task (T). Thus, the performance measure (P) is the performance at task T, which is measured by P, and it improves with experience E.” Example: In Spam E-Mail detection, Task, T: To classify mails into Spam or Not Spam. Performance measure, P: Total percent of mails being correctly classified as being “Spam” or “Not Spam”. Experience, E: Set of Mails with label “Spam” Steps for Designing Learning System are: Step 1) Choosing the Training Experience: The very important and first task is to choose the training data or training experience which will be fed to the Machine Learning Algorithm. It is important to note that the data or experience that we fed to the algorithm must have a significant impact on the Success or Failure of the Model. So Training data or experience should be chosen wisely. Below are the attributes which will impact on Success and Failure of Data: The training experience will be able to provide direct or indirect feedback regarding choices. For example: While Playing chess the training data will provide feedback to itself like instead of this move if this is chosen the chances of success increases. Second important attribute is the degree to which the learner will control the sequences of training examples. For example: when training data is fed to the machine then at that time accuracy is very less but when it gains experience while playing again and again with itself or opponent the machine algorithm will get feedback and control the chess game accordingly. Third important attribute is how it will represent the distribution of examples over which performance will be measured. For example, a Machine learning algorithm will get experience while going through a number of different cases and different examples. Thus, Machine Learning Algorithm will get more and more experience by passing through more and more examples and hence its performance will increase. Step 2- Choosing target function: The next important step is choosing the target function. It means according to the knowledge fed to the algorithm the machine learning will choose NextMove function which will describe what type of legal moves should be taken. For example : While playing chess with the opponent, when opponent will play then the machine learning algorithm will decide what be the number of possible legal moves taken in order to get success. Step 3- Choosing Representation for Target function: When the machine algorithm will know all the possible legal moves the next step is to choose the optimized move using any representation i.e. using linear Equations, Hierarchical Graph Representation, Tabular form etc. The NextMove function will move the Target move like out of these move which will provide more success rate. For Example : while playing chess machine have 4 possible moves, so the machine will choose that optimized move which will provide success to it. Step 4- Choosing Function Approximation Algorithm: An optimized move cannot be chosen just with the training data. The training data had to go through with set of example and through these examples the training data will approximates which steps are chosen and after that machine will provide feedback on it. For Example : When a training data of Playing chess is fed to algorithm so at that time it is not machine algorithm will fail or get success and again from that failure or success it will measure while next move what step should be chosen and what is its success rate. Step 5- Final Design: The final design is created at last when system goes from number of examples , failures and success , correct and incorrect decision and what will be the next step etc. Example: DeepBlue is an intelligent computer which is ML-based won chess game against the chess expert Garry Kasparov, and it became the first computer which had beaten a human chess expert. arshbhatia Technical Scripter 2020 Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Apr, 2022" }, { "code": null, "e": 241, "s": 54, "text": "According to Arthur Samuel “Machine Learning enables a Machine to Automatically learn from Data, Improve performance from an Experience and predict things without explicitly programmed.”" }, { "code": null, "e": 644, "s": 241, "text": "In Simple Words, When we fed the Training Data to Machine Learning Algorithm, this algorithm will produce a mathematical model and with the help of the mathematical model, the machine will make a prediction and take a decision without being explicitly programmed. Also, during training data, the more machine will work with it the more it will get experience and the more efficient result is produced. " }, { "code": null, "e": 1047, "s": 644, "text": "Example : In Driverless Car, the training data is fed to Algorithm like how to Drive Car in Highway, Busy and Narrow Street with factors like speed limit, parking, stop at signal etc. After that, a Logical and Mathematical model is created on the basis of that and after that, the car will work according to the logical model. Also, the more data the data is fed the more efficient output is produced." }, { "code": null, "e": 1097, "s": 1047, "text": "Designing a Learning System in Machine Learning :" }, { "code": null, "e": 1343, "s": 1097, "text": "According to Tom Mitchell, “A computer program is said to be learning from experience (E), with respect to some task (T). Thus, the performance measure (P) is the performance at task T, which is measured by P, and it improves with experience E.”" }, { "code": null, "e": 1378, "s": 1343, "text": "Example: In Spam E-Mail detection," }, { "code": null, "e": 1428, "s": 1378, "text": "Task, T: To classify mails into Spam or Not Spam." }, { "code": null, "e": 1533, "s": 1428, "text": "Performance measure, P: Total percent of mails being correctly classified as being “Spam” or “Not Spam”." }, { "code": null, "e": 1579, "s": 1533, "text": "Experience, E: Set of Mails with label “Spam”" }, { "code": null, "e": 1620, "s": 1579, "text": "Steps for Designing Learning System are:" }, { "code": null, "e": 2011, "s": 1620, "text": "Step 1) Choosing the Training Experience: The very important and first task is to choose the training data or training experience which will be fed to the Machine Learning Algorithm. It is important to note that the data or experience that we fed to the algorithm must have a significant impact on the Success or Failure of the Model. So Training data or experience should be chosen wisely." }, { "code": null, "e": 2086, "s": 2011, "text": "Below are the attributes which will impact on Success and Failure of Data:" }, { "code": null, "e": 2342, "s": 2086, "text": "The training experience will be able to provide direct or indirect feedback regarding choices. For example: While Playing chess the training data will provide feedback to itself like instead of this move if this is chosen the chances of success increases." }, { "code": null, "e": 2710, "s": 2342, "text": "Second important attribute is the degree to which the learner will control the sequences of training examples. For example: when training data is fed to the machine then at that time accuracy is very less but when it gains experience while playing again and again with itself or opponent the machine algorithm will get feedback and control the chess game accordingly." }, { "code": null, "e": 3115, "s": 2710, "text": "Third important attribute is how it will represent the distribution of examples over which performance will be measured. For example, a Machine learning algorithm will get experience while going through a number of different cases and different examples. Thus, Machine Learning Algorithm will get more and more experience by passing through more and more examples and hence its performance will increase." }, { "code": null, "e": 3576, "s": 3115, "text": "Step 2- Choosing target function: The next important step is choosing the target function. It means according to the knowledge fed to the algorithm the machine learning will choose NextMove function which will describe what type of legal moves should be taken. For example : While playing chess with the opponent, when opponent will play then the machine learning algorithm will decide what be the number of possible legal moves taken in order to get success." }, { "code": null, "e": 4103, "s": 3576, "text": "Step 3- Choosing Representation for Target function: When the machine algorithm will know all the possible legal moves the next step is to choose the optimized move using any representation i.e. using linear Equations, Hierarchical Graph Representation, Tabular form etc. The NextMove function will move the Target move like out of these move which will provide more success rate. For Example : while playing chess machine have 4 possible moves, so the machine will choose that optimized move which will provide success to it." }, { "code": null, "e": 4682, "s": 4103, "text": "Step 4- Choosing Function Approximation Algorithm: An optimized move cannot be chosen just with the training data. The training data had to go through with set of example and through these examples the training data will approximates which steps are chosen and after that machine will provide feedback on it. For Example : When a training data of Playing chess is fed to algorithm so at that time it is not machine algorithm will fail or get success and again from that failure or success it will measure while next move what step should be chosen and what is its success rate." }, { "code": null, "e": 5066, "s": 4682, "text": "Step 5- Final Design: The final design is created at last when system goes from number of examples , failures and success , correct and incorrect decision and what will be the next step etc. Example: DeepBlue is an intelligent computer which is ML-based won chess game against the chess expert Garry Kasparov, and it became the first computer which had beaten a human chess expert." }, { "code": null, "e": 5077, "s": 5066, "text": "arshbhatia" }, { "code": null, "e": 5101, "s": 5077, "text": "Technical Scripter 2020" }, { "code": null, "e": 5120, "s": 5101, "text": "Technical Scripter" } ]
KPMG Digital Enablement Oracle Interview Experience
09 Aug, 2021 KPMG came to our campus on 28th July 2021 looking for students for three profiles. Digital Enablement Oracle, Digital Enablement Microsoft, and Digital Trust. This article is about Digital Enablement Oracle. The other two profiles were non-coding. Round 1(Online Test): 60 mins MCQ test with questions on aptitude and some basic networking questions as well as data structures questions. A 15 mins psychometric test after this. And lastly a coding round of 30 mins. In the coding round we were not asked to run the code but to only write the code in a plain text editor. There were 5 coding questions of basic level. First two questions were pattern printing. The third question was a removing duplicates from array. The fourth question was related to arrays, it was something basic. anyone with a minimum practice from GeeksforGeeks could easily solve all of these. I don’t remember the fifth question. After this round the results were declared on 5th August. Out of almost about 430 students, 50 were shortlisted for Digital Enablement Oracle profile. Round 2(Group Discussion): The next round was a group discussion round. We were given a topic and we were asked to discuss it. Our topic was “Impact of Covid 19 on global economy”. Good communication skills was taken note of. Results were declared the same day. About 25 students qualified. The next technical interview was scheduled the same day. Round 3(Technical Interview): This was a technical interview, and I was interviewed by a software engineer of the company. She introduced herself and asked me to “tell her about myself”. After the brief introduction she started coding questions. We had to write our code in the hirepro platform. First question was a basic pattern question. Very Basic. We had to print the pattern- * * * * * * * * *here the maximum number is entered by the user. * * * * * * * * * here the maximum number is entered by the user. Second question was about printing the largest palindromic substring from a user-entered string. I gave an O(n^3) solution and later I was asked to optimize the code to O(n^2). She was satisfied with the solution and asked me to explain the code and run it on some test cases. It Passed all test cases. The Third question was about sorting techniques, why heapsort is used, how is it better than mergesort and asked me to write the code for any one of them. I wrote the code for heapsort. After this, she started asking me OOPS concept. Inheritance, Encapsulation, method overloading, and method overriding. And kept giving examples about where all this would fail, and I was asked whether she told correctly. Some questions were, can the static method be inherited, can a java function have two main methods etc. After this, she looked into my resume and as I had mentioned DBMS and SQL in it, she started asking me questions about joins, acid properties, and then I was given a problem and told to write an SQL query. The problem was something like this- Write a query to find the names of all students who are studying in a department along with department id. The name of students who are not currently in a department should also be displayed. I solved this using left outer join and she was satisfied. After this she said, okay I am done with questions, do you have any questions for me?. I asked her a question about what initial training I would go under and she answered me and the interview ended. Round 4: The results of the previous round were declared the same night and this interview was scheduled the next day. This Interview was taken by the technical director. He gave me a brief introduction and asked me to introduce myself. After this, he directly started asking me about my projects that I mentioned in my resume. There was a long 20 mins discussion about a project where i had used database. He told me to describe my project, methods used. He then gave me cases where my project would fail and asked me to come up with a solution for those cases. He was checking my concepts. After this, he asked me to rate myself on a language of my choice. I selected Java and rated myself 8/10. He asked me what language i used first when i started coding. I told C. He asked me why I switched to JAVA. After this it became more of a casual conversation. He told me about the role, what would i be working on etc. At last he asked me whether I had any questions for him. I asked two relevant questions and then he said, “We Will See You Soon” and left the meeting giving me hope. And on 7th August, I got a message from Training and Placement Department that I had been selected for the profile of Digital Enablement Oracle. I was really happy and I suggest everyone should read interview experiences from GeeksforGeeks as it really gives you an idea about the questions you can face in an interview. KPMG Marketing Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n09 Aug, 2021" }, { "code": null, "e": 277, "s": 28, "text": "KPMG came to our campus on 28th July 2021 looking for students for three profiles. Digital Enablement Oracle, Digital Enablement Microsoft, and Digital Trust. This article is about Digital Enablement Oracle. The other two profiles were non-coding. " }, { "code": null, "e": 496, "s": 277, "text": "Round 1(Online Test): 60 mins MCQ test with questions on aptitude and some basic networking questions as well as data structures questions. A 15 mins psychometric test after this. And lastly a coding round of 30 mins. " }, { "code": null, "e": 648, "s": 496, "text": "In the coding round we were not asked to run the code but to only write the code in a plain text editor. There were 5 coding questions of basic level. " }, { "code": null, "e": 935, "s": 648, "text": "First two questions were pattern printing. The third question was a removing duplicates from array. The fourth question was related to arrays, it was something basic. anyone with a minimum practice from GeeksforGeeks could easily solve all of these. I don’t remember the fifth question." }, { "code": null, "e": 1086, "s": 935, "text": "After this round the results were declared on 5th August. Out of almost about 430 students, 50 were shortlisted for Digital Enablement Oracle profile." }, { "code": null, "e": 1113, "s": 1086, "text": "Round 2(Group Discussion):" }, { "code": null, "e": 1312, "s": 1113, "text": "The next round was a group discussion round. We were given a topic and we were asked to discuss it. Our topic was “Impact of Covid 19 on global economy”. Good communication skills was taken note of." }, { "code": null, "e": 1378, "s": 1312, "text": "Results were declared the same day. About 25 students qualified. " }, { "code": null, "e": 1435, "s": 1378, "text": "The next technical interview was scheduled the same day." }, { "code": null, "e": 1732, "s": 1435, "text": "Round 3(Technical Interview): This was a technical interview, and I was interviewed by a software engineer of the company. She introduced herself and asked me to “tell her about myself”. After the brief introduction she started coding questions. We had to write our code in the hirepro platform. " }, { "code": null, "e": 1943, "s": 1732, "text": "First question was a basic pattern question. Very Basic. We had to print the pattern- *\n * *\n * * *\n * *\n *here the maximum number is entered by the user." }, { "code": null, "e": 2022, "s": 1943, "text": " *\n * *\n * * *\n * *\n *" }, { "code": null, "e": 2070, "s": 2022, "text": "here the maximum number is entered by the user." }, { "code": null, "e": 2373, "s": 2070, "text": "Second question was about printing the largest palindromic substring from a user-entered string. I gave an O(n^3) solution and later I was asked to optimize the code to O(n^2). She was satisfied with the solution and asked me to explain the code and run it on some test cases. It Passed all test cases." }, { "code": null, "e": 2559, "s": 2373, "text": "The Third question was about sorting techniques, why heapsort is used, how is it better than mergesort and asked me to write the code for any one of them. I wrote the code for heapsort." }, { "code": null, "e": 2884, "s": 2559, "text": "After this, she started asking me OOPS concept. Inheritance, Encapsulation, method overloading, and method overriding. And kept giving examples about where all this would fail, and I was asked whether she told correctly. Some questions were, can the static method be inherited, can a java function have two main methods etc." }, { "code": null, "e": 3378, "s": 2884, "text": "After this, she looked into my resume and as I had mentioned DBMS and SQL in it, she started asking me questions about joins, acid properties, and then I was given a problem and told to write an SQL query. The problem was something like this- Write a query to find the names of all students who are studying in a department along with department id. The name of students who are not currently in a department should also be displayed. I solved this using left outer join and she was satisfied." }, { "code": null, "e": 3578, "s": 3378, "text": "After this she said, okay I am done with questions, do you have any questions for me?. I asked her a question about what initial training I would go under and she answered me and the interview ended." }, { "code": null, "e": 3697, "s": 3578, "text": "Round 4: The results of the previous round were declared the same night and this interview was scheduled the next day." }, { "code": null, "e": 4170, "s": 3697, "text": "This Interview was taken by the technical director. He gave me a brief introduction and asked me to introduce myself. After this, he directly started asking me about my projects that I mentioned in my resume. There was a long 20 mins discussion about a project where i had used database. He told me to describe my project, methods used. He then gave me cases where my project would fail and asked me to come up with a solution for those cases. He was checking my concepts." }, { "code": null, "e": 4385, "s": 4170, "text": "After this, he asked me to rate myself on a language of my choice. I selected Java and rated myself 8/10. He asked me what language i used first when i started coding. I told C. He asked me why I switched to JAVA. " }, { "code": null, "e": 4496, "s": 4385, "text": "After this it became more of a casual conversation. He told me about the role, what would i be working on etc." }, { "code": null, "e": 4662, "s": 4496, "text": "At last he asked me whether I had any questions for him. I asked two relevant questions and then he said, “We Will See You Soon” and left the meeting giving me hope." }, { "code": null, "e": 4807, "s": 4662, "text": "And on 7th August, I got a message from Training and Placement Department that I had been selected for the profile of Digital Enablement Oracle." }, { "code": null, "e": 4983, "s": 4807, "text": "I was really happy and I suggest everyone should read interview experiences from GeeksforGeeks as it really gives you an idea about the questions you can face in an interview." }, { "code": null, "e": 4988, "s": 4983, "text": "KPMG" }, { "code": null, "e": 4998, "s": 4988, "text": "Marketing" }, { "code": null, "e": 5020, "s": 4998, "text": "Interview Experiences" } ]
How to convert array values to lowercase in PHP ?
24 Jun, 2021 Given an array containing uppercase string elements and the task is to convert the array elements (uppercase) into lowercase. There are two ways to convert array values to lowercase in PHP. Using foreach loop Using array_map() function Using foreach loop: In this approach, an iterator iterates through the value of an array individually and convert each array elements into lowercase and stores the converted values to the original array.Program: PHP <?php // Declare an array$arr = array('GFG', 'GEEK', 'GEEKS', 'GEEKSFORGEEKS'); $j = 0; // Iterate loop to convert array// elements into lowercase and// overwriting the original arrayforeach( $arr as $element ) { $arr[$j] = strtolower($element); $j++;} // Display the content of arrayforeach( $arr as $element ) echo $element . "\n"; ?> gfg geek geeks geeksforgeeks Using array_map() function: In this approach, the array_map() function is used to accept two parameters callback and an array. Syntax: array array_map( callable callback, array array ) Here callback is a function to be called for operation on an array. This function can be an inbuilt function or an user-defined function whereas array is list of values on which operation to be performed.Program 2: PHP <?php // Declare an array$arr = array('GFG', 'GEEK', 'GEEKS', 'GEEKSFORGEEKS'); $arr = array_map( 'strtolower', $arr ); // Display the content of arrayforeach( $arr as $element ) echo $element . "\n"; ?> gfg geek geeks geeksforgeeks AshokJaiswal Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 220, "s": 28, "text": "Given an array containing uppercase string elements and the task is to convert the array elements (uppercase) into lowercase. There are two ways to convert array values to lowercase in PHP. " }, { "code": null, "e": 239, "s": 220, "text": "Using foreach loop" }, { "code": null, "e": 266, "s": 239, "text": "Using array_map() function" }, { "code": null, "e": 480, "s": 266, "text": "Using foreach loop: In this approach, an iterator iterates through the value of an array individually and convert each array elements into lowercase and stores the converted values to the original array.Program: " }, { "code": null, "e": 484, "s": 480, "text": "PHP" }, { "code": "<?php // Declare an array$arr = array('GFG', 'GEEK', 'GEEKS', 'GEEKSFORGEEKS'); $j = 0; // Iterate loop to convert array// elements into lowercase and// overwriting the original arrayforeach( $arr as $element ) { $arr[$j] = strtolower($element); $j++;} // Display the content of arrayforeach( $arr as $element ) echo $element . \"\\n\"; ?>", "e": 842, "s": 484, "text": null }, { "code": null, "e": 871, "s": 842, "text": "gfg\ngeek\ngeeks\ngeeksforgeeks" }, { "code": null, "e": 1010, "s": 873, "text": "Using array_map() function: In this approach, the array_map() function is used to accept two parameters callback and an array. Syntax: " }, { "code": null, "e": 1060, "s": 1010, "text": "array array_map( callable callback, array array )" }, { "code": null, "e": 1277, "s": 1060, "text": "Here callback is a function to be called for operation on an array. This function can be an inbuilt function or an user-defined function whereas array is list of values on which operation to be performed.Program 2: " }, { "code": null, "e": 1281, "s": 1277, "text": "PHP" }, { "code": "<?php // Declare an array$arr = array('GFG', 'GEEK', 'GEEKS', 'GEEKSFORGEEKS'); $arr = array_map( 'strtolower', $arr ); // Display the content of arrayforeach( $arr as $element ) echo $element . \"\\n\"; ?>", "e": 1495, "s": 1281, "text": null }, { "code": null, "e": 1524, "s": 1495, "text": "gfg\ngeek\ngeeks\ngeeksforgeeks" }, { "code": null, "e": 1539, "s": 1526, "text": "AshokJaiswal" }, { "code": null, "e": 1546, "s": 1539, "text": "Picked" }, { "code": null, "e": 1550, "s": 1546, "text": "PHP" }, { "code": null, "e": 1563, "s": 1550, "text": "PHP Programs" }, { "code": null, "e": 1580, "s": 1563, "text": "Web Technologies" }, { "code": null, "e": 1607, "s": 1580, "text": "Web technologies Questions" }, { "code": null, "e": 1611, "s": 1607, "text": "PHP" } ]
Understanding Character Encoding
07 Feb, 2018 Ever imagined how a computer is able to understand and display what you have written? Ever wondered what a UTF-8 or UTF-16 meant when you were going through some configurations? Just think about how “HeLLo WorlD” should be interpreted by a computer.We all know that a computer stores data in bits and bytes. So, to display a character on screen or map the character as a byte in memory of the computer needs to have a standard. Read the following : \x48\x65\x4C\x4C\x6F\x20\x57\x6F\x72\x6C\x44 This is something a memory would show you. How do you know what character each memory byte specifies? Here comes character encoding into the picture: If you have already not guessed it – Its “HeLLo WorlD” in UTF-8 for you. And yes, we will go ahead and read about UTF-8. But let’s start with ASCII. Most of you who have done programming or worked with strings must have known what ASCII is. If you haven’t then let’s define what ASCII is.ASCII: ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as ‘a’ or ‘@’ or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose. Just look at the following – And so on. You can look at the ASCII table and mapping at http://www.asciitable.com/. If you have not already looked at the table, I will recommend that you do it now! You will observe that these are a simple set of English words and punctuations. Now Suppose I want to write the below characters: AB?@ This will be interpreted by my decoder as 0x410x0a0x200x420x3f0x40 in hex and 065010032066063064 in decimal, where even a space (0x20) and a next line (0x0a) has a byte value or a memory space. Different countries, languages but the need that brought them together Today internet has made the world come close together. And the people all over the world do not speak just English, right? There came a need to expand this space. If you have created an application and you see that people in France want to use it as you see a high potential there. Wouldn’t it be nice to just have a change in language but having the same functionality? Why not create a Universal Code in short Unicode for everyone ?? So, here came the Unicode with a really good idea. It assigned every character, including different languages, a unique number called Code Point. One advantage of Unicode over other possible sets is that its first 256 code points are identical to ASCII. So for a software/browser it is easier to encode and decode characters of majority of living languages in use on computers. It aims to be, and to a large extent already is, a superset of all other character sets that have been encoded. Unicode also is a character set (not an encoding). It uses the same characters like the ASCII standard, but it extends the list with additional characters, which gives each character a Code point. It has the ambition to contain all characters (and popular icons) used in the entire world. Before knowing these let us get a few terminologies straight : A character is a minimal unit of text that has semantic value. A character set is a collection of characters that might be used by multiple languages. Example: The Latin character set is used by English and most European languages, though the Greek character set is used only by the Greek language. A coded character set is a character set in which each character corresponds to a unique number. A code point of a coded character set is any legal value in the character set. A code unit is a bit sequence used to encode each character of a repertoire within a given encoding form. Ever wondered what is UTF-8 or UTF-16?? UTF-8: UTF-8 has truly been the dominant character encoding for the World Wide Web since 2009, and as of June 2017 accounts for 89.4% of all Web pages. UTF-8 encodes each of the 1,112,064 valid code points in Unicode using one to four 8-bit bytes. Code points with lower numerical values, which tend to occur more frequently, are encoded using fewer bytes. The first 128 characters of Unicode, which correspond one-to-one with ASCII, are encoded using a single octet with the same binary value as ASCII, so that valid ASCII text is valid UTF-8-encoded Unicode as well. So how many bytes give access to what characters in these encodings?UTF-8:1 byte: Standard ASCII2 bytes: Arabic, Hebrew, most European scripts (most notably excluding Georgian)3 bytes: BMP4 bytes: All Unicode characters UTF-16:2 bytes: BMP4 bytes: All Unicode characters So I did make a mention about BMP. What is it exactly? Basic Multilingual Plane (BMP) contains characters for almost all modern languages, and a large number of symbols. A primary objective for the BMP is to support the unification of prior character sets as well as characters for writing. UTF-8, UTF-16 and UTF-32 are encodings that apply the Unicode character table. But they each have a slightly different way on how to encode them. UTF-8 will only use 1 byte when encoding an ASCII character, giving the same output as any other ASCII encoding. But for other characters, it will use the first bit to indicate that a 2nd byte will follow. UTF-16 uses 16-bit by default, but that only gives you 65k possible characters, which is nowhere near enough for the full Unicode set. So some characters use pairs of 16-bit values. UTF-32 is opposite, it uses the most memory (each character is a fixed 4 bytes wide), which makes it quite bloated but now in this scenario every character has this precise length, so string manipulation becomes far simpler. You can compute the number of characters in a string simply from the length in bytes of the string. You can’t do that with UTF-8.This is how it eases to accommodate the entire character set for different languages and help people spread their applications or information to the world just coding/writing in their language rest all is taken care by the Decoder. As this being just the beginning into the world of Character Encoding. I hope this helps you understand Character encoding at a higher level. This article is contributed by Deepa Banerjee. 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. GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Feb, 2018" }, { "code": null, "e": 503, "s": 54, "text": "Ever imagined how a computer is able to understand and display what you have written? Ever wondered what a UTF-8 or UTF-16 meant when you were going through some configurations? Just think about how “HeLLo WorlD” should be interpreted by a computer.We all know that a computer stores data in bits and bytes. So, to display a character on screen or map the character as a byte in memory of the computer needs to have a standard. Read the following :" }, { "code": null, "e": 548, "s": 503, "text": "\\x48\\x65\\x4C\\x4C\\x6F\\x20\\x57\\x6F\\x72\\x6C\\x44" }, { "code": null, "e": 650, "s": 548, "text": "This is something a memory would show you. How do you know what character each memory byte specifies?" }, { "code": null, "e": 698, "s": 650, "text": "Here comes character encoding into the picture:" }, { "code": null, "e": 1327, "s": 698, "text": "If you have already not guessed it – Its “HeLLo WorlD” in UTF-8 for you. And yes, we will go ahead and read about UTF-8. But let’s start with ASCII. Most of you who have done programming or worked with strings must have known what ASCII is. If you haven’t then let’s define what ASCII is.ASCII: ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as ‘a’ or ‘@’ or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose." }, { "code": null, "e": 1356, "s": 1327, "text": "Just look at the following –" }, { "code": null, "e": 1604, "s": 1356, "text": "And so on. You can look at the ASCII table and mapping at http://www.asciitable.com/. If you have not already looked at the table, I will recommend that you do it now! You will observe that these are a simple set of English words and punctuations." }, { "code": null, "e": 1655, "s": 1604, "text": "Now Suppose I want to write the below characters: " }, { "code": null, "e": 1660, "s": 1655, "text": "AB?@" }, { "code": null, "e": 1854, "s": 1660, "text": "This will be interpreted by my decoder as 0x410x0a0x200x420x3f0x40 in hex and 065010032066063064 in decimal, where even a space (0x20) and a next line (0x0a) has a byte value or a memory space." }, { "code": null, "e": 1926, "s": 1854, "text": "Different countries, languages but the need that brought them together " }, { "code": null, "e": 2297, "s": 1926, "text": "Today internet has made the world come close together. And the people all over the world do not speak just English, right? There came a need to expand this space. If you have created an application and you see that people in France want to use it as you see a high potential there. Wouldn’t it be nice to just have a change in language but having the same functionality?" }, { "code": null, "e": 2362, "s": 2297, "text": "Why not create a Universal Code in short Unicode for everyone ??" }, { "code": null, "e": 2852, "s": 2362, "text": "So, here came the Unicode with a really good idea. It assigned every character, including different languages, a unique number called Code Point. One advantage of Unicode over other possible sets is that its first 256 code points are identical to ASCII. So for a software/browser it is easier to encode and decode characters of majority of living languages in use on computers. It aims to be, and to a large extent already is, a superset of all other character sets that have been encoded." }, { "code": null, "e": 3141, "s": 2852, "text": "Unicode also is a character set (not an encoding). It uses the same characters like the ASCII standard, but it extends the list with additional characters, which gives each character a Code point. It has the ambition to contain all characters (and popular icons) used in the entire world." }, { "code": null, "e": 3204, "s": 3141, "text": "Before knowing these let us get a few terminologies straight :" }, { "code": null, "e": 3267, "s": 3204, "text": "A character is a minimal unit of text that has semantic value." }, { "code": null, "e": 3503, "s": 3267, "text": "A character set is a collection of characters that might be used by multiple languages. Example: The Latin character set is used by English and most European languages, though the Greek character set is used only by the Greek language." }, { "code": null, "e": 3600, "s": 3503, "text": "A coded character set is a character set in which each character corresponds to a unique number." }, { "code": null, "e": 3679, "s": 3600, "text": "A code point of a coded character set is any legal value in the character set." }, { "code": null, "e": 3785, "s": 3679, "text": "A code unit is a bit sequence used to encode each character of a repertoire within a given encoding form." }, { "code": null, "e": 3825, "s": 3785, "text": "Ever wondered what is UTF-8 or UTF-16??" }, { "code": null, "e": 4394, "s": 3825, "text": "UTF-8: UTF-8 has truly been the dominant character encoding for the World Wide Web since 2009, and as of June 2017 accounts for 89.4% of all Web pages. UTF-8 encodes each of the 1,112,064 valid code points in Unicode using one to four 8-bit bytes. Code points with lower numerical values, which tend to occur more frequently, are encoded using fewer bytes. The first 128 characters of Unicode, which correspond one-to-one with ASCII, are encoded using a single octet with the same binary value as ASCII, so that valid ASCII text is valid UTF-8-encoded Unicode as well." }, { "code": null, "e": 4614, "s": 4394, "text": "So how many bytes give access to what characters in these encodings?UTF-8:1 byte: Standard ASCII2 bytes: Arabic, Hebrew, most European scripts (most notably excluding Georgian)3 bytes: BMP4 bytes: All Unicode characters" }, { "code": null, "e": 4665, "s": 4614, "text": "UTF-16:2 bytes: BMP4 bytes: All Unicode characters" }, { "code": null, "e": 4720, "s": 4665, "text": "So I did make a mention about BMP. What is it exactly?" }, { "code": null, "e": 4956, "s": 4720, "text": "Basic Multilingual Plane (BMP) contains characters for almost all modern languages, and a large number of symbols. A primary objective for the BMP is to support the unification of prior character sets as well as characters for writing." }, { "code": null, "e": 6076, "s": 4956, "text": "UTF-8, UTF-16 and UTF-32 are encodings that apply the Unicode character table. But they each have a slightly different way on how to encode them. UTF-8 will only use 1 byte when encoding an ASCII character, giving the same output as any other ASCII encoding. But for other characters, it will use the first bit to indicate that a 2nd byte will follow. UTF-16 uses 16-bit by default, but that only gives you 65k possible characters, which is nowhere near enough for the full Unicode set. So some characters use pairs of 16-bit values. UTF-32 is opposite, it uses the most memory (each character is a fixed 4 bytes wide), which makes it quite bloated but now in this scenario every character has this precise length, so string manipulation becomes far simpler. You can compute the number of characters in a string simply from the length in bytes of the string. You can’t do that with UTF-8.This is how it eases to accommodate the entire character set for different languages and help people spread their applications or information to the world just coding/writing in their language rest all is taken care by the Decoder." }, { "code": null, "e": 6218, "s": 6076, "text": "As this being just the beginning into the world of Character Encoding. I hope this helps you understand Character encoding at a higher level." }, { "code": null, "e": 6644, "s": 6218, "text": "This article is contributed by Deepa Banerjee. 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." }, { "code": null, "e": 6650, "s": 6644, "text": "GBlog" } ]
Leaders in an array | Practice | GeeksforGeeks
Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. Example 1: Input: n = 6 A[] = {16,17,4,3,5,2} Output: 17 5 2 Explanation: The first leader is 17 as it is greater than all the elements to its right. Similarly, the next leader is 5. The right most element is always a leader so it is also included. Example 2: Input: n = 5 A[] = {1,2,3,4,0} Output: 4 0 Your Task: You don't need to read input or print anything. The task is to complete the function leader() which takes array A and n as input parameters and returns an array of leaders in order of their appearance. Expected Time Complexity: O(n) Expected Auxiliary Space: O(n) Constraints: 1 <= n <= 107 0 <= Ai <= 107 0 madanlalsalvi20012 hours ago #Simple C++ solution vector<int> leaders(int a[], int n){ // Code here vector<int> v; int max=a[n-1]; for(int i=n-1;i>=0;i--){ if(a[i]>=max) { max=a[i]; v.push_back(max); } } reverse(v.begin(), v.end()); return v; } 0 vishaltuqz18 hours ago Simple Easy to understand Java code class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> res = new ArrayList<>(); int max = -1; for ( int i = n-1; i >= 0; i--){ if (arr[i] >= max){ max = arr[i]; res.add(max); } } Collections.reverse(res); return res; }} +1 surendramkishor2 days ago #Very Easy Python Solution for understand def leaders(self, A, N): #Code here Max = 0 leaders = [] for item in reversed(A): if item >= Max: leaders.append(item) Max = item return reversed(leaders) 0 aditya1h2o2 days ago C++ solution class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ // Code here int max=a[n-1]; vector<int>A; A.push_back(a[n-1]); for(int i=n-2;i>=0;i--){ if(a[i]>=max){ A.push_back(a[i]); max=a[i]; } } reverse(A.begin(),A.end()); return A; }}; 0 rushabhkalmate2 days ago class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ int maxi=INT_MIN; vector<int>ans; for(int i=n-1;i>=0;i--){ if(a[i]>=maxi){ ans.push_back(a[i]); maxi=max(a[i],maxi); } } reverse(ans.begin(), ans.end()); return ans; }}; 0 mokalevaibhav3 days ago MOST EFFICIENT C++ SOLUTION : vector<int> leaders(int a[], int n) { int max=0; vector<int> v; for(int i=n-1;i>=0;i--) { if(max<=a[i]) { max=a[i]; v.push_back(max); } } int s=v.size(); for(int i=0;i<s/2;i++) { v[i]^=v[s-i-1]^=v[i]^=v[s-1-i]; } //reverse(v.begin(),v.end()); return v; } 0 shivamdubeyagra84 days ago // Time = 1.19/2.51 (Java Solution) class Solution{ static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> ans = new ArrayList<>(); ans.add(arr[n-1]); int leader = arr[n-1]; for(int i=n-2; i>=0; i--) { if(arr[i] >= leader) { ans.add(arr[i]); leader = arr[i]; } } Collections.reverse(ans); return ans; }} 0 cu15bcs15875 days ago static ArrayList<Integer> leaders(int arr[], int n){ // Your code here ArrayList<Integer> res = new ArrayList<>(); int t1=0,t2=arr[n-1]; res.add(arr[n-1]); for(int i = n-2; i >= 0; i--) { t1 = arr[i]; t2 = Math.max(t1,t2); if(t1 == t2) res.add(t1); } Collections.reverse(res); return res; } 0 swatidubey9145 days ago JAVA easy solution , Upvote if helpfull. class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> al = new ArrayList<>(); Stack<Integer> st = new Stack<>(); st.push(arr[n-1]); int max = arr[n-1]; for(int i = n-2 ; i >= 0 ; i--){ if(arr[i] >= max){ st.push(arr[i]); max = arr[i]; } } while(st.size() > 0){ al.add(st.pop()); } return al; }} 0 swaptheshinigami5 days ago class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> leaders =new ArrayList<Integer>(); leaders.add(arr[n-1]); int leader=arr[n-1]; for(int i=n-2;i>=0;i--){ if(arr[i]>=leader){ leaders.add(arr[i]); leader=arr[i]; } } Collections.reverse(leaders); return leaders; }} 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. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems 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": 467, "s": 238, "text": "Given an array A of positive integers. Your task is to find the leaders in the array. An element of array is leader if it is greater than or equal to all the elements to its right side. The rightmost element is always a leader. " }, { "code": null, "e": 480, "s": 469, "text": "Example 1:" }, { "code": null, "e": 724, "s": 480, "text": "Input:\nn = 6\nA[] = {16,17,4,3,5,2}\nOutput: 17 5 2\nExplanation: The first leader is 17 \nas it is greater than all the elements\nto its right. Similarly, the next \nleader is 5. The right most element \nis always a leader so it is also \nincluded.\n" }, { "code": null, "e": 737, "s": 726, "text": "Example 2:" }, { "code": null, "e": 781, "s": 737, "text": "Input:\nn = 5\nA[] = {1,2,3,4,0}\nOutput: 4 0\n" }, { "code": null, "e": 996, "s": 783, "text": "Your Task:\nYou don't need to read input or print anything. The task is to complete the function leader() which takes array A and n as input parameters and returns an array of leaders in order of their appearance." }, { "code": null, "e": 1060, "s": 998, "text": "Expected Time Complexity: O(n)\nExpected Auxiliary Space: O(n)" }, { "code": null, "e": 1104, "s": 1062, "text": "Constraints:\n1 <= n <= 107\n0 <= Ai <= 107" }, { "code": null, "e": 1106, "s": 1104, "text": "0" }, { "code": null, "e": 1135, "s": 1106, "text": "madanlalsalvi20012 hours ago" }, { "code": null, "e": 1157, "s": 1135, "text": "#Simple C++ solution " }, { "code": null, "e": 1475, "s": 1159, "text": " vector<int> leaders(int a[], int n){ // Code here vector<int> v; int max=a[n-1]; for(int i=n-1;i>=0;i--){ if(a[i]>=max) { max=a[i]; v.push_back(max); } } reverse(v.begin(), v.end()); return v; }" }, { "code": null, "e": 1477, "s": 1475, "text": "0" }, { "code": null, "e": 1500, "s": 1477, "text": "vishaltuqz18 hours ago" }, { "code": null, "e": 1536, "s": 1500, "text": "Simple Easy to understand Java code" }, { "code": null, "e": 1972, "s": 1536, "text": "class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> res = new ArrayList<>(); int max = -1; for ( int i = n-1; i >= 0; i--){ if (arr[i] >= max){ max = arr[i]; res.add(max); } } Collections.reverse(res); return res; }}" }, { "code": null, "e": 1975, "s": 1972, "text": "+1" }, { "code": null, "e": 2001, "s": 1975, "text": "surendramkishor2 days ago" }, { "code": null, "e": 2287, "s": 2001, "text": "#Very Easy Python Solution for understand\n\n def leaders(self, A, N):\n #Code here\n Max = 0\n leaders = []\n for item in reversed(A):\n if item >= Max:\n leaders.append(item)\n Max = item\n return reversed(leaders)" }, { "code": null, "e": 2289, "s": 2287, "text": "0" }, { "code": null, "e": 2310, "s": 2289, "text": "aditya1h2o2 days ago" }, { "code": null, "e": 2323, "s": 2310, "text": "C++ solution" }, { "code": null, "e": 2713, "s": 2323, "text": "class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ // Code here int max=a[n-1]; vector<int>A; A.push_back(a[n-1]); for(int i=n-2;i>=0;i--){ if(a[i]>=max){ A.push_back(a[i]); max=a[i]; } } reverse(A.begin(),A.end()); return A; }}; " }, { "code": null, "e": 2715, "s": 2713, "text": "0" }, { "code": null, "e": 2740, "s": 2715, "text": "rushabhkalmate2 days ago" }, { "code": null, "e": 3111, "s": 2740, "text": "class Solution{ //Function to find the leaders in the array. public: vector<int> leaders(int a[], int n){ int maxi=INT_MIN; vector<int>ans; for(int i=n-1;i>=0;i--){ if(a[i]>=maxi){ ans.push_back(a[i]); maxi=max(a[i],maxi); } } reverse(ans.begin(), ans.end()); return ans; }};" }, { "code": null, "e": 3113, "s": 3111, "text": "0" }, { "code": null, "e": 3137, "s": 3113, "text": "mokalevaibhav3 days ago" }, { "code": null, "e": 3168, "s": 3137, "text": "MOST EFFICIENT C++ SOLUTION : " }, { "code": null, "e": 3608, "s": 3168, "text": "vector<int> leaders(int a[], int n)\n{\n int max=0;\n vector<int> v;\n for(int i=n-1;i>=0;i--)\n {\n \n if(max<=a[i])\n {\n max=a[i];\n v.push_back(max);\n }\n }\n int s=v.size();\n for(int i=0;i<s/2;i++)\n {\n v[i]^=v[s-i-1]^=v[i]^=v[s-1-i];\n }\n //reverse(v.begin(),v.end());\n return v;\n }" }, { "code": null, "e": 3610, "s": 3608, "text": "0" }, { "code": null, "e": 3637, "s": 3610, "text": "shivamdubeyagra84 days ago" }, { "code": null, "e": 3702, "s": 3637, "text": "// Time = 1.19/2.51 (Java Solution)" }, { "code": null, "e": 3720, "s": 3704, "text": "class Solution{" }, { "code": null, "e": 3776, "s": 3720, "text": " static ArrayList<Integer> leaders(int arr[], int n){" }, { "code": null, "e": 4121, "s": 3776, "text": " ArrayList<Integer> ans = new ArrayList<>(); ans.add(arr[n-1]); int leader = arr[n-1]; for(int i=n-2; i>=0; i--) { if(arr[i] >= leader) { ans.add(arr[i]); leader = arr[i]; } } Collections.reverse(ans); return ans; }}" }, { "code": null, "e": 4123, "s": 4121, "text": "0" }, { "code": null, "e": 4145, "s": 4123, "text": "cu15bcs15875 days ago" }, { "code": null, "e": 4553, "s": 4145, "text": "static ArrayList<Integer> leaders(int arr[], int n){\n // Your code here\n ArrayList<Integer> res = new ArrayList<>();\n int t1=0,t2=arr[n-1];\n res.add(arr[n-1]);\n for(int i = n-2; i >= 0; i--) {\n t1 = arr[i];\n t2 = Math.max(t1,t2);\n \n if(t1 == t2) res.add(t1);\n }\n Collections.reverse(res);\n return res;\n }" }, { "code": null, "e": 4555, "s": 4553, "text": "0" }, { "code": null, "e": 4579, "s": 4555, "text": "swatidubey9145 days ago" }, { "code": null, "e": 4620, "s": 4579, "text": "JAVA easy solution , Upvote if helpfull." }, { "code": null, "e": 5122, "s": 4622, "text": "class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> al = new ArrayList<>(); Stack<Integer> st = new Stack<>(); st.push(arr[n-1]); int max = arr[n-1]; for(int i = n-2 ; i >= 0 ; i--){ if(arr[i] >= max){ st.push(arr[i]); max = arr[i]; } } while(st.size() > 0){ al.add(st.pop()); } return al; }} " }, { "code": null, "e": 5124, "s": 5122, "text": "0" }, { "code": null, "e": 5151, "s": 5124, "text": "swaptheshinigami5 days ago" }, { "code": null, "e": 5586, "s": 5151, "text": "class Solution{ //Function to find the leaders in the array. static ArrayList<Integer> leaders(int arr[], int n){ ArrayList<Integer> leaders =new ArrayList<Integer>(); leaders.add(arr[n-1]); int leader=arr[n-1]; for(int i=n-2;i>=0;i--){ if(arr[i]>=leader){ leaders.add(arr[i]); leader=arr[i]; } } Collections.reverse(leaders); return leaders; }}" }, { "code": null, "e": 5732, "s": 5586, "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": 5768, "s": 5732, "text": " Login to access your submissions. " }, { "code": null, "e": 5778, "s": 5768, "text": "\nProblem\n" }, { "code": null, "e": 5788, "s": 5778, "text": "\nContest\n" }, { "code": null, "e": 5851, "s": 5788, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6036, "s": 5851, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6320, "s": 6036, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 6466, "s": 6320, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 6543, "s": 6466, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 6584, "s": 6543, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 6612, "s": 6584, "text": "Disable browser extensions." }, { "code": null, "e": 6683, "s": 6612, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 6870, "s": 6683, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
MediaMetadataRetriever Class in Android with Examples
18 Feb, 2021 anMediaMetadataRetriever class provides a unified interface for retrieving frames and metadata from an input media file. It is located under android.media package. For example: retrieving song name, artist name, width or height of the video, video format/mime-type, duration of media, media modified date, etc. Constants/Keys provided by MediaMetadataRetriever class are plentiful. These constants are used to retrieve media information. Although, the work done by many of the Constants is obvious from their name, here is a small description of each constant present in MediaMetadataRetriever class. Constant Type Constant Name Description Constant Type Constant Name Description Method Type Methods extractMetadata(int keyCode) Call this method after setDataSource(). getEmbeddedPicture() Call this method after setDataSource(). getFrameAtTime(long timeUs, int option) Call this method after setDataSource(). getFrameAtTime(long timeUs) Call this method after setDataSource(). getFrameAtTime() Call this method after setDataSource(). release() Call it when one is done with the object. This method releases the memory allocated internally. setDataSource(FileDescriptor fd, long offset, long length) Sets the data source (FileDescriptor) to use. setDataSource(String path) Sets the data source (file pathname) to use. setDataSource(FileDescriptor fd) Sets the data source (FileDescriptor) to use. setDataSource(Context context, Uri uri) Sets the data source as a content Uri. Close() Closes this resource, relinquishing any underlying resources. This method is invoked automatically on objects managed by the try-with-resources statement. 1. Get mp3 duration Here is the sample code snippet in Java to get the mp3 duration. Java // load data file// filePath is of type String which holds the path of fileMediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();metaRetriever.setDataSource(filePath); // get mp3 infoString duration = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);long dur = Long.parseLong(duration); // convert duration to minute:secondsString seconds = String.valueOf((dur % 60000) / 1000);String minutes = String.valueOf(dur / 60000);String out = minutes + ":" + seconds;if (seconds.length() == 1) { txtTime.setText("0" + minutes + ":0" + seconds);}else { txtTime.setText("0" + minutes + ":" + seconds);} // close objectmetaRetriever.release(); 2. Detect the orientation of the video Below is a sample video Here is the sample code snippet in Java to detect the orientation of the video Java MediaMetadataRetriever m = new MediaMetadataRetriever(); // load data filem.setDataSource(path); // getting the bitmap of a frame from videoBitmap thumbnail = m.getFrameAtTime(); if (Build.VERSION.SDK_INT >= 17) { String s = m.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);} // Another way of determining whether the video is Landscape or portraitMediaMetadataRetriever retriever = new MediaMetadataRetriever();retriever.setDataSource(inputPath);video_width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));video_height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); // close objectretriever.release(); // If the width is bigger than the height then it means that// the video was taken in landscape mode and vice versa.if ((video_width > video_height)) { // landscape}else { // portrait} 3. Setting up the Album cover and Album title in a Music App Below is a sample image Here is the sample code snippet in Java to setting up the Album cover and Album title in a Music App. Java MediaMetadataRetriever retriever = new MediaMetadataRetriever();retriever.setDataSource(filePath); // getting the embedded picture from mediabyte[] art = retriever.getEmbeddedPicture(); if (art != null) { // Convert the byte array to a bitmap imgAlbum.setImageBitmap(BitmapFactory.decodeByteArray(art, 0, art.length));}else { imgAlbum.setImageResource(R.drawable.no_image);}// close objectretriever.release(); 4. Making a CropVideo Activity like TikTok Below is a sample video Here is the sample code snippet in Java to make a CropVideo Activity like TikTok. Java try { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(context, videoUri); // Retrieve media data use microsecond long interval = (endPosition - startPosition) / (totalThumbsCount - 1); for (long i = 0; i < totalThumbsCount; ++i) { long frameTime = startPosition + interval * i; Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(frameTime * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); if (bitmap == null) continue; try { bitmap = Bitmap.createScaledBitmap(bitmap, THUMB_WIDTH, THUMB_HEIGHT, false); } catch (final Throwable t) { t.printStackTrace(); } // add bitmaps to the recyclerview here... } mediaMetadataRetriever.release();}catch (final Throwable e) { Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);} Note: Always check for illegal filePath.Handle the null bitmap condition. There may be cases when the media doesn’t return a valid bitmap.The frame index must be that of a valid frame. The total number of frames available for retrieval can be queried via the METADATA_KEY_VIDEO_FRAME_COUNT key.When retrieving the frame at the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be returned. If time is negative, time position and option will be ignored, and any frame that the implementation considers as representative may be returned.setDataSource(), Call this method before the rest of the methods in this class. This method may be time-consuming. Always check for illegal filePath. Handle the null bitmap condition. There may be cases when the media doesn’t return a valid bitmap. The frame index must be that of a valid frame. The total number of frames available for retrieval can be queried via the METADATA_KEY_VIDEO_FRAME_COUNT key. When retrieving the frame at the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be returned. If time is negative, time position and option will be ignored, and any frame that the implementation considers as representative may be returned. setDataSource(), Call this method before the rest of the methods in this class. This method may be time-consuming. Reference link: https://developer.android.com/reference/android/media/MediaMetadataRetriever android 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": 52, "s": 24, "text": "\n18 Feb, 2021" }, { "code": null, "e": 653, "s": 52, "text": "anMediaMetadataRetriever class provides a unified interface for retrieving frames and metadata from an input media file. It is located under android.media package. For example: retrieving song name, artist name, width or height of the video, video format/mime-type, duration of media, media modified date, etc. Constants/Keys provided by MediaMetadataRetriever class are plentiful. These constants are used to retrieve media information. Although, the work done by many of the Constants is obvious from their name, here is a small description of each constant present in MediaMetadataRetriever class." }, { "code": null, "e": 667, "s": 653, "text": "Constant Type" }, { "code": null, "e": 681, "s": 667, "text": "Constant Name" }, { "code": null, "e": 693, "s": 681, "text": "Description" }, { "code": null, "e": 707, "s": 693, "text": "Constant Type" }, { "code": null, "e": 721, "s": 707, "text": "Constant Name" }, { "code": null, "e": 733, "s": 721, "text": "Description" }, { "code": null, "e": 745, "s": 733, "text": "Method Type" }, { "code": null, "e": 753, "s": 745, "text": "Methods" }, { "code": null, "e": 782, "s": 753, "text": "extractMetadata(int keyCode)" }, { "code": null, "e": 822, "s": 782, "text": "Call this method after setDataSource()." }, { "code": null, "e": 843, "s": 822, "text": "getEmbeddedPicture()" }, { "code": null, "e": 883, "s": 843, "text": "Call this method after setDataSource()." }, { "code": null, "e": 923, "s": 883, "text": "getFrameAtTime(long timeUs, int option)" }, { "code": null, "e": 963, "s": 923, "text": "Call this method after setDataSource()." }, { "code": null, "e": 991, "s": 963, "text": "getFrameAtTime(long timeUs)" }, { "code": null, "e": 1031, "s": 991, "text": "Call this method after setDataSource()." }, { "code": null, "e": 1048, "s": 1031, "text": "getFrameAtTime()" }, { "code": null, "e": 1088, "s": 1048, "text": "Call this method after setDataSource()." }, { "code": null, "e": 1098, "s": 1088, "text": "release()" }, { "code": null, "e": 1140, "s": 1098, "text": "Call it when one is done with the object." }, { "code": null, "e": 1194, "s": 1140, "text": "This method releases the memory allocated internally." }, { "code": null, "e": 1253, "s": 1194, "text": "setDataSource(FileDescriptor fd, long offset, long length)" }, { "code": null, "e": 1299, "s": 1253, "text": "Sets the data source (FileDescriptor) to use." }, { "code": null, "e": 1326, "s": 1299, "text": "setDataSource(String path)" }, { "code": null, "e": 1371, "s": 1326, "text": "Sets the data source (file pathname) to use." }, { "code": null, "e": 1404, "s": 1371, "text": "setDataSource(FileDescriptor fd)" }, { "code": null, "e": 1450, "s": 1404, "text": "Sets the data source (FileDescriptor) to use." }, { "code": null, "e": 1490, "s": 1450, "text": "setDataSource(Context context, Uri uri)" }, { "code": null, "e": 1529, "s": 1490, "text": "Sets the data source as a content Uri." }, { "code": null, "e": 1537, "s": 1529, "text": "Close()" }, { "code": null, "e": 1600, "s": 1537, "text": "Closes this resource, relinquishing any underlying resources. " }, { "code": null, "e": 1660, "s": 1600, "text": "This method is invoked automatically on objects managed by " }, { "code": null, "e": 1694, "s": 1660, "text": "the try-with-resources statement." }, { "code": null, "e": 1714, "s": 1694, "text": "1. Get mp3 duration" }, { "code": null, "e": 1780, "s": 1714, "text": "Here is the sample code snippet in Java to get the mp3 duration. " }, { "code": null, "e": 1785, "s": 1780, "text": "Java" }, { "code": "// load data file// filePath is of type String which holds the path of fileMediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();metaRetriever.setDataSource(filePath); // get mp3 infoString duration = metaRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);long dur = Long.parseLong(duration); // convert duration to minute:secondsString seconds = String.valueOf((dur % 60000) / 1000);String minutes = String.valueOf(dur / 60000);String out = minutes + \":\" + seconds;if (seconds.length() == 1) { txtTime.setText(\"0\" + minutes + \":0\" + seconds);}else { txtTime.setText(\"0\" + minutes + \":\" + seconds);} // close objectmetaRetriever.release();", "e": 2469, "s": 1785, "text": null }, { "code": null, "e": 2508, "s": 2469, "text": "2. Detect the orientation of the video" }, { "code": null, "e": 2532, "s": 2508, "text": "Below is a sample video" }, { "code": null, "e": 2611, "s": 2532, "text": "Here is the sample code snippet in Java to detect the orientation of the video" }, { "code": null, "e": 2616, "s": 2611, "text": "Java" }, { "code": "MediaMetadataRetriever m = new MediaMetadataRetriever(); // load data filem.setDataSource(path); // getting the bitmap of a frame from videoBitmap thumbnail = m.getFrameAtTime(); if (Build.VERSION.SDK_INT >= 17) { String s = m.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION);} // Another way of determining whether the video is Landscape or portraitMediaMetadataRetriever retriever = new MediaMetadataRetriever();retriever.setDataSource(inputPath);video_width = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH));video_height = Integer.valueOf(retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)); // close objectretriever.release(); // If the width is bigger than the height then it means that// the video was taken in landscape mode and vice versa.if ((video_width > video_height)) { // landscape}else { // portrait}", "e": 3535, "s": 2616, "text": null }, { "code": null, "e": 3596, "s": 3535, "text": "3. Setting up the Album cover and Album title in a Music App" }, { "code": null, "e": 3620, "s": 3596, "text": "Below is a sample image" }, { "code": null, "e": 3722, "s": 3620, "text": "Here is the sample code snippet in Java to setting up the Album cover and Album title in a Music App." }, { "code": null, "e": 3727, "s": 3722, "text": "Java" }, { "code": "MediaMetadataRetriever retriever = new MediaMetadataRetriever();retriever.setDataSource(filePath); // getting the embedded picture from mediabyte[] art = retriever.getEmbeddedPicture(); if (art != null) { // Convert the byte array to a bitmap imgAlbum.setImageBitmap(BitmapFactory.decodeByteArray(art, 0, art.length));}else { imgAlbum.setImageResource(R.drawable.no_image);}// close objectretriever.release();", "e": 4148, "s": 3727, "text": null }, { "code": null, "e": 4191, "s": 4148, "text": "4. Making a CropVideo Activity like TikTok" }, { "code": null, "e": 4215, "s": 4191, "text": "Below is a sample video" }, { "code": null, "e": 4297, "s": 4215, "text": "Here is the sample code snippet in Java to make a CropVideo Activity like TikTok." }, { "code": null, "e": 4302, "s": 4297, "text": "Java" }, { "code": "try { MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); mediaMetadataRetriever.setDataSource(context, videoUri); // Retrieve media data use microsecond long interval = (endPosition - startPosition) / (totalThumbsCount - 1); for (long i = 0; i < totalThumbsCount; ++i) { long frameTime = startPosition + interval * i; Bitmap bitmap = mediaMetadataRetriever.getFrameAtTime(frameTime * 1000, MediaMetadataRetriever.OPTION_CLOSEST_SYNC); if (bitmap == null) continue; try { bitmap = Bitmap.createScaledBitmap(bitmap, THUMB_WIDTH, THUMB_HEIGHT, false); } catch (final Throwable t) { t.printStackTrace(); } // add bitmaps to the recyclerview here... } mediaMetadataRetriever.release();}catch (final Throwable e) { Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);}", "e": 5244, "s": 4302, "text": null }, { "code": null, "e": 5250, "s": 5244, "text": "Note:" }, { "code": null, "e": 5984, "s": 5250, "text": "Always check for illegal filePath.Handle the null bitmap condition. There may be cases when the media doesn’t return a valid bitmap.The frame index must be that of a valid frame. The total number of frames available for retrieval can be queried via the METADATA_KEY_VIDEO_FRAME_COUNT key.When retrieving the frame at the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be returned. If time is negative, time position and option will be ignored, and any frame that the implementation considers as representative may be returned.setDataSource(), Call this method before the rest of the methods in this class. This method may be time-consuming." }, { "code": null, "e": 6019, "s": 5984, "text": "Always check for illegal filePath." }, { "code": null, "e": 6118, "s": 6019, "text": "Handle the null bitmap condition. There may be cases when the media doesn’t return a valid bitmap." }, { "code": null, "e": 6275, "s": 6118, "text": "The frame index must be that of a valid frame. The total number of frames available for retrieval can be queried via the METADATA_KEY_VIDEO_FRAME_COUNT key." }, { "code": null, "e": 6607, "s": 6275, "text": "When retrieving the frame at the given time position, there is no guarantee that the data source has a frame located at the position. When this happens, a frame nearby will be returned. If time is negative, time position and option will be ignored, and any frame that the implementation considers as representative may be returned." }, { "code": null, "e": 6722, "s": 6607, "text": "setDataSource(), Call this method before the rest of the methods in this class. This method may be time-consuming." }, { "code": null, "e": 6815, "s": 6722, "text": "Reference link: https://developer.android.com/reference/android/media/MediaMetadataRetriever" }, { "code": null, "e": 6823, "s": 6815, "text": "android" }, { "code": null, "e": 6836, "s": 6823, "text": "Android-View" }, { "code": null, "e": 6844, "s": 6836, "text": "Android" }, { "code": null, "e": 6849, "s": 6844, "text": "Java" }, { "code": null, "e": 6854, "s": 6849, "text": "Java" }, { "code": null, "e": 6862, "s": 6854, "text": "Android" } ]
Test Case Generation | Set 5 (Generating random Sorted Arrays and Palindromes)
28 Jun, 2021 Generating Random Sorted ArraysWe store the random array elements in an array and then sort it and print it. // A C++ Program to generate test cases for// array filled with random numbers#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated#define MAX 100000 // Define the maximum number of array elements#define MAXNUM 100 int main(){ // Uncomment the below line to store // the test data in a file // freopen("Test_Cases_Random_Sorted_Array.in", // "w", stdout); // For random values every time srand(time(NULL)); int NUM; // Number of array elements for (int i=1; i<=RUN; i++) { int arr[MAXNUM]; NUM = 1 + rand() % MAXNUM; // First print the number of array elements printf("%d\n", NUM); // Then print the array elements separated by // space for (int j=0; j<NUM; j++) arr[j] = rand() % MAX; // Sort the generated random array sort (arr, arr + NUM); // Print the sorted random array for (int j=0; j<NUM; j++) printf("%d ", arr[j]); printf("\n"); } // Uncomment the below line to store // the test data in a file // fclose(stdout); return(0);} Generating Random Palindromes The test case generation plan generates odd as well as even length palindromes. The test case generation plan uses one of the most under-rated data structure- Deque Since a palindrome is read the same from left as well as right so we simply put the same random characters on both the left side (done using push_front()) and the right side (done using push_back()) // A C++ Program to generate test cases for// random strings#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated// Here it is 'a' to 'z'#define MAX 25 // Define the maximum length of string#define MAXLEN 50 int main(){ // Uncomment the below line to store // the test data in a file // freopen("Test_Cases_Palindrome.in", "w", // stdout); // For random values every time srand(time(NULL)); // A container for storing the palindromes deque<char> container; deque<char>::iterator it; int LEN; // Length of string for (int i=1; i<=RUN; i++) { LEN = 1 + rand() % MAXLEN; // First print the length of string printf("%d\n", LEN); // If it is an odd-length palindrome if (LEN % 2) container.push_back('a' + rand() % MAX); // Then print the characters of the palindromic // string for (int j=1; j<=LEN/2; j++) { char ch = 'a' + rand() % MAX; container.push_back(ch); container.push_front(ch); } for (it=container.begin(); it!=container.end(); ++it) printf("%c",*it); container.clear(); printf("\n"); } // Uncomment the below line to store // the test data in a file // fclose(stdout); return(0);} This article is contributed by Rachit Belwariar. 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. References : –http://spojtoolkit.com/TestCaseGenerator/ Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Competitive Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 161, "s": 52, "text": "Generating Random Sorted ArraysWe store the random array elements in an array and then sort it and print it." }, { "code": "// A C++ Program to generate test cases for// array filled with random numbers#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated#define MAX 100000 // Define the maximum number of array elements#define MAXNUM 100 int main(){ // Uncomment the below line to store // the test data in a file // freopen(\"Test_Cases_Random_Sorted_Array.in\", // \"w\", stdout); // For random values every time srand(time(NULL)); int NUM; // Number of array elements for (int i=1; i<=RUN; i++) { int arr[MAXNUM]; NUM = 1 + rand() % MAXNUM; // First print the number of array elements printf(\"%d\\n\", NUM); // Then print the array elements separated by // space for (int j=0; j<NUM; j++) arr[j] = rand() % MAX; // Sort the generated random array sort (arr, arr + NUM); // Print the sorted random array for (int j=0; j<NUM; j++) printf(\"%d \", arr[j]); printf(\"\\n\"); } // Uncomment the below line to store // the test data in a file // fclose(stdout); return(0);}", "e": 1391, "s": 161, "text": null }, { "code": null, "e": 1423, "s": 1393, "text": "Generating Random Palindromes" }, { "code": null, "e": 1503, "s": 1423, "text": "The test case generation plan generates odd as well as even length palindromes." }, { "code": null, "e": 1588, "s": 1503, "text": "The test case generation plan uses one of the most under-rated data structure- Deque" }, { "code": null, "e": 1787, "s": 1588, "text": "Since a palindrome is read the same from left as well as right so we simply put the same random characters on both the left side (done using push_front()) and the right side (done using push_back())" }, { "code": "// A C++ Program to generate test cases for// random strings#include<bits/stdc++.h>using namespace std; // Define the number of runs for the test data// generated#define RUN 5 // Define the range of the test data generated// Here it is 'a' to 'z'#define MAX 25 // Define the maximum length of string#define MAXLEN 50 int main(){ // Uncomment the below line to store // the test data in a file // freopen(\"Test_Cases_Palindrome.in\", \"w\", // stdout); // For random values every time srand(time(NULL)); // A container for storing the palindromes deque<char> container; deque<char>::iterator it; int LEN; // Length of string for (int i=1; i<=RUN; i++) { LEN = 1 + rand() % MAXLEN; // First print the length of string printf(\"%d\\n\", LEN); // If it is an odd-length palindrome if (LEN % 2) container.push_back('a' + rand() % MAX); // Then print the characters of the palindromic // string for (int j=1; j<=LEN/2; j++) { char ch = 'a' + rand() % MAX; container.push_back(ch); container.push_front(ch); } for (it=container.begin(); it!=container.end(); ++it) printf(\"%c\",*it); container.clear(); printf(\"\\n\"); } // Uncomment the below line to store // the test data in a file // fclose(stdout); return(0);}", "e": 3243, "s": 1787, "text": null }, { "code": null, "e": 3543, "s": 3243, "text": "This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 3599, "s": 3543, "text": "References : –http://spojtoolkit.com/TestCaseGenerator/" }, { "code": null, "e": 3724, "s": 3599, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3748, "s": 3724, "text": "Competitive Programming" } ]
What is thread safe or non-thread safe in PHP ? - GeeksforGeeks
17 Jul, 2019 Thread-safe: It is used to ensure that when the shared data structure which is manipulated by different threads are prevented from entering the race condition. Thread-safety is recommended when the web server run multiple threads of execution simultaneously for different requests. In Thread Safety binary can work in a multi-threaded web server context. Thread Safety works by creating a local storage copy in each thread so that the data will not collide with another thread.For example: Apache + LoadModule IIS Non-thread-safe: It does not check the safety of the threads which makes it faster to run but at the same time, it becomes more unstable and crashes very frequently. It refers to a single thread only builds. In non-thread safe version binaries widespread use in the case of interaction with a web server through the FastCGI protocol, by not utilizing multi-threading.For example: Apache + FastCGI IIS + FastCGI So it depends on the way that you want to use PHP. AFAIR running PHP with the fastCGI is the preferable way. If you are unknown which version of PHP is installed in your system then there is an easy way to know that.Check the version of installed PHP Thread safe or Non Thread Safe:Open a phpinfo() and search for the line Thread safety for a thread-safe build you should find enable. On Windows:php -i|findstr "Thread" php -i|findstr "Thread" On *nix:php -i|grep Thread php -i|grep Thread In the both cases will display any oneThread Safety => enabled //or Thread Safety => disabled Thread Safety => enabled //or Thread Safety => disabled Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? How to receive JSON POST with PHP ? How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to call PHP function on the click of a Button ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP?
[ { "code": null, "e": 24659, "s": 24631, "text": "\n17 Jul, 2019" }, { "code": null, "e": 25149, "s": 24659, "text": "Thread-safe: It is used to ensure that when the shared data structure which is manipulated by different threads are prevented from entering the race condition. Thread-safety is recommended when the web server run multiple threads of execution simultaneously for different requests. In Thread Safety binary can work in a multi-threaded web server context. Thread Safety works by creating a local storage copy in each thread so that the data will not collide with another thread.For example:" }, { "code": null, "e": 25169, "s": 25149, "text": "Apache + LoadModule" }, { "code": null, "e": 25173, "s": 25169, "text": "IIS" }, { "code": null, "e": 25553, "s": 25173, "text": "Non-thread-safe: It does not check the safety of the threads which makes it faster to run but at the same time, it becomes more unstable and crashes very frequently. It refers to a single thread only builds. In non-thread safe version binaries widespread use in the case of interaction with a web server through the FastCGI protocol, by not utilizing multi-threading.For example:" }, { "code": null, "e": 25570, "s": 25553, "text": "Apache + FastCGI" }, { "code": null, "e": 25584, "s": 25570, "text": "IIS + FastCGI" }, { "code": null, "e": 25969, "s": 25584, "text": "So it depends on the way that you want to use PHP. AFAIR running PHP with the fastCGI is the preferable way. If you are unknown which version of PHP is installed in your system then there is an easy way to know that.Check the version of installed PHP Thread safe or Non Thread Safe:Open a phpinfo() and search for the line Thread safety for a thread-safe build you should find enable." }, { "code": null, "e": 26005, "s": 25969, "text": "On Windows:php -i|findstr \"Thread\"\n" }, { "code": null, "e": 26030, "s": 26005, "text": "php -i|findstr \"Thread\"\n" }, { "code": null, "e": 26058, "s": 26030, "text": "On *nix:php -i|grep Thread\n" }, { "code": null, "e": 26078, "s": 26058, "text": "php -i|grep Thread\n" }, { "code": null, "e": 26173, "s": 26078, "text": "In the both cases will display any oneThread Safety => enabled\n//or\nThread Safety => disabled\n" }, { "code": null, "e": 26230, "s": 26173, "text": "Thread Safety => enabled\n//or\nThread Safety => disabled\n" }, { "code": null, "e": 26237, "s": 26230, "text": "Picked" }, { "code": null, "e": 26241, "s": 26237, "text": "PHP" }, { "code": null, "e": 26254, "s": 26241, "text": "PHP Programs" }, { "code": null, "e": 26271, "s": 26254, "text": "Web Technologies" }, { "code": null, "e": 26298, "s": 26271, "text": "Web technologies Questions" }, { "code": null, "e": 26302, "s": 26298, "text": "PHP" }, { "code": null, "e": 26400, "s": 26302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26409, "s": 26400, "text": "Comments" }, { "code": null, "e": 26422, "s": 26409, "text": "Old Comments" }, { "code": null, "e": 26472, "s": 26422, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26512, "s": 26472, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26573, "s": 26512, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 26623, "s": 26573, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 26659, "s": 26623, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 26709, "s": 26659, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26749, "s": 26709, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26801, "s": 26749, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 26862, "s": 26801, "text": "How to Upload Image into Database and Display it using PHP ?" } ]
Icosagonal number - GeeksforGeeks
16 Jul, 2021 Given a number n, the task is to find the nth Icosagonal number. An Icosagonal number is the 20-gon is a twenty-sided polygon. The number derived from the figurative class. There are different pattern series number in this number. The dots are countable, arrange in a specific way of position and create a diagram. All the dots have a common dots points, all others dots are connected to this points and except this common point the dots connected to their i-th dots with their respective successive layer.Examples : Input : 3 Output :57Input :8 Output :512 Formula for nth icosagonal number: C++ Java Python 3 C# PHP Javascript // C++ program to find// nth Icosagonal number#include <bits/stdc++.h>using namespace std; // Function to calculate Icosagonal numberint icosagonal_poly(long int n){ // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2;} // Drivers codeint main(){ long int n = 7; cout << n << "th Icosagonal number :" << icosagonal_poly(n); return 0;} // Java program to find// nth Icosagonal number import java.io.*; class GFG { // Function to calculate Icosagonal number static int icosagonal_poly(int n){ // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2;} // Drivers code public static void main (String[] args) { int n = 7; System.out.print (n + "th Icosagonal number :"); System.out.println(icosagonal_poly(n)); }}// This code is contributed by aj_36 # Python 3 program to find# nth Icosagonal number # Function to calculate# Icosagonal numberdef icosagonal_poly(n) : # Formula for finding # nth Icosagonal number return (18 * n * n - 16 * n) // 2 # Driver Codeif __name__ == '__main__' : n = 7 print(n,"th Icosagonal number : ", icosagonal_poly(n)) # This code is contributed m_kit // C# program to find// nth Icosagonal numberusing System; class GFG{ // Function to calculate// Icosagonal numberstatic int icosagonal_poly(int n){ // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2;} // Driver codestatic public void Main (){ int n = 7; Console.Write(n + "th Icosagonal " + "number :");Console.WriteLine(icosagonal_poly(n));}} // This code is contributed by ajit <?php// PHP program to find// nth Icosagonal number // Function to calculate// Icosagonal numberfunction icosagonal_poly($n){ // Formula for finding // nth Icosagonal number return (18 * $n * $n - 16 * $n) / 2;} // Driver Code$n = 7;echo $n , "th Icosagonal number :", icosagonal_poly($n); // This code is contributed by ajit?> <script> // Javascript program to find nth Icosagonal number // Function to calculate // Icosagonal number function icosagonal_poly(n) { // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2; } let n = 7; document.write(n + "th Icosagonal number :"); document.write(icosagonal_poly(n)); </script> Output : 7th Icosagonal number :385 Time Complexity: O(1)Auxiliary Space: O(1) Reference: https://en.wikipedia.org/wiki/Polygonal_number jit_t mukesh07 manikarora059 number-theory Geometric Mathematical number-theory Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) Equation of circle when three points on the circle are given Convex Hull | Set 2 (Graham Scan) Given n line segments, find if any two segments intersect Closest Pair of Points | O(nlogn) Implementation Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24629, "s": 24601, "text": "\n16 Jul, 2021" }, { "code": null, "e": 25148, "s": 24629, "text": "Given a number n, the task is to find the nth Icosagonal number. An Icosagonal number is the 20-gon is a twenty-sided polygon. The number derived from the figurative class. There are different pattern series number in this number. The dots are countable, arrange in a specific way of position and create a diagram. All the dots have a common dots points, all others dots are connected to this points and except this common point the dots connected to their i-th dots with their respective successive layer.Examples : " }, { "code": null, "e": 25191, "s": 25148, "text": "Input : 3 Output :57Input :8 Output :512 " }, { "code": null, "e": 25230, "s": 25193, "text": "Formula for nth icosagonal number: " }, { "code": null, "e": 25236, "s": 25232, "text": "C++" }, { "code": null, "e": 25241, "s": 25236, "text": "Java" }, { "code": null, "e": 25250, "s": 25241, "text": "Python 3" }, { "code": null, "e": 25253, "s": 25250, "text": "C#" }, { "code": null, "e": 25257, "s": 25253, "text": "PHP" }, { "code": null, "e": 25268, "s": 25257, "text": "Javascript" }, { "code": "// C++ program to find// nth Icosagonal number#include <bits/stdc++.h>using namespace std; // Function to calculate Icosagonal numberint icosagonal_poly(long int n){ // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2;} // Drivers codeint main(){ long int n = 7; cout << n << \"th Icosagonal number :\" << icosagonal_poly(n); return 0;}", "e": 25665, "s": 25268, "text": null }, { "code": "// Java program to find// nth Icosagonal number import java.io.*; class GFG { // Function to calculate Icosagonal number static int icosagonal_poly(int n){ // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2;} // Drivers code public static void main (String[] args) { int n = 7; System.out.print (n + \"th Icosagonal number :\"); System.out.println(icosagonal_poly(n)); }}// This code is contributed by aj_36", "e": 26143, "s": 25665, "text": null }, { "code": "# Python 3 program to find# nth Icosagonal number # Function to calculate# Icosagonal numberdef icosagonal_poly(n) : # Formula for finding # nth Icosagonal number return (18 * n * n - 16 * n) // 2 # Driver Codeif __name__ == '__main__' : n = 7 print(n,\"th Icosagonal number : \", icosagonal_poly(n)) # This code is contributed m_kit", "e": 26524, "s": 26143, "text": null }, { "code": "// C# program to find// nth Icosagonal numberusing System; class GFG{ // Function to calculate// Icosagonal numberstatic int icosagonal_poly(int n){ // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2;} // Driver codestatic public void Main (){ int n = 7; Console.Write(n + \"th Icosagonal \" + \"number :\");Console.WriteLine(icosagonal_poly(n));}} // This code is contributed by ajit", "e": 26982, "s": 26524, "text": null }, { "code": "<?php// PHP program to find// nth Icosagonal number // Function to calculate// Icosagonal numberfunction icosagonal_poly($n){ // Formula for finding // nth Icosagonal number return (18 * $n * $n - 16 * $n) / 2;} // Driver Code$n = 7;echo $n , \"th Icosagonal number :\", icosagonal_poly($n); // This code is contributed by ajit?>", "e": 27344, "s": 26982, "text": null }, { "code": "<script> // Javascript program to find nth Icosagonal number // Function to calculate // Icosagonal number function icosagonal_poly(n) { // Formula for finding // nth Icosagonal number return (18 * n * n - 16 * n) / 2; } let n = 7; document.write(n + \"th Icosagonal number :\"); document.write(icosagonal_poly(n)); </script>", "e": 27733, "s": 27344, "text": null }, { "code": null, "e": 27744, "s": 27733, "text": "Output : " }, { "code": null, "e": 27771, "s": 27744, "text": "7th Icosagonal number :385" }, { "code": null, "e": 27814, "s": 27771, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 27873, "s": 27814, "text": "Reference: https://en.wikipedia.org/wiki/Polygonal_number " }, { "code": null, "e": 27879, "s": 27873, "text": "jit_t" }, { "code": null, "e": 27888, "s": 27879, "text": "mukesh07" }, { "code": null, "e": 27902, "s": 27888, "text": "manikarora059" }, { "code": null, "e": 27916, "s": 27902, "text": "number-theory" }, { "code": null, "e": 27926, "s": 27916, "text": "Geometric" }, { "code": null, "e": 27939, "s": 27926, "text": "Mathematical" }, { "code": null, "e": 27953, "s": 27939, "text": "number-theory" }, { "code": null, "e": 27966, "s": 27953, "text": "Mathematical" }, { "code": null, "e": 27976, "s": 27966, "text": "Geometric" }, { "code": null, "e": 28074, "s": 27976, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28083, "s": 28074, "text": "Comments" }, { "code": null, "e": 28096, "s": 28083, "text": "Old Comments" }, { "code": null, "e": 28149, "s": 28096, "text": "Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping)" }, { "code": null, "e": 28210, "s": 28149, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 28244, "s": 28210, "text": "Convex Hull | Set 2 (Graham Scan)" }, { "code": null, "e": 28302, "s": 28244, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 28351, "s": 28302, "text": "Closest Pair of Points | O(nlogn) Implementation" }, { "code": null, "e": 28381, "s": 28351, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 28441, "s": 28381, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28456, "s": 28441, "text": "C++ Data Types" }, { "code": null, "e": 28499, "s": 28456, "text": "Set in C++ Standard Template Library (STL)" } ]
Predicting customer churns without any labeled data in E-Commerce. | by Tony Liu | Towards Data Science
Do you ever feel confused or even frustrated when you are putting huge amount of effort into engaging your customers but you don’t really know who is going to engage? It all feels collapsed when you are going to spend 10k$ but only to get 5k$ revenue (potentially, to make it even worse). One thing that we found extremely useful in helping you to limit marketing cost is defining and predicting your churned/lapsed customers. With a precise model, you will be able to slash up to 80% of the cost and reduce a huge part of the uncertainty in your campaign strategy. Let’s jump right into today’s topic! First, we want to talk about why it is hard to predict churns. But before that, we need to touch a bit of two different types of 2C (to customer) business models. No1 is where people subscribe and pre-pay which is called subscription model. No2 is where people come and buy without leaving any hint about when they will return for the next order, this is called transactional model. What are some examples of a subscription model? I will pause 30 seconds for you to think of at least 2. My answer would be Apple Music, Spotify, Amazon Prime, New York Times, even your electricity, gas, garbage, sewer, cable is counted towards subscription. What is distinguished about a subscription model is an explicit contract. That means both parties know the money and time. This is a relatively easy case in churn modeling because of that. What are some examples of a transactional model? Every brand that sells tangible products without signed repetition is a transactional model. You will now instantly understand why it is harder to model churns in this case because churn is really invisible and opaque. We are going to talk about churns in a transactional model because we love challenges. But to overcome challenges, we need to be smarter. We know it is gonna be impossible to solve the question in a supervised learning framework. Why? Because as an employee, 99% of the time you find yourself struggling to ask for one more day for a project. When you have a supervised learning problem but you don’t have enough labeled data, usually the right solution is to find another approach rather than self-label 1000, 2000 data for yourself. Time matters. (see my other post about some pitfalls you will definitely fall into as a junior data scientist.) So how do we tackle this problem? We need to turn around to another problem in marketing that is more broadly known and used, Customer Lifetime Value (CLV). What does CLV do? CLV is rather a simple model that can estimate how much you can get from a customer given his/her historical behaviors. What makes it simple and effective is there are only three components in CLV analysis, frequency, recency, and monetary value. Frequency is the number of orders so far. Recency is the number of days between the first order and the last order. Almost everyone has a hard time remembering this definition because recency is related to “recent”, which in nature stands for what is the last time you did something? This is the opposite of the definition of recency. You need to flip it to remember it. Monetary value is the average price of all orders. In our churn model, we don’t care about money so much so we will leave it out for now. Before proceeding, I want to ask the readers to pause for 30 seconds to think about why this model is so useful and popular in marketing. My answers would be a) it makes sense to everyone b) because it makes senses intuitively, it must have captured something in the nature of human behavior. Now it is time to get real about the model. I would defer all the math to the original paper because not everyone here is signed up for that complexity. We care more about usability rather than theories. The basic idea for the model is this: we observe each customer by some time unit (day), each customer has some probability to order at any given day, and each customer has some probability to churn at any given day. We assume that those two probabilities are independent and constant over time. Then we can build some equations to depict transactional behaviors and use math to estimate the probabilities. Using Python, we can make the best of this package for it. First, you need to install this package using this command: pip install lifetimes This package includes 4 models that can serve our churn models and if you are interested, you can check out GammaGammaFitter for a full evaluation of customer lifetimes value modeling journey. I personally recommend using BetaGeoFitter or ModifiedBetaGeoFitter in your initial attempts. The reason is that they are relatively easier to converge and faster to train (this is also one of the important reasons why the original authors developed them instead of the classic ParetoNBDFitter). My experience with BetaGeoBetaBinomFitter told me that this model also takes more time than the other two models to train. We need some training data now, you can get by typing this command in python from lifetimes.datasets import load_cdnow_summarydata = load_cdnow_summary(index_col=[0]) I have some other data sources that I used for this post, but you can expect similar plots, graphs, and numbers generated using this example dataset. Looking at the dataset, we have the following structure: print(data.head())""" frequency recency TID1 2 30.43 38.86""" Frequency is the number of historical orders a certain customer has made. Recency is the number of days between the first discovery and the last purchase. T is the number of days a customer has been discovered. If you use your own dataset, you need to organize your data in the same way. I am going to use ModifiedBetaGeoFitter in my post. mbgf = ModifiedBetaGeoFitter(penalizer_coef=0.001)# penalizer_coef is helpful in converging the trainingmbgf.fit(summary_train['frequency'], summary_train['recency'], summary_train['T'])# display some parameters of the modeldisplay(mbgf)# <lifetimes.ModifiedBetaGeoFitter: fitted with xxx subjects, a: 1.10, alpha: 3.27, b: 0.05, r: 0.85> So the model has been successfully trained and we want to get some visual senses of what it looks like: plot_probability_alive_matrix(mbgf) This graph depicts the relationships between Recency and Frequency against the likelihood of churn. Given a certain frequency, higher recency increases the likelihood of not churn. This makes sense because high recency means there are recent activities of the customer showing that they stick with the brand. Give a certain level of recency, higher frequency increases the likelihood of churn. This might look unintuitive because we often think that the more a customer bought the more likely they like the brand and the less likely they will go away. But it works otherwise if I explain it to you: Let’s say that you run a supermarket and you have some loyal customers that you see at least every other day. Let’s call one of them Bella. She started to come since one year ago and she never missed a single day so you really think that she is loyal. One day you did not see her and the next day you did not see her again, and you start to talk to yourself “is everything going well with her? Am I going to lose her forever?”. Your worries instantly come about when you stop seeing some loyal customers since one or two days ago. As you care a lot about your dedicated people, you wouldn’t care much about someone who has only stopped by once a year. Now think about this likelihood of returning in terms of how much you worry if they will ever come back. Someone loyal stops visiting you is a much stronger signal of churning than you don’t see someone in 7 months but you only expect to see them once a year. It is this change of behavior that causes our worries and we really sense that. Now we fully understand what projection this model can give us and next will be what our real projections are: summary_train['mbgf_lh'] = mbgf.conditional_probability_alive(summary_train['frequency'], summary_train['recency'], summary_train['T'])summary_train['mbgf_lh'].plot.hist() This plot shows the distribution of the likelihood of returning in the future. We notice that most people will be very unlikely to come back (this is mostly true in E-Commerce, most people just buy and leave and never come back). Now I have kept my promise and led you to the end of this journey. I want to leave a homework for you and you can comment below: how can you use this plot to manage your E-Commerce business? Can you make money out of it? If so, how? Some useful resources: Professor Peter Fader talks about Customer Lifetime Value in Wharton. His paper: Counting Your Customers: Who Are They and What Will They Do Next?,
[ { "code": null, "e": 775, "s": 172, "text": "Do you ever feel confused or even frustrated when you are putting huge amount of effort into engaging your customers but you don’t really know who is going to engage? It all feels collapsed when you are going to spend 10k$ but only to get 5k$ revenue (potentially, to make it even worse). One thing that we found extremely useful in helping you to limit marketing cost is defining and predicting your churned/lapsed customers. With a precise model, you will be able to slash up to 80% of the cost and reduce a huge part of the uncertainty in your campaign strategy. Let’s jump right into today’s topic!" }, { "code": null, "e": 1158, "s": 775, "text": "First, we want to talk about why it is hard to predict churns. But before that, we need to touch a bit of two different types of 2C (to customer) business models. No1 is where people subscribe and pre-pay which is called subscription model. No2 is where people come and buy without leaving any hint about when they will return for the next order, this is called transactional model." }, { "code": null, "e": 1605, "s": 1158, "text": "What are some examples of a subscription model? I will pause 30 seconds for you to think of at least 2. My answer would be Apple Music, Spotify, Amazon Prime, New York Times, even your electricity, gas, garbage, sewer, cable is counted towards subscription. What is distinguished about a subscription model is an explicit contract. That means both parties know the money and time. This is a relatively easy case in churn modeling because of that." }, { "code": null, "e": 1873, "s": 1605, "text": "What are some examples of a transactional model? Every brand that sells tangible products without signed repetition is a transactional model. You will now instantly understand why it is harder to model churns in this case because churn is really invisible and opaque." }, { "code": null, "e": 2520, "s": 1873, "text": "We are going to talk about churns in a transactional model because we love challenges. But to overcome challenges, we need to be smarter. We know it is gonna be impossible to solve the question in a supervised learning framework. Why? Because as an employee, 99% of the time you find yourself struggling to ask for one more day for a project. When you have a supervised learning problem but you don’t have enough labeled data, usually the right solution is to find another approach rather than self-label 1000, 2000 data for yourself. Time matters. (see my other post about some pitfalls you will definitely fall into as a junior data scientist.)" }, { "code": null, "e": 2677, "s": 2520, "text": "So how do we tackle this problem? We need to turn around to another problem in marketing that is more broadly known and used, Customer Lifetime Value (CLV)." }, { "code": null, "e": 3451, "s": 2677, "text": "What does CLV do? CLV is rather a simple model that can estimate how much you can get from a customer given his/her historical behaviors. What makes it simple and effective is there are only three components in CLV analysis, frequency, recency, and monetary value. Frequency is the number of orders so far. Recency is the number of days between the first order and the last order. Almost everyone has a hard time remembering this definition because recency is related to “recent”, which in nature stands for what is the last time you did something? This is the opposite of the definition of recency. You need to flip it to remember it. Monetary value is the average price of all orders. In our churn model, we don’t care about money so much so we will leave it out for now." }, { "code": null, "e": 3744, "s": 3451, "text": "Before proceeding, I want to ask the readers to pause for 30 seconds to think about why this model is so useful and popular in marketing. My answers would be a) it makes sense to everyone b) because it makes senses intuitively, it must have captured something in the nature of human behavior." }, { "code": null, "e": 4413, "s": 3744, "text": "Now it is time to get real about the model. I would defer all the math to the original paper because not everyone here is signed up for that complexity. We care more about usability rather than theories. The basic idea for the model is this: we observe each customer by some time unit (day), each customer has some probability to order at any given day, and each customer has some probability to churn at any given day. We assume that those two probabilities are independent and constant over time. Then we can build some equations to depict transactional behaviors and use math to estimate the probabilities. Using Python, we can make the best of this package for it." }, { "code": null, "e": 4473, "s": 4413, "text": "First, you need to install this package using this command:" }, { "code": null, "e": 4495, "s": 4473, "text": "pip install lifetimes" }, { "code": null, "e": 4688, "s": 4495, "text": "This package includes 4 models that can serve our churn models and if you are interested, you can check out GammaGammaFitter for a full evaluation of customer lifetimes value modeling journey." }, { "code": null, "e": 5107, "s": 4688, "text": "I personally recommend using BetaGeoFitter or ModifiedBetaGeoFitter in your initial attempts. The reason is that they are relatively easier to converge and faster to train (this is also one of the important reasons why the original authors developed them instead of the classic ParetoNBDFitter). My experience with BetaGeoBetaBinomFitter told me that this model also takes more time than the other two models to train." }, { "code": null, "e": 5184, "s": 5107, "text": "We need some training data now, you can get by typing this command in python" }, { "code": null, "e": 5274, "s": 5184, "text": "from lifetimes.datasets import load_cdnow_summarydata = load_cdnow_summary(index_col=[0])" }, { "code": null, "e": 5424, "s": 5274, "text": "I have some other data sources that I used for this post, but you can expect similar plots, graphs, and numbers generated using this example dataset." }, { "code": null, "e": 5481, "s": 5424, "text": "Looking at the dataset, we have the following structure:" }, { "code": null, "e": 5573, "s": 5481, "text": "print(data.head())\"\"\" frequency recency TID1 2 30.43 38.86\"\"\"" }, { "code": null, "e": 5861, "s": 5573, "text": "Frequency is the number of historical orders a certain customer has made. Recency is the number of days between the first discovery and the last purchase. T is the number of days a customer has been discovered. If you use your own dataset, you need to organize your data in the same way." }, { "code": null, "e": 5913, "s": 5861, "text": "I am going to use ModifiedBetaGeoFitter in my post." }, { "code": null, "e": 6252, "s": 5913, "text": "mbgf = ModifiedBetaGeoFitter(penalizer_coef=0.001)# penalizer_coef is helpful in converging the trainingmbgf.fit(summary_train['frequency'], summary_train['recency'], summary_train['T'])# display some parameters of the modeldisplay(mbgf)# <lifetimes.ModifiedBetaGeoFitter: fitted with xxx subjects, a: 1.10, alpha: 3.27, b: 0.05, r: 0.85>" }, { "code": null, "e": 6356, "s": 6252, "text": "So the model has been successfully trained and we want to get some visual senses of what it looks like:" }, { "code": null, "e": 6392, "s": 6356, "text": "plot_probability_alive_matrix(mbgf)" }, { "code": null, "e": 6991, "s": 6392, "text": "This graph depicts the relationships between Recency and Frequency against the likelihood of churn. Given a certain frequency, higher recency increases the likelihood of not churn. This makes sense because high recency means there are recent activities of the customer showing that they stick with the brand. Give a certain level of recency, higher frequency increases the likelihood of churn. This might look unintuitive because we often think that the more a customer bought the more likely they like the brand and the less likely they will go away. But it works otherwise if I explain it to you:" }, { "code": null, "e": 7983, "s": 6991, "text": "Let’s say that you run a supermarket and you have some loyal customers that you see at least every other day. Let’s call one of them Bella. She started to come since one year ago and she never missed a single day so you really think that she is loyal. One day you did not see her and the next day you did not see her again, and you start to talk to yourself “is everything going well with her? Am I going to lose her forever?”. Your worries instantly come about when you stop seeing some loyal customers since one or two days ago. As you care a lot about your dedicated people, you wouldn’t care much about someone who has only stopped by once a year. Now think about this likelihood of returning in terms of how much you worry if they will ever come back. Someone loyal stops visiting you is a much stronger signal of churning than you don’t see someone in 7 months but you only expect to see them once a year. It is this change of behavior that causes our worries and we really sense that." }, { "code": null, "e": 8094, "s": 7983, "text": "Now we fully understand what projection this model can give us and next will be what our real projections are:" }, { "code": null, "e": 8266, "s": 8094, "text": "summary_train['mbgf_lh'] = mbgf.conditional_probability_alive(summary_train['frequency'], summary_train['recency'], summary_train['T'])summary_train['mbgf_lh'].plot.hist()" }, { "code": null, "e": 8563, "s": 8266, "text": "This plot shows the distribution of the likelihood of returning in the future. We notice that most people will be very unlikely to come back (this is mostly true in E-Commerce, most people just buy and leave and never come back). Now I have kept my promise and led you to the end of this journey." }, { "code": null, "e": 8729, "s": 8563, "text": "I want to leave a homework for you and you can comment below: how can you use this plot to manage your E-Commerce business? Can you make money out of it? If so, how?" }, { "code": null, "e": 8752, "s": 8729, "text": "Some useful resources:" }, { "code": null, "e": 8822, "s": 8752, "text": "Professor Peter Fader talks about Customer Lifetime Value in Wharton." }, { "code": null, "e": 8833, "s": 8822, "text": "His paper:" } ]
Program to find longest consecutive run of 1 in binary form of a number in C++
Suppose we have a number n, we have to find the length of the longest consecutive run of 1s in its binary representation. So, if the input is like n = 312, then the output will be 3, as 312 is 100111000 in binary and there are 3 consecutive 1s. To solve this, we will follow these steps − ret := 0, len := 0 ret := 0, len := 0 for initialize i := 0, when i < 32, update (increase i by 1), do:if n/2 is odd, then(increase len by 1)Otherwiselen := 0ret := maximum of ret and len for initialize i := 0, when i < 32, update (increase i by 1), do: if n/2 is odd, then(increase len by 1) if n/2 is odd, then (increase len by 1) (increase len by 1) Otherwiselen := 0 Otherwise len := 0 len := 0 ret := maximum of ret and len ret := maximum of ret and len return ret return ret Let us see the following implementation to get better understanding: Source Code (C++) − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int solve(int n) { int ret = 0; int len = 0; for(int i = 0; i < 32; i++){ if((n >> i) & 1){ len++; }else{ len = 0; } ret = max(ret, len); } return ret; } }; main(){ Solution ob; cout << ob.solve(312); } 312 3
[ { "code": null, "e": 1184, "s": 1062, "text": "Suppose we have a number n, we have to find the length of the longest consecutive run of 1s in its binary representation." }, { "code": null, "e": 1307, "s": 1184, "text": "So, if the input is like n = 312, then the output will be 3, as 312 is 100111000 in binary and there are 3 consecutive 1s." }, { "code": null, "e": 1351, "s": 1307, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1370, "s": 1351, "text": "ret := 0, len := 0" }, { "code": null, "e": 1389, "s": 1370, "text": "ret := 0, len := 0" }, { "code": null, "e": 1539, "s": 1389, "text": "for initialize i := 0, when i < 32, update (increase i by 1), do:if n/2 is odd, then(increase len by 1)Otherwiselen := 0ret := maximum of ret and len" }, { "code": null, "e": 1605, "s": 1539, "text": "for initialize i := 0, when i < 32, update (increase i by 1), do:" }, { "code": null, "e": 1644, "s": 1605, "text": "if n/2 is odd, then(increase len by 1)" }, { "code": null, "e": 1664, "s": 1644, "text": "if n/2 is odd, then" }, { "code": null, "e": 1684, "s": 1664, "text": "(increase len by 1)" }, { "code": null, "e": 1704, "s": 1684, "text": "(increase len by 1)" }, { "code": null, "e": 1722, "s": 1704, "text": "Otherwiselen := 0" }, { "code": null, "e": 1732, "s": 1722, "text": "Otherwise" }, { "code": null, "e": 1741, "s": 1732, "text": "len := 0" }, { "code": null, "e": 1750, "s": 1741, "text": "len := 0" }, { "code": null, "e": 1780, "s": 1750, "text": "ret := maximum of ret and len" }, { "code": null, "e": 1810, "s": 1780, "text": "ret := maximum of ret and len" }, { "code": null, "e": 1821, "s": 1810, "text": "return ret" }, { "code": null, "e": 1832, "s": 1821, "text": "return ret" }, { "code": null, "e": 1901, "s": 1832, "text": "Let us see the following implementation to get better understanding:" }, { "code": null, "e": 1921, "s": 1901, "text": "Source Code (C++) −" }, { "code": null, "e": 1932, "s": 1921, "text": " Live Demo" }, { "code": null, "e": 2311, "s": 1932, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int solve(int n) {\n int ret = 0;\n int len = 0;\n for(int i = 0; i < 32; i++){\n if((n >> i) & 1){\n len++;\n }else{\n len = 0;\n }\n ret = max(ret, len);\n }\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << ob.solve(312);\n}" }, { "code": null, "e": 2315, "s": 2311, "text": "312" }, { "code": null, "e": 2317, "s": 2315, "text": "3" } ]
How to connect to Telnet server from Node.js ? - GeeksforGeeks
15 Dec, 2021 In this article, we will see how to connect the Telnet server with Node.js application. Telnet: The telnet is an application protocol over the Transmission Control Protocol (TCP) used on the internet or local area network to provide a bidirectional interactive text-oriented communication facility using a virtual terminal connection. Telnet is used to share a terminal with someone far from us. They provide lots of benefits like virtual terminals and real-time execution on command on the shared terminal. if you have more curious about the telnet refer to this article. NodeJS: Node.js is a runtime environment for javascript, based on the V8 engine the executes javascript on the server-side. So with the help of nodejs we also create an event-driven application,if you have more curious about the telnet refer to this article. Program Approach: Firstly declare the same global variable for further use. Import or require two modules for work with telnet server, first one is the net module the help to manage the network and the second one telnet-stream is used for establishing a connection with a telnet server. Initialize net socket object with IP and port number of the telnet server. Create a telnet client and connect this above socket. After connection, the socket listing some events is as close for if connections are closed and data for collecting data from the telnet server last but not a least do and will event to occur every new step in telnet server create a log. Connect the Telnet server from Node.js Step 1: Run the below command for initializing npm. npm init -y Note: -y is used for all settings are default. Step 2: install some packages. npm install telnet-stream Note: telnet-stream is used to connect the telnet to our node application. Step 3: Create a file with the below code. Here, the filename is index.js Javascript // Some global variable for further usevar TelnetSocket, net, socket, tSocket; // Require the net module for work with networkingnet = require("net"); // Require and create a TelnetSocket Object({ TelnetSocket } = require("telnet-stream")); // Initialize the socket with the our ip and portsocket = net.createConnection(22, "test.rebex.net"); // Connect the socket with telnettSocket = new TelnetSocket(socket); // If the connection are close "close handler"tSocket.on("close", function () { return process.exit();}); // If the connection are on "on handler"tSocket.on("data", function (buffer) { return process.stdout.write(buffer.toString("utf8"));}); // If the connection are occurred somethin "doing handler"tSocket.on("do", function (option) { return tSocket.writeWont(option);}); tSocket.on("will", function (option) { return tSocket.writeDont(option);}); // If the connection are send teh data "data handler"process.stdin.on("data", function (buffer) { return tSocket.write(buffer.toString("utf8"));}); Step 4: Run index.js file. node index.js Output: Finally, you have connected your node application to telnet. adnanirshad158 rajeev0719singh gabaa406 Node.js-process-module NodeJS-Questions Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to build a basic CRUD app with Node.js and ReactJS ? How to connect Node.js with React.js ? Mongoose Populate() Method Express.js req.params Property Mongoose find() Function 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": 24557, "s": 24529, "text": "\n15 Dec, 2021" }, { "code": null, "e": 24645, "s": 24557, "text": "In this article, we will see how to connect the Telnet server with Node.js application." }, { "code": null, "e": 25130, "s": 24645, "text": "Telnet: The telnet is an application protocol over the Transmission Control Protocol (TCP) used on the internet or local area network to provide a bidirectional interactive text-oriented communication facility using a virtual terminal connection. Telnet is used to share a terminal with someone far from us. They provide lots of benefits like virtual terminals and real-time execution on command on the shared terminal. if you have more curious about the telnet refer to this article." }, { "code": null, "e": 25389, "s": 25130, "text": "NodeJS: Node.js is a runtime environment for javascript, based on the V8 engine the executes javascript on the server-side. So with the help of nodejs we also create an event-driven application,if you have more curious about the telnet refer to this article." }, { "code": null, "e": 25407, "s": 25389, "text": "Program Approach:" }, { "code": null, "e": 25465, "s": 25407, "text": "Firstly declare the same global variable for further use." }, { "code": null, "e": 25676, "s": 25465, "text": "Import or require two modules for work with telnet server, first one is the net module the help to manage the network and the second one telnet-stream is used for establishing a connection with a telnet server." }, { "code": null, "e": 25751, "s": 25676, "text": "Initialize net socket object with IP and port number of the telnet server." }, { "code": null, "e": 25805, "s": 25751, "text": "Create a telnet client and connect this above socket." }, { "code": null, "e": 26042, "s": 25805, "text": "After connection, the socket listing some events is as close for if connections are closed and data for collecting data from the telnet server last but not a least do and will event to occur every new step in telnet server create a log." }, { "code": null, "e": 26081, "s": 26042, "text": "Connect the Telnet server from Node.js" }, { "code": null, "e": 26133, "s": 26081, "text": "Step 1: Run the below command for initializing npm." }, { "code": null, "e": 26145, "s": 26133, "text": "npm init -y" }, { "code": null, "e": 26192, "s": 26145, "text": "Note: -y is used for all settings are default." }, { "code": null, "e": 26223, "s": 26192, "text": "Step 2: install some packages." }, { "code": null, "e": 26249, "s": 26223, "text": "npm install telnet-stream" }, { "code": null, "e": 26324, "s": 26249, "text": "Note: telnet-stream is used to connect the telnet to our node application." }, { "code": null, "e": 26398, "s": 26324, "text": "Step 3: Create a file with the below code. Here, the filename is index.js" }, { "code": null, "e": 26409, "s": 26398, "text": "Javascript" }, { "code": "// Some global variable for further usevar TelnetSocket, net, socket, tSocket; // Require the net module for work with networkingnet = require(\"net\"); // Require and create a TelnetSocket Object({ TelnetSocket } = require(\"telnet-stream\")); // Initialize the socket with the our ip and portsocket = net.createConnection(22, \"test.rebex.net\"); // Connect the socket with telnettSocket = new TelnetSocket(socket); // If the connection are close \"close handler\"tSocket.on(\"close\", function () { return process.exit();}); // If the connection are on \"on handler\"tSocket.on(\"data\", function (buffer) { return process.stdout.write(buffer.toString(\"utf8\"));}); // If the connection are occurred somethin \"doing handler\"tSocket.on(\"do\", function (option) { return tSocket.writeWont(option);}); tSocket.on(\"will\", function (option) { return tSocket.writeDont(option);}); // If the connection are send teh data \"data handler\"process.stdin.on(\"data\", function (buffer) { return tSocket.write(buffer.toString(\"utf8\"));});", "e": 27435, "s": 26409, "text": null }, { "code": null, "e": 27462, "s": 27435, "text": "Step 4: Run index.js file." }, { "code": null, "e": 27476, "s": 27462, "text": "node index.js" }, { "code": null, "e": 27545, "s": 27476, "text": "Output: Finally, you have connected your node application to telnet." }, { "code": null, "e": 27560, "s": 27545, "text": "adnanirshad158" }, { "code": null, "e": 27576, "s": 27560, "text": "rajeev0719singh" }, { "code": null, "e": 27585, "s": 27576, "text": "gabaa406" }, { "code": null, "e": 27608, "s": 27585, "text": "Node.js-process-module" }, { "code": null, "e": 27625, "s": 27608, "text": "NodeJS-Questions" }, { "code": null, "e": 27632, "s": 27625, "text": "Picked" }, { "code": null, "e": 27640, "s": 27632, "text": "Node.js" }, { "code": null, "e": 27657, "s": 27640, "text": "Web Technologies" }, { "code": null, "e": 27755, "s": 27657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27764, "s": 27755, "text": "Comments" }, { "code": null, "e": 27777, "s": 27764, "text": "Old Comments" }, { "code": null, "e": 27834, "s": 27777, "text": "How to build a basic CRUD app with Node.js and ReactJS ?" }, { "code": null, "e": 27873, "s": 27834, "text": "How to connect Node.js with React.js ?" }, { "code": null, "e": 27900, "s": 27873, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27931, "s": 27900, "text": "Express.js req.params Property" }, { "code": null, "e": 27956, "s": 27931, "text": "Mongoose find() Function" }, { "code": null, "e": 28012, "s": 27956, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28074, "s": 28012, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28117, "s": 28074, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28167, "s": 28117, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Minimum Cost to Merge Stones in C++
Suppose we have N piles of stones arranged in a row. Here the i-th pile has stones[i] number of stones. A move consists of merging K consecutive piles into one pile, now the cost of this move is equal to the total number of stones in these K number of piles. We have to find the minimum cost to merge all piles of stones into one pile. If there is no such solution then, return -1. So, if the input is like [3,2,4,1] and K = 2, then the output will be 20, this is because, we will start with [3, 2, 4, 1]. Then we merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. After that we merge [4, 1] for a cost of 5, and we are left with [5, 5]. Then we merge [5, 5] for a cost of 10, and we are left with [10]. So, the total cost was 20, and this is the minimum one. To solve this, we will follow these steps − n := size of stones n := size of stones if (n - 1) mod (k - 1) is not equal to 0, then −return -1 if (n - 1) mod (k - 1) is not equal to 0, then − return -1 return -1 Define an array prefix of size n + 1 Define an array prefix of size n + 1 for initialize i := 1, when i <= n, update (increase i by 1), do −prefix[i] := prefix[i - 1] + stones[i - 1] for initialize i := 1, when i <= n, update (increase i by 1), do − prefix[i] := prefix[i - 1] + stones[i - 1] prefix[i] := prefix[i - 1] + stones[i - 1] Define one 2D array dp of size n x n Define one 2D array dp of size n x n for initialize length := k, when length <= n, update (increase length by 1), do −for initialize i := 0, j := length - 1, when j < n, update (increase i by 1), (increase j by 1), do −dp[i, j] := inffor initialize mid := i, when mid < j, update mid := mid + k - 1, do −dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j]if (j - i) mod (k - 1) is same as 0, then −dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i] for initialize length := k, when length <= n, update (increase length by 1), do − for initialize i := 0, j := length - 1, when j < n, update (increase i by 1), (increase j by 1), do − for initialize i := 0, j := length - 1, when j < n, update (increase i by 1), (increase j by 1), do − dp[i, j] := inf dp[i, j] := inf for initialize mid := i, when mid < j, update mid := mid + k - 1, do −dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j] for initialize mid := i, when mid < j, update mid := mid + k - 1, do − dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j] dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j] if (j - i) mod (k - 1) is same as 0, then −dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i] if (j - i) mod (k - 1) is same as 0, then − dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i] dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i] return dp[0, n - 1] return dp[0, n - 1] Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int mergeStones(vector<int>& stones, int k){ int n = stones.size(); if ((n - 1) % (k - 1) != 0) return -1; vector<int> prefix(n + 1); for (int i = 1; i <= n; i++) { prefix[i] = prefix[i - 1] + stones[i - 1]; } vector<vector<int>> dp(n, vector<int>(n)); for (int length = k; length <= n; length++) { for (int i = 0, j = length - 1; j < n; i++, j++) { dp[i][j] = INT_MAX; for (int mid = i; mid < j; mid += k - 1) { dp[i][j] = min(dp[i][j], dp[i][mid] + dp[mid + 1][j]); } if ((j - i) % (k - 1) == 0) { dp[i][j] += prefix[j + 1] - prefix[i]; } } } return dp[0][n - 1]; } }; main(){ Solution ob; vector<int> v = {3,2,4,1}; cout << (ob.mergeStones(v, 2)); } {3,2,4,1}, 2 20
[ { "code": null, "e": 1444, "s": 1062, "text": "Suppose we have N piles of stones arranged in a row. Here the i-th pile has stones[i] number of stones. A move consists of merging K consecutive piles into one pile, now the cost of this move is equal to the total number of stones in these K number of piles. We have to find the minimum cost to merge all piles of stones into one pile. If there is no such solution then, return -1." }, { "code": null, "e": 1833, "s": 1444, "text": "So, if the input is like [3,2,4,1] and K = 2, then the output will be 20, this is because, we will start with [3, 2, 4, 1]. Then we merge [3, 2] for a cost of 5, and we are left with [5, 4, 1]. After that we merge [4, 1] for a cost of 5, and we are left with [5, 5]. Then we merge [5, 5] for a cost of 10, and we are left with [10]. So, the total cost was 20, and this is the minimum one." }, { "code": null, "e": 1877, "s": 1833, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1897, "s": 1877, "text": "n := size of stones" }, { "code": null, "e": 1917, "s": 1897, "text": "n := size of stones" }, { "code": null, "e": 1975, "s": 1917, "text": "if (n - 1) mod (k - 1) is not equal to 0, then −return -1" }, { "code": null, "e": 2024, "s": 1975, "text": "if (n - 1) mod (k - 1) is not equal to 0, then −" }, { "code": null, "e": 2034, "s": 2024, "text": "return -1" }, { "code": null, "e": 2044, "s": 2034, "text": "return -1" }, { "code": null, "e": 2081, "s": 2044, "text": "Define an array prefix of size n + 1" }, { "code": null, "e": 2118, "s": 2081, "text": "Define an array prefix of size n + 1" }, { "code": null, "e": 2227, "s": 2118, "text": "for initialize i := 1, when i <= n, update (increase i by 1), do −prefix[i] := prefix[i - 1] + stones[i - 1]" }, { "code": null, "e": 2294, "s": 2227, "text": "for initialize i := 1, when i <= n, update (increase i by 1), do −" }, { "code": null, "e": 2337, "s": 2294, "text": "prefix[i] := prefix[i - 1] + stones[i - 1]" }, { "code": null, "e": 2380, "s": 2337, "text": "prefix[i] := prefix[i - 1] + stones[i - 1]" }, { "code": null, "e": 2417, "s": 2380, "text": "Define one 2D array dp of size n x n" }, { "code": null, "e": 2454, "s": 2417, "text": "Define one 2D array dp of size n x n" }, { "code": null, "e": 2876, "s": 2454, "text": "for initialize length := k, when length <= n, update (increase length by 1), do −for initialize i := 0, j := length - 1, when j < n, update (increase i by 1), (increase j by 1), do −dp[i, j] := inffor initialize mid := i, when mid < j, update mid := mid + k - 1, do −dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j]if (j - i) mod (k - 1) is same as 0, then −dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i]" }, { "code": null, "e": 2958, "s": 2876, "text": "for initialize length := k, when length <= n, update (increase length by 1), do −" }, { "code": null, "e": 3060, "s": 2958, "text": "for initialize i := 0, j := length - 1, when j < n, update (increase i by 1), (increase j by 1), do −" }, { "code": null, "e": 3162, "s": 3060, "text": "for initialize i := 0, j := length - 1, when j < n, update (increase i by 1), (increase j by 1), do −" }, { "code": null, "e": 3178, "s": 3162, "text": "dp[i, j] := inf" }, { "code": null, "e": 3194, "s": 3178, "text": "dp[i, j] := inf" }, { "code": null, "e": 3328, "s": 3194, "text": "for initialize mid := i, when mid < j, update mid := mid + k - 1, do −dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j]" }, { "code": null, "e": 3399, "s": 3328, "text": "for initialize mid := i, when mid < j, update mid := mid + k - 1, do −" }, { "code": null, "e": 3463, "s": 3399, "text": "dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j]" }, { "code": null, "e": 3527, "s": 3463, "text": "dp[i, j] := minimum of dp[i, j] and dp[i, mid] + dp[mid + 1, j]" }, { "code": null, "e": 3619, "s": 3527, "text": "if (j - i) mod (k - 1) is same as 0, then −dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i]" }, { "code": null, "e": 3663, "s": 3619, "text": "if (j - i) mod (k - 1) is same as 0, then −" }, { "code": null, "e": 3712, "s": 3663, "text": "dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i]" }, { "code": null, "e": 3761, "s": 3712, "text": "dp[i, j] := dp[i, j] + prefix[j + 1] - prefix[i]" }, { "code": null, "e": 3781, "s": 3761, "text": "return dp[0, n - 1]" }, { "code": null, "e": 3801, "s": 3781, "text": "return dp[0, n - 1]" }, { "code": null, "e": 3871, "s": 3801, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3882, "s": 3871, "text": " Live Demo" }, { "code": null, "e": 4818, "s": 3882, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int mergeStones(vector<int>& stones, int k){\n int n = stones.size();\n if ((n - 1) % (k - 1) != 0)\n return -1;\n vector<int> prefix(n + 1);\n for (int i = 1; i <= n; i++) {\n prefix[i] = prefix[i - 1] + stones[i - 1];\n } \n vector<vector<int>> dp(n, vector<int>(n));\n for (int length = k; length <= n; length++) {\n for (int i = 0, j = length - 1; j < n; i++, j++) {\n dp[i][j] = INT_MAX;\n for (int mid = i; mid < j; mid += k - 1) {\n dp[i][j] = min(dp[i][j], dp[i][mid] + dp[mid +\n 1][j]);\n }\n if ((j - i) % (k - 1) == 0) {\n dp[i][j] += prefix[j + 1] - prefix[i];\n }\n }\n }\n return dp[0][n - 1];\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {3,2,4,1};\n cout << (ob.mergeStones(v, 2));\n}" }, { "code": null, "e": 4831, "s": 4818, "text": "{3,2,4,1}, 2" }, { "code": null, "e": 4834, "s": 4831, "text": "20" } ]
How to exponentially scale the Y axis with matplotlib?
To exponentially scale the Y-axis with matplotlib, we can take the following steps − Set the figure size and adjust the padding between and around the subplots. Inintialize a variable dt for steps. Create x and y data points using numpy. Plot the x and y data points using numpy. Set the exponential scale for the Y-axis, using plt.yscale('symlog'). To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True dt = 0.01 x = np.arange(-50.0, 50.0, dt) y = np.arange(0, 100.0, dt) plt.plot(x, y) plt.yscale('symlog') plt.show() It will produce the following output
[ { "code": null, "e": 1147, "s": 1062, "text": "To exponentially scale the Y-axis with matplotlib, we can take the following steps −" }, { "code": null, "e": 1223, "s": 1147, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1260, "s": 1223, "text": "Inintialize a variable dt for steps." }, { "code": null, "e": 1300, "s": 1260, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1342, "s": 1300, "text": "Plot the x and y data points using numpy." }, { "code": null, "e": 1412, "s": 1342, "text": "Set the exponential scale for the Y-axis, using plt.yscale('symlog')." }, { "code": null, "e": 1454, "s": 1412, "text": "To display the figure, use show() method." }, { "code": null, "e": 1713, "s": 1454, "text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndt = 0.01\n\nx = np.arange(-50.0, 50.0, dt)\ny = np.arange(0, 100.0, dt)\n\nplt.plot(x, y)\nplt.yscale('symlog')\n\nplt.show()" }, { "code": null, "e": 1750, "s": 1713, "text": "It will produce the following output" } ]
How to Hide an HTML Element by Class using JavaScript ? - GeeksforGeeks
02 Mar, 2020 Suppose you have given an HTML document and the task is to hide an HTML element by its class name with the help of JavaScript. There are two approaches to explain with the proper example. Approach 1: In this approach, getElementsByClassName() selector is used to select elements of specific class. Indexing is used to get the element at respective index. To get the access to the CSS visibility property, We can use DOM style.visibility on the elements to set it to hidden value. Example:<!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class="outer"> <div class="child1">Child 1</div> <div class="child1">Child 1</div> <div class="child2">Child 2</div> <div class="child2">Child 2</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"> </p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.getElementsByClassName('child1')[0]. style.visibility = 'hidden'; down.innerHTML = "Element is hidden"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class="outer"> <div class="child1">Child 1</div> <div class="child1">Child 1</div> <div class="child2">Child 2</div> <div class="child2">Child 2</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"> </p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.getElementsByClassName('child1')[0]. style.visibility = 'hidden'; down.innerHTML = "Element is hidden"; } </script></body> </html> Output: Approach 2: In this approach, querySelectorAll() selector is used to select elements of specific class. Indexing is used to get the element at respective index. To get the access to the CSS visibility property, We can use DOM style.visibility on the elements to set it to hidden value. Example:<!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class="outer"> <div class="child1">Child 1</div> <div class="child1">Child 1</div> <div class="child2">Child 2</div> <div class="child2">Child 2</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.querySelectorAll('.child1')[0]. style.visibility = 'hidden'; down.innerHTML = "Element is hidden"; } </script></body> </html> <!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class="outer"> <div class="child1">Child 1</div> <div class="child1">Child 1</div> <div class="child2">Child 2</div> <div class="child2">Child 2</div> </div> <br> <button onClick="GFG_Fun()"> click here </button> <p id="geeks"></p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.querySelectorAll('.child1')[0]. style.visibility = 'hidden'; down.innerHTML = "Element is hidden"; } </script></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to Upload Image into Database and Display it using PHP ? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? HTML Cheat Sheet - A Basic Guide to HTML REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26593, "s": 26565, "text": "\n02 Mar, 2020" }, { "code": null, "e": 26781, "s": 26593, "text": "Suppose you have given an HTML document and the task is to hide an HTML element by its class name with the help of JavaScript. There are two approaches to explain with the proper example." }, { "code": null, "e": 27073, "s": 26781, "text": "Approach 1: In this approach, getElementsByClassName() selector is used to select elements of specific class. Indexing is used to get the element at respective index. To get the access to the CSS visibility property, We can use DOM style.visibility on the elements to set it to hidden value." }, { "code": null, "e": 28265, "s": 27073, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class=\"outer\"> <div class=\"child1\">Child 1</div> <div class=\"child1\">Child 1</div> <div class=\"child2\">Child 2</div> <div class=\"child2\">Child 2</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"> </p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.getElementsByClassName('child1')[0]. style.visibility = 'hidden'; down.innerHTML = \"Element is hidden\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class=\"outer\"> <div class=\"child1\">Child 1</div> <div class=\"child1\">Child 1</div> <div class=\"child2\">Child 2</div> <div class=\"child2\">Child 2</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"> </p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.getElementsByClassName('child1')[0]. style.visibility = 'hidden'; down.innerHTML = \"Element is hidden\"; } </script></body> </html>", "e": 29449, "s": 28265, "text": null }, { "code": null, "e": 29457, "s": 29449, "text": "Output:" }, { "code": null, "e": 29743, "s": 29457, "text": "Approach 2: In this approach, querySelectorAll() selector is used to select elements of specific class. Indexing is used to get the element at respective index. To get the access to the CSS visibility property, We can use DOM style.visibility on the elements to set it to hidden value." }, { "code": null, "e": 30928, "s": 29743, "text": "Example:<!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class=\"outer\"> <div class=\"child1\">Child 1</div> <div class=\"child1\">Child 1</div> <div class=\"child2\">Child 2</div> <div class=\"child2\">Child 2</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.querySelectorAll('.child1')[0]. style.visibility = 'hidden'; down.innerHTML = \"Element is hidden\"; } </script></body> </html>" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to hide an HTML element by class in JavaScript </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <style> body { text-align: center; } h1 { color: green; } .geeks { color: green; font-size: 24px; font-weight: bold; } </style></head> <body> <h1> GeeksforGeeks </h1> <b> Click on button to hide the element by class name </b> <br> <div class=\"outer\"> <div class=\"child1\">Child 1</div> <div class=\"child1\">Child 1</div> <div class=\"child2\">Child 2</div> <div class=\"child2\">Child 2</div> </div> <br> <button onClick=\"GFG_Fun()\"> click here </button> <p id=\"geeks\"></p> <script> var down = document.getElementById('GFG_DOWN'); function GFG_Fun() { document.querySelectorAll('.child1')[0]. style.visibility = 'hidden'; down.innerHTML = \"Element is hidden\"; } </script></body> </html>", "e": 32105, "s": 30928, "text": null }, { "code": null, "e": 32113, "s": 32105, "text": "Output:" }, { "code": null, "e": 32122, "s": 32113, "text": "CSS-Misc" }, { "code": null, "e": 32132, "s": 32122, "text": "HTML-Misc" }, { "code": null, "e": 32148, "s": 32132, "text": "JavaScript-Misc" }, { "code": null, "e": 32152, "s": 32148, "text": "CSS" }, { "code": null, "e": 32157, "s": 32152, "text": "HTML" }, { "code": null, "e": 32168, "s": 32157, "text": "JavaScript" }, { "code": null, "e": 32185, "s": 32168, "text": "Web Technologies" }, { "code": null, "e": 32212, "s": 32185, "text": "Web technologies Questions" }, { "code": null, "e": 32217, "s": 32212, "text": "HTML" }, { "code": null, "e": 32315, "s": 32217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32363, "s": 32315, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32400, "s": 32363, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 32464, "s": 32400, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 32503, "s": 32464, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 32564, "s": 32503, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 32624, "s": 32564, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 32672, "s": 32624, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32713, "s": 32672, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 32737, "s": 32713, "text": "REST API (Introduction)" } ]
Count the total number of elements in the List in C#?
To count the total number of elements in the List, the code is as follows − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(String[] args) { List<String> list = new List<String>(); list.Add("One"); list.Add("Two"); list.Add("Three"); list.Add("Four"); list.Add("Five"); Console.WriteLine("Elements in List1..."); foreach (string res in list) { Console.WriteLine(res); } Console.WriteLine("\nCount of elements in list = "+list.Count); list.Clear(); Console.WriteLine("\nCount of elements in list (updated) = "+list.Count); } } This will produce the following output − Elements in List1... One Two Three Four Five Count of elements in list = 5 Count of elements in list (updated) = 0 Let us now see another example − Live Demo using System; using System.Collections.Generic; public class Demo { public static void Main(String[] args) { List<String> list = new List<String>(); list.Add("100"); list.Add("200"); list.Add("300"); list.Add("400"); list.Add("500"); Console.WriteLine("Count of elements in the list = "+list.Count); Console.WriteLine("Enumerator iterates through the list elements..."); List<string>.Enumerator demoEnum = list.GetEnumerator(); while (demoEnum.MoveNext()) { string res = demoEnum.Current; Console.WriteLine(res); } list.Add("600"); list.Add("700"); Console.WriteLine("Count of elements in the list (updated) = "+list.Count); } } This will produce the following output − Count of elements in the list = 5 Enumerator iterates through the list elements... 100 200 300 400 500 Count of elements in the list (updated) = 7
[ { "code": null, "e": 1138, "s": 1062, "text": "To count the total number of elements in the List, the code is as follows −" }, { "code": null, "e": 1149, "s": 1138, "text": " Live Demo" }, { "code": null, "e": 1730, "s": 1149, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(String[] args) {\n List<String> list = new List<String>();\n list.Add(\"One\");\n list.Add(\"Two\");\n list.Add(\"Three\");\n list.Add(\"Four\");\n list.Add(\"Five\");\n Console.WriteLine(\"Elements in List1...\");\n foreach (string res in list) {\n Console.WriteLine(res);\n }\n Console.WriteLine(\"\\nCount of elements in list = \"+list.Count);\n list.Clear();\n Console.WriteLine(\"\\nCount of elements in list (updated) = \"+list.Count);\n }\n}" }, { "code": null, "e": 1771, "s": 1730, "text": "This will produce the following output −" }, { "code": null, "e": 1886, "s": 1771, "text": "Elements in List1...\nOne\nTwo\nThree\nFour\nFive\nCount of elements in list = 5\nCount of elements in list (updated) = 0" }, { "code": null, "e": 1919, "s": 1886, "text": "Let us now see another example −" }, { "code": null, "e": 1930, "s": 1919, "text": " Live Demo" }, { "code": null, "e": 2669, "s": 1930, "text": "using System;\nusing System.Collections.Generic;\npublic class Demo {\n public static void Main(String[] args) {\n List<String> list = new List<String>();\n list.Add(\"100\");\n list.Add(\"200\");\n list.Add(\"300\");\n list.Add(\"400\");\n list.Add(\"500\");\n Console.WriteLine(\"Count of elements in the list = \"+list.Count); \n Console.WriteLine(\"Enumerator iterates through the list elements...\");\n List<string>.Enumerator demoEnum = list.GetEnumerator();\n while (demoEnum.MoveNext()) {\n string res = demoEnum.Current;\n Console.WriteLine(res);\n }\n list.Add(\"600\");\n list.Add(\"700\");\n Console.WriteLine(\"Count of elements in the list (updated) = \"+list.Count);\n }\n}" }, { "code": null, "e": 2710, "s": 2669, "text": "This will produce the following output −" }, { "code": null, "e": 2857, "s": 2710, "text": "Count of elements in the list = 5\nEnumerator iterates through the list elements...\n100\n200\n300\n400\n500\nCount of elements in the list (updated) = 7" } ]
Find nth term of the Dragon Curve Sequence - GeeksforGeeks
26 Apr, 2021 Dragon Curve Sequence is an infinite binary sequence of 0s and 1s. The first term of the sequence is 1. From the next term, we alternately insert 1 and 0 between each element of the previous term. To understand better refer the following explanations: 1 (starts with 1) “1” 1 “0” 1 and 0 are inserted alternately to the left and right of the previous term. Here the number in the double quotes represents the newly added elements.So the second term becomes 1 1 0 “1” 1 “0” 1 “1” 0 “0” So the third term becomes 1 1 0 1 1 0 0 “1” 1 “0” 1 “1” 0 “0” 1 “1” 1 “0” 0 “1” 0 “0” The fourth term becomes 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 This is also popularly known as the regular paperfolding sequence. Given a natural number n. The task is to find the nth string formed by Dragon Curve sequence of length .Examples: Input: n = 4 Output: 110110011100100 Explanation: We get 1 as the first term, "110" as the second term, "1101100" as the third term , And hence our fourth term will be "110110011100100" Input: n = 3 Output: 1101100 Approach: Start with the first term 1. Then add 1 and 0 alternately after each element of the preceding term. The new term obtained becomes the current term. Repeat the process in a loop from 1 to n to generate each term and finally the nth term.Below is the implementation of above idea: C++ Java Python C# PHP Javascript // CPP code to find nth term// of the Dragon Curve Sequence#include <bits/stdc++.h>using namespace std; // function to generate the nth termstring Dragon_Curve_Sequence(int n) { // first term string s = "1"; // generating each term of the sequence for (int i = 2; i <= n; i++) { string temp = "1"; char prev = '1', zero = '0', one = '1'; // loop to generate the ith term for (int j = 0; j < s.length(); j++) { // add character from the // original string temp += s[j]; // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s;} // Driver programint main(){ // Taking inputs int n = 4; // generate nth term of dragon curve sequence string s = Dragon_Curve_Sequence(n); // Printing output cout << s << "\n";} // Java code to find nth term// of the Dragon Curve Sequenceimport java.util.*; class solution{ // function to generate the nth termstatic String Dragon_Curve_Sequence(int n) { // first term String s = "1"; // generating each term of the sequence for (int i = 2; i <= n; i++) { String temp = "1"; char prev = '1', zero = '0', one = '1'; // loop to generate the ith term for (int j = 0; j < s.length(); j++) { // add character from the // original string temp += s.charAt(j); // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s;} // Driver programpublic static void main(String args[]){ // Taking inputs int n = 4; // generate nth term of dragon curve sequence String s = Dragon_Curve_Sequence(n); // Printing output System.out.println(s);} } //This code is contributed by //Surendra_Gangwar # Python code to find nth term# of the Dragon Curve Sequence # function to generate # the nth termdef Dragon_Curve_Sequence(n): # first term s = "1" # generating each term # of the sequence for i in range(2, n + 1): temp = "1" prev = '1' zero = '0' one = '1' # loop to generate the ith term for j in range(len(s)): # add character from the # original string temp += s[j] # add alternate 0 and # 1 in between if (prev == '0'): # if previous added term # was '0' then add '1' temp += one # now current term becomes # previous term prev = one else: # if previous added term # was '1', then add '0' temp += zero # now current term becomes # previous term prev = zero # s becomes the ith term # of the sequence s = temp return s # Driver Coden = 4 # generate nth term of # dragon curve sequences = Dragon_Curve_Sequence(n) # Printing outputprint(s) # This code is contributed by# Sanjit_Prasad // C# code to find nth term // of the Dragon Curve Sequence using System; class GFG{ // function to generate the nth term static String Dragon_Curve_Sequence(int n) { // first term String s = "1"; // generating each term of the sequence for (int i = 2; i <= n; i++) { String temp = "1"; char prev = '1', zero = '0', one = '1'; // loop to generate the ith term for (int j = 0; j < s.Length; j++) { // add character from the // original string temp += s[j]; // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s; } // Driver Codepublic static void Main() { // Taking inputs int n = 4; // generate nth term of dragon // curve sequence String s = Dragon_Curve_Sequence(n); // Printing output Console.WriteLine(s); } } // This code is contributed by Rajput-Ji <?php// PHP code to find nth term// of the Dragon Curve Sequence // function to generate the nth termfunction Dragon_Curve_Sequence($n) { // first term $s = "1"; // generating each term of the sequence for ($i = 2; $i <= $n; $i++) { $temp = "1"; $prev = '1'; $zero = '0'; $one = '1'; // loop to generate the ith term for ($j = 0; $j < strlen($s); $j++) { // add character from the // original string $temp .= $s[$j]; // add alternate 0 and 1 in between if ($prev == '0') { // if previous added term // was '0' then add '1' $temp .= $one; // now current term becomes // previous term $prev = $one; } else { // if previous added term // was '1', then add '0' $temp .= $zero; // now current term becomes // previous term $prev = $zero; } } // s becomes the ith term of the sequence $s = $temp; } return $s;} // Driver code // Taking inputs $n = 4; // generate nth term of dragon curve sequence $s = Dragon_Curve_Sequence($n); // Printing output echo $s."\n"; // This code is contributed by mits?> <script>// Javascript code to find nth term// of the Dragon Curve Sequence // function to generate the nth termfunction Dragon_Curve_Sequence(n) { // first term let s = "1"; // generating each term of the sequence for (let i = 2; i <= n; i++) { let temp = "1"; let prev = '1'; let zero = '0'; let one = '1'; // loop to generate the ith term for (let j = 0; j < s.length; j++) { // add character from the // original string temp = temp + s[j]; // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s;} // Driver code // Taking inputs let n = 4; // generate nth term of dragon curve sequence let s = Dragon_Curve_Sequence(n); // Printing output document.write(s + "<br>"); // This code is contributed by gfgking</script> Output: 110110011100100 Sanjit_Prasad SURENDRA_GANGWAR Rajput-Ji Mithun Kumar gfgking binary-string Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Singular Value Decomposition (SVD) Check if a number is Palindrome Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not
[ { "code": null, "e": 26071, "s": 26043, "text": "\n26 Apr, 2021" }, { "code": null, "e": 26324, "s": 26071, "text": "Dragon Curve Sequence is an infinite binary sequence of 0s and 1s. The first term of the sequence is 1. From the next term, we alternately insert 1 and 0 between each element of the previous term. To understand better refer the following explanations: " }, { "code": null, "e": 26344, "s": 26324, "text": "1 (starts with 1) " }, { "code": null, "e": 26537, "s": 26344, "text": "“1” 1 “0” 1 and 0 are inserted alternately to the left and right of the previous term. Here the number in the double quotes represents the newly added elements.So the second term becomes 1 1 0" }, { "code": null, "e": 26601, "s": 26537, "text": "“1” 1 “0” 1 “1” 0 “0” So the third term becomes 1 1 0 1 1 0 0 " }, { "code": null, "e": 26703, "s": 26601, "text": "“1” 1 “0” 1 “1” 0 “0” 1 “1” 1 “0” 0 “1” 0 “0” The fourth term becomes 1 1 0 1 1 0 0 1 1 1 0 0 1 0 0 " }, { "code": null, "e": 26885, "s": 26703, "text": "This is also popularly known as the regular paperfolding sequence. Given a natural number n. The task is to find the nth string formed by Dragon Curve sequence of length .Examples: " }, { "code": null, "e": 27102, "s": 26885, "text": "Input: n = 4\nOutput: 110110011100100\nExplanation:\nWe get 1 as the first term, \n\"110\" as the second term,\n\"1101100\" as the third term ,\nAnd hence our fourth term will be\n\"110110011100100\"\n\nInput: n = 3\nOutput: 1101100" }, { "code": null, "e": 27394, "s": 27104, "text": "Approach: Start with the first term 1. Then add 1 and 0 alternately after each element of the preceding term. The new term obtained becomes the current term. Repeat the process in a loop from 1 to n to generate each term and finally the nth term.Below is the implementation of above idea: " }, { "code": null, "e": 27398, "s": 27394, "text": "C++" }, { "code": null, "e": 27403, "s": 27398, "text": "Java" }, { "code": null, "e": 27410, "s": 27403, "text": "Python" }, { "code": null, "e": 27413, "s": 27410, "text": "C#" }, { "code": null, "e": 27417, "s": 27413, "text": "PHP" }, { "code": null, "e": 27428, "s": 27417, "text": "Javascript" }, { "code": "// CPP code to find nth term// of the Dragon Curve Sequence#include <bits/stdc++.h>using namespace std; // function to generate the nth termstring Dragon_Curve_Sequence(int n) { // first term string s = \"1\"; // generating each term of the sequence for (int i = 2; i <= n; i++) { string temp = \"1\"; char prev = '1', zero = '0', one = '1'; // loop to generate the ith term for (int j = 0; j < s.length(); j++) { // add character from the // original string temp += s[j]; // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s;} // Driver programint main(){ // Taking inputs int n = 4; // generate nth term of dragon curve sequence string s = Dragon_Curve_Sequence(n); // Printing output cout << s << \"\\n\";}", "e": 28873, "s": 27428, "text": null }, { "code": "// Java code to find nth term// of the Dragon Curve Sequenceimport java.util.*; class solution{ // function to generate the nth termstatic String Dragon_Curve_Sequence(int n) { // first term String s = \"1\"; // generating each term of the sequence for (int i = 2; i <= n; i++) { String temp = \"1\"; char prev = '1', zero = '0', one = '1'; // loop to generate the ith term for (int j = 0; j < s.length(); j++) { // add character from the // original string temp += s.charAt(j); // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s;} // Driver programpublic static void main(String args[]){ // Taking inputs int n = 4; // generate nth term of dragon curve sequence String s = Dragon_Curve_Sequence(n); // Printing output System.out.println(s);} } //This code is contributed by //Surendra_Gangwar", "e": 30410, "s": 28873, "text": null }, { "code": "# Python code to find nth term# of the Dragon Curve Sequence # function to generate # the nth termdef Dragon_Curve_Sequence(n): # first term s = \"1\" # generating each term # of the sequence for i in range(2, n + 1): temp = \"1\" prev = '1' zero = '0' one = '1' # loop to generate the ith term for j in range(len(s)): # add character from the # original string temp += s[j] # add alternate 0 and # 1 in between if (prev == '0'): # if previous added term # was '0' then add '1' temp += one # now current term becomes # previous term prev = one else: # if previous added term # was '1', then add '0' temp += zero # now current term becomes # previous term prev = zero # s becomes the ith term # of the sequence s = temp return s # Driver Coden = 4 # generate nth term of # dragon curve sequences = Dragon_Curve_Sequence(n) # Printing outputprint(s) # This code is contributed by# Sanjit_Prasad", "e": 31715, "s": 30410, "text": null }, { "code": "// C# code to find nth term // of the Dragon Curve Sequence using System; class GFG{ // function to generate the nth term static String Dragon_Curve_Sequence(int n) { // first term String s = \"1\"; // generating each term of the sequence for (int i = 2; i <= n; i++) { String temp = \"1\"; char prev = '1', zero = '0', one = '1'; // loop to generate the ith term for (int j = 0; j < s.Length; j++) { // add character from the // original string temp += s[j]; // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s; } // Driver Codepublic static void Main() { // Taking inputs int n = 4; // generate nth term of dragon // curve sequence String s = Dragon_Curve_Sequence(n); // Printing output Console.WriteLine(s); } } // This code is contributed by Rajput-Ji", "e": 33243, "s": 31715, "text": null }, { "code": "<?php// PHP code to find nth term// of the Dragon Curve Sequence // function to generate the nth termfunction Dragon_Curve_Sequence($n) { // first term $s = \"1\"; // generating each term of the sequence for ($i = 2; $i <= $n; $i++) { $temp = \"1\"; $prev = '1'; $zero = '0'; $one = '1'; // loop to generate the ith term for ($j = 0; $j < strlen($s); $j++) { // add character from the // original string $temp .= $s[$j]; // add alternate 0 and 1 in between if ($prev == '0') { // if previous added term // was '0' then add '1' $temp .= $one; // now current term becomes // previous term $prev = $one; } else { // if previous added term // was '1', then add '0' $temp .= $zero; // now current term becomes // previous term $prev = $zero; } } // s becomes the ith term of the sequence $s = $temp; } return $s;} // Driver code // Taking inputs $n = 4; // generate nth term of dragon curve sequence $s = Dragon_Curve_Sequence($n); // Printing output echo $s.\"\\n\"; // This code is contributed by mits?>", "e": 34674, "s": 33243, "text": null }, { "code": "<script>// Javascript code to find nth term// of the Dragon Curve Sequence // function to generate the nth termfunction Dragon_Curve_Sequence(n) { // first term let s = \"1\"; // generating each term of the sequence for (let i = 2; i <= n; i++) { let temp = \"1\"; let prev = '1'; let zero = '0'; let one = '1'; // loop to generate the ith term for (let j = 0; j < s.length; j++) { // add character from the // original string temp = temp + s[j]; // add alternate 0 and 1 in between if (prev == '0') { // if previous added term // was '0' then add '1' temp += one; // now current term becomes // previous term prev = one; } else { // if previous added term // was '1', then add '0' temp += zero; // now current term becomes // previous term prev = zero; } } // s becomes the ith term of the sequence s = temp; } return s;} // Driver code // Taking inputs let n = 4; // generate nth term of dragon curve sequence let s = Dragon_Curve_Sequence(n); // Printing output document.write(s + \"<br>\"); // This code is contributed by gfgking</script>", "e": 36148, "s": 34674, "text": null }, { "code": null, "e": 36158, "s": 36148, "text": "Output: " }, { "code": null, "e": 36174, "s": 36158, "text": "110110011100100" }, { "code": null, "e": 36190, "s": 36176, "text": "Sanjit_Prasad" }, { "code": null, "e": 36207, "s": 36190, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 36217, "s": 36207, "text": "Rajput-Ji" }, { "code": null, "e": 36230, "s": 36217, "text": "Mithun Kumar" }, { "code": null, "e": 36238, "s": 36230, "text": "gfgking" }, { "code": null, "e": 36252, "s": 36238, "text": "binary-string" }, { "code": null, "e": 36265, "s": 36252, "text": "Mathematical" }, { "code": null, "e": 36273, "s": 36265, "text": "Strings" }, { "code": null, "e": 36281, "s": 36273, "text": "Strings" }, { "code": null, "e": 36294, "s": 36281, "text": "Mathematical" }, { "code": null, "e": 36392, "s": 36294, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36436, "s": 36392, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 36467, "s": 36436, "text": "Modular multiplicative inverse" }, { "code": null, "e": 36492, "s": 36467, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 36527, "s": 36492, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 36559, "s": 36527, "text": "Check if a number is Palindrome" }, { "code": null, "e": 36605, "s": 36559, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 36630, "s": 36605, "text": "Reverse a string in Java" }, { "code": null, "e": 36664, "s": 36630, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 36739, "s": 36664, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
QlikView - Mapping Tables
Mapping table is a table, which is created to map the column values between two tables. It is also called a Lookup table, which is only used to look for a related value from some other table. Let us consider the following input data file, which represents the sales values in different regions. ProductID,ProductCategory,Region,SaleAmount 1,Outdoor Recreation,Europe,4579 2,Clothing,Europe,4125 3,Costumes & Accessories,South Asia,6521 4,Athletics,South Asia,4125 5,Personal Care,Australia,5124 6,Arts & Entertainment,North AMerica,1245 7,Hardware,South America,456 8,Home & Garden,South America,241 9,Food,South Asia,1247 10,Home & Garden,South Asia,5462 11,Office Supplies,Australia,577 The following data represents the countries and their regions. Region,Country Europe,Germany Europe,Italy South Asia,Singapore South Asia,Korea North AMerica,USA South America,Brazil South America,Peru South Asia,China South Asia,Sri Lanka The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and ess Control+R to load the data into the QlikView's memory. Let us create two table boxes for each of the above table as shown below. Here we cannot get the value of country in the Sales region report. The following script produces the mapping table, which maps the region value from the sales table with the country value from the MapCountryRegion table. On completing the above steps and creating a Table box to view the data, we get the country columns along with other columns from Sales table. 70 Lectures 5 hours Arthur Fong Print Add Notes Bookmark this page
[ { "code": null, "e": 3112, "s": 2920, "text": "Mapping table is a table, which is created to map the column values between two tables. It is also called a Lookup table, which is only used to look for a related value from some other table." }, { "code": null, "e": 3215, "s": 3112, "text": "Let us consider the following input data file, which represents the sales values in different regions." }, { "code": null, "e": 3610, "s": 3215, "text": "ProductID,ProductCategory,Region,SaleAmount\n1,Outdoor Recreation,Europe,4579\n2,Clothing,Europe,4125\n3,Costumes & Accessories,South Asia,6521\n4,Athletics,South Asia,4125\n5,Personal Care,Australia,5124\n6,Arts & Entertainment,North AMerica,1245\n7,Hardware,South America,456\n8,Home & Garden,South America,241\n9,Food,South Asia,1247\n10,Home & Garden,South Asia,5462\n11,Office Supplies,Australia,577\n" }, { "code": null, "e": 3673, "s": 3610, "text": "The following data represents the countries and their regions." }, { "code": null, "e": 3851, "s": 3673, "text": "Region,Country\nEurope,Germany\nEurope,Italy\nSouth Asia,Singapore\nSouth Asia,Korea\nNorth AMerica,USA\nSouth America,Brazil\nSouth America,Peru\nSouth Asia,China\nSouth Asia,Sri Lanka\n" }, { "code": null, "e": 4167, "s": 3851, "text": "The above data is loaded to QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and ess Control+R to load the data into the QlikView's memory." }, { "code": null, "e": 4309, "s": 4167, "text": "Let us create two table boxes for each of the above table as shown below. Here we cannot get the value of country in the Sales region report." }, { "code": null, "e": 4463, "s": 4309, "text": "The following script produces the mapping table, which maps the region value from the sales table with the country value from the MapCountryRegion table." }, { "code": null, "e": 4606, "s": 4463, "text": "On completing the above steps and creating a Table box to view the data, we get the country columns along with other columns from Sales table." }, { "code": null, "e": 4639, "s": 4606, "text": "\n 70 Lectures \n 5 hours \n" }, { "code": null, "e": 4652, "s": 4639, "text": " Arthur Fong" }, { "code": null, "e": 4659, "s": 4652, "text": " Print" }, { "code": null, "e": 4670, "s": 4659, "text": " Add Notes" } ]
Mood & Modality and Dialogue Sentiment | Towards Data Science
In this article, we will see how verbal functional categories used in customer dialogue text and how these categories contribute to the semantics, especially the text sentiment. Verb phrase in a sentence sometimes can carry huge semantics, sometimes hint the sentiment only by itself even though if one does not see the rest of the context words, hence contribute to sentiment analysis models as important features. For example, cross all the not-included-in-any-VP words from the following customer reviews: The product isn't working properly. I didn't like this product.I'm not satisfied with the product quality at all. In order to charge meaning to the sentence, many languages like the verb to admit different inflections such as tense and person. Moreover most of the time we want to express our feeling and opinions about how the proposed action by the verb happened: are we sure, did we see the action by our own eyes, do we think it’s likely or unlikely? This is more of a semantic capability, thus one usually needs more than inflecting the verb, more than grammatical constructions. Function of the verb is a broad topic, but I will explain some basic concepts before the statistical parts. You can skip to the next section if you have this background. Tense is a grammatical realization of time by means of verbal inflection. English has 2 tenses: past and present. Future is not a tense not having an inflectional marker, but it is rather a time . Future time is formed either by will or with adverbs such as tomorrow , 8 o'clock or next week/month etc. As you see tense is a grammatical concept and time is rather a semantic concept. Another concept is aspect, a grammatical category which reflects the action given by the verb happened with respect to time. English has two aspects: action complete: perfective has moved, had movedaction in progress: progressive is moving, was moving One can summarize tense and aspect as follows: Voice in English is either passive or active, as we learnt in high school. Passive voice has further semantic subcategories, but in this article, we will stay at high school level grammar 😉 Mood is a grammatical category indicating whether a verb expresses a fact (indicative mood) or conditionality (subjunctive mood). Some examples are: Sun rises at 6 o'clock here. indicativeIt is important the manager be informed of the changes subjunctive Mood is grammatical and associates to two semantic notions: modality and illocution. Illocution of a sentence can be thought as sentence type : Go there! imperativeDo you want to go there? interrogativeGod save the queen! optativeI will see it. declarative Modality is a semantic notion that is related to speaker’s opinion and belief about the event’s believability, obligatoriness, desirability, or reality. Modality in English can be achieved by modal verbs (will/would, can/could, may/might, shall/should, must), modal adverbs (maybe, perhaps, possibly, probably), some subordinate clauses including (wish, it’s time,possible, probable, chance, possibility ), some modal nouns (decree, demand,necessity, requirement, request) or some modal adjectives (advisable, crucial, imperative, likely, necessary, probable, possible). I would love you if things were different irrealisYou may go permissionI may come with you too possibilityI might come with you too possibilityI must go obligationHe must be earning good money necessityI can ride a bike abilityI can come with you too possibilityIt is possible that we might see big changes around us. possibilityIt might be the truth doubtI'm sure they'll come confidenceLights are on, so he must be in the office evidentiality From now on, we will see the different verbal features that customers use to interact with conversational agents and how those usages lead to different semantics. Let’s begin with our Chris, our voice assistant in your car and see some typical user utterances in automotive conversational AI. Chris datasets include many imperative sentences: navigatenavigate homestart navigationstop naviplay Britney Spearsplay musicsend a messageread my messages Sometimes the utterance consists only of a noun phrase: musicdie navigationnew messages Particles are always a part of any voice assistant dialogue dataset: yesnopleaseyes please Of course, some cursing and insulting are included, some in the form of sarcasm: you suckyou are dumbyou are miserablea**chlochyou are so intelligent (!) Chris is a driver assistant, so it is pretty normal that the utterances are succinct and to the point. It is not due to rudeness or roughness, just because one needs to speak short while driving. Compare the following two sentences, obviously, the first one is easier if you are driving: Hey Chris, drive me homeHey Chris, shall we drive home together? Imperative sentences in SLU are very common and definitely does not mean rudeness nor related to any speaker sentiment. Nothing interesting here really, first groups of utterances have verbs in the imperative mood, active voice and unmarked aspect. No modal verbs, no modal expressions or past tense. Sentiment for a voice assistant, in this case, better be calculated from the speech signal. Spoken language may not be very exciting so far, then we can switch to written language which allows longer sentences hence more verb forms 😄 I used Women’s E-Commerce Clothing Reviews dataset to explore usage of verbal features. I will use lovely spaCy matcher (definitely not just because I am a contributor 😄) in this section. The dataset includes user reviews and ratings about purchases from a e-commerce website. Before starting, let’s remember the POS tags related to verbs as we will go over the verbs mostly. English verbs have five forms: the base (VB and VBP), -s (VBZ), -ing (VBG), past (VBD), and past participle (VBN). Again, future time has no marker. Modal verbs can , could , might , may , will , would admit the tag MD . Let’s begin with Voice , matching patterns to passive voice are is/was adverb* past-participle-verb and have/has/had been adverb* past-participle-verb . Corresponding Matcher patterns can be: {"TEXT": {"REGEX": "(is|was)"}}, {"POS": "ADV", "OP": "*"}, {"TAG": "VBN"}and {"LEMMA": "have"}, {"TEXT":"been"}, {"POS": "ADV", "OP": "*"}, {"TAG": "VBN"} The first pattern is is/was , followed by any number of adverbs, then a past participle verb. POS is for UD POS tags and TAG is for extended POS. The second pattern is similar: have , has and had is represented by lemma : have . I’ll first import spaCy, load English model then add these two rules to the Matcher object: import spacyfrom spacy.matcher import Matchernlp = spacy.load("en_core_web_sm")matcher = Matcher(nlp.vocab)pass1 = [{"TEXT": {"REGEX": "(is|was)"}}, {"POS": "ADV", "OP": "*"}, {"TAG": "VBN"}pass2 = [{"LEMMA": "have"}, {"TEXT":"been"}, {"POS": "ADV", "OP": "*"}, {"TAG": "VBN"}]matcher.add("pass1", None, pass1)matcher.add("pass2", None, pass2) Then I run the Matcher against the dataset and here are some passive voice examples, both from positive and negative reviews: one wash and this was ruined!washed them according to directions and they were ruined.this could not have been returned fasteri kept it anyway because the xs has been sold out, and got it taken in a bit.it is simply stunning and indeed appears to have been designed by an artist.would buy this again in several different colors if they were offeredif these were presented in other colors, i would buy those as well How do the number of passive voice verbs in a review correlate to the review rating? First of all, let’s see the rating distribution of the reviews: Next, we see the distribution of passive voice verb counts in reviews. Many reviews do not include passive voice at all, some have one passive verb and few have more than one passive construction. Do the number of passive voice verbs correlate to the review rating? From the below, indeed no (checking out the heatmap alone is enough, it points to no correlation at all). No surprise looking at the corpus sentences, passive voice can be “designed by a famous designer” or “they are returned”. While referring to the cloths, how it is designed, tailored, done can be negative or positive; it is returned, ruined, presented can be negative or positive as well. Let’s see how the time of the verb tense and aspect correlates to the review rating. Remember past and present tense are easy to calculate (by looking at the verb inflection), and future is not really a tense since there is no inflection. We will count number of future time occurrences by counting wills, going tos and time adverbs. We can do the tense-aspect table again with Matcher patterns this time: I will also count present perfect progressive tense (“have been doing”) and past perfect progressive tense (“had been doing”), they will contribute both perfective and progressive aspect counts for present and past tenses. Here are some examples of the tense and aspects used in the reviews: I love, love, love this jumpsuit. it's fun, flirty, and fabulous! every time i wear it, i get nothing but great compliments!fits nicely! i'm 5'4, 130lb and pregnant so i bough t medium to grow into.I have been waiting for this sweater coat to ship for weeks and i was so excited for it to arrive. this coat is not true to size and made me look short and squat.I have been searching for the perfect denim jacket and this it!I had been eyeing this coat for a few weeks after it appeared in the email, and i finally decided to purchase it to treat myself. What about the future time? Since there is no morphological marker, we can get help from will , going to , plan to , in 2/5/10 days , next week/month/summer , the day after tomorrow ... Corresponding Matcher patterns can be: future_modal = [{"TEXT": "will", "TAG": "MD"}]future_adv = [{"TEXT": {"REGEX": "(plan(ning) to|(am|is|are) going to)"}}time_expr1 = [{"TEXT": {"REGEX": "((next|oncoming)(week|month|year|summer|winter|autumn|fall|)|the day after tomorrow)"}}]time_expr2 = [{"TEXT": "in"}, {"LIKE_NUM": True}, {"TEXT": {"REGEX":"(day|week|month|year)s"}}] and examples from the corpus are: sadly will be returning, but i'm sure i will find something to exchange it for!I love this shirt because when i first saw it, i wasn't sure if it was a shirt or dress. since it is see-through if you wear it like a dress you will need a slip or wear it with leggings.Just ordered this in a small for me (5'6", 135, size 4) and medium for my mom (5'3", 130, size 8) and it is gorgeous - beautifully draped, all the weight/warmth i'll need for houston fall and winter, looks polished snapped or unsnapped. age-appropriate for both my mom (60's) and myself (30's). will look amazing with skinny jeans or leggings.This will be perfect for the mild fall weather in texasThere's no extra buttons to replace the old one with and i'm worried more of the coat is going to fall apart.This is going to be my go to all season.i plan to wear it out to dinner for my birthday and to a house party on new years day....i am planning to exchange this and hoping it doesn't happen againit is nice addition to my wardrobe and i am planning to wear it to the multiple occasionthis is one of those rare dresses that looks good on me now and will still look good on me in 6 months when i've got a huge belly. According to the below counts, customers used past tense a lot. Present tense is also used widely, whereas future time is used once or twice in each review. Here are the corresponding histograms: According to the heatmap below, usage present and future tense is not really correlated to the rating; both negative and positive ratings include these two tensed verbs. However, past tense looks a bit negatively correlated; more usage of the past tense means worse rating. Perfective and progressive aspects also do not look very bright, they are also a bit negatively correlated. The below ridgeline plot shows some information, better reviews tends to have a spike towards 0 usage of past tense; unhappier customers tend to have a smoother usage of past tense instead. A possible explanation might be customers complained a lot: “package came late”, “waistline didn’t fit”, “I couldn’t zip”, “I didn’t like it”; whereas happy customers look to the future 😄We all look to the future when we are happier, don’t we?😉 As we saw, modality is a semantic notion and the same modal can give different modalities. Let’s see different semantics could introduced for an example: i love that i could dress it up for a party, or down for work. possibilitythe straps are very pretty and it could easily be nightwear too. possibilitythis is a light weight bra, could be a little more supportive. pretty color, with nice lines. irrealisI bought this and like other reviews, agree that the quality probably could be better, but i still love it enough to keep. irrealisgot it on sale, but it still could've been cheaper. irrealisBought a large, could barely pull up over my butt. ability could is correlated to both negative and positive sentiment. Possibility mood looks like on the positive side, where irrealis looks like being both positive or negative. What about couldn't ? It is a whole another story, examples below show how much couldn't provides semantic richness to both negative and positive sentiment, though almost all examples include only one type of modality: so small in fact that i could not zip it up! abilityi was so excited to get his dress for my wedding shower and then i couldn't wear it :( abilityi really tried because the fabric is wonderful and the shirt is light and breezy for summer, i just couldn't make it work abilityi simply couldn't resist! i could not be more pleased and regret not having bought this item earlier, since i would have enjoyed wearing it during the holidays.i could not be happier with the purchase and the keyhole in the back is a beautiful detail. emphasizing opinioni also thought that this was very heavy for a maxi dress and could not imagine wearing it in 80 degree weather. ability i think it's maybe a little too long (or short, i can't figure it out) but i couldn't pass up this skirt because the pattern is so pretty. ability i just wish it was more of a blue denim blue but nonetheless, i could not walk away from the store without this. ability would and wouldn't might feel different but statistically, they are similar to could and couldn't : Irrealis happens both in negative and positive reviews. Consider: maybe if i weren't as small chested this wouldn't be an issue for me. i definitely recommend this tee.the neckline wouldn't even stay up on my upper body, it was that loose. Then no surprise that the presence of would/wouldn’t/could/couldn’t does not give away much about the review sentiment. Corresponding Matcher pattern would be [{"TEXT": {"REGEX": "(would|could|can|might|may)"}, "TAG": "MD"}] MD being the modal verb tag and we exclude will . Dear readers, here we reach the end of this article. We had a great time with spaCy, haven’t we (as usual)? 😃 We process huge amounts of data every day but sometimes we forget to read what is written in the corpus. Language is not just a bunch of words coming together; it has many aspects, both statistical and linguistical. Today we enjoyed both. Next time we will continue with statistical discourse for voice assistants. Till next time, you can always visit Chris on https://chris.com. You can also visit me on https://duygua.github.io always. Meanwhile stay happy, safe and tuned! Palmer, F. (2001), Mood and Modality (2nd ed., Cambridge Textbooks in Linguistics). Cambridge: Cambridge University Press. doi:10.1017/CBO9781139167178
[ { "code": null, "e": 350, "s": 172, "text": "In this article, we will see how verbal functional categories used in customer dialogue text and how these categories contribute to the semantics, especially the text sentiment." }, { "code": null, "e": 681, "s": 350, "text": "Verb phrase in a sentence sometimes can carry huge semantics, sometimes hint the sentiment only by itself even though if one does not see the rest of the context words, hence contribute to sentiment analysis models as important features. For example, cross all the not-included-in-any-VP words from the following customer reviews:" }, { "code": null, "e": 795, "s": 681, "text": "The product isn't working properly. I didn't like this product.I'm not satisfied with the product quality at all." }, { "code": null, "e": 1136, "s": 795, "text": "In order to charge meaning to the sentence, many languages like the verb to admit different inflections such as tense and person. Moreover most of the time we want to express our feeling and opinions about how the proposed action by the verb happened: are we sure, did we see the action by our own eyes, do we think it’s likely or unlikely?" }, { "code": null, "e": 1436, "s": 1136, "text": "This is more of a semantic capability, thus one usually needs more than inflecting the verb, more than grammatical constructions. Function of the verb is a broad topic, but I will explain some basic concepts before the statistical parts. You can skip to the next section if you have this background." }, { "code": null, "e": 1820, "s": 1436, "text": "Tense is a grammatical realization of time by means of verbal inflection. English has 2 tenses: past and present. Future is not a tense not having an inflectional marker, but it is rather a time . Future time is formed either by will or with adverbs such as tomorrow , 8 o'clock or next week/month etc. As you see tense is a grammatical concept and time is rather a semantic concept." }, { "code": null, "e": 1970, "s": 1820, "text": "Another concept is aspect, a grammatical category which reflects the action given by the verb happened with respect to time. English has two aspects:" }, { "code": null, "e": 2084, "s": 1970, "text": "action complete: perfective has moved, had movedaction in progress: progressive is moving, was moving" }, { "code": null, "e": 2131, "s": 2084, "text": "One can summarize tense and aspect as follows:" }, { "code": null, "e": 2321, "s": 2131, "text": "Voice in English is either passive or active, as we learnt in high school. Passive voice has further semantic subcategories, but in this article, we will stay at high school level grammar 😉" }, { "code": null, "e": 2470, "s": 2321, "text": "Mood is a grammatical category indicating whether a verb expresses a fact (indicative mood) or conditionality (subjunctive mood). Some examples are:" }, { "code": null, "e": 2602, "s": 2470, "text": "Sun rises at 6 o'clock here. indicativeIt is important the manager be informed of the changes subjunctive" }, { "code": null, "e": 2746, "s": 2602, "text": "Mood is grammatical and associates to two semantic notions: modality and illocution. Illocution of a sentence can be thought as sentence type :" }, { "code": null, "e": 3009, "s": 2746, "text": "Go there! imperativeDo you want to go there? interrogativeGod save the queen! optativeI will see it. declarative" }, { "code": null, "e": 3580, "s": 3009, "text": "Modality is a semantic notion that is related to speaker’s opinion and belief about the event’s believability, obligatoriness, desirability, or reality. Modality in English can be achieved by modal verbs (will/would, can/could, may/might, shall/should, must), modal adverbs (maybe, perhaps, possibly, probably), some subordinate clauses including (wish, it’s time,possible, probable, chance, possibility ), some modal nouns (decree, demand,necessity, requirement, request) or some modal adjectives (advisable, crucial, imperative, likely, necessary, probable, possible)." }, { "code": null, "e": 4379, "s": 3580, "text": "I would love you if things were different irrealisYou may go permissionI may come with you too possibilityI might come with you too possibilityI must go obligationHe must be earning good money necessityI can ride a bike abilityI can come with you too possibilityIt is possible that we might see big changes around us. possibilityIt might be the truth doubtI'm sure they'll come confidenceLights are on, so he must be in the office evidentiality" }, { "code": null, "e": 4542, "s": 4379, "text": "From now on, we will see the different verbal features that customers use to interact with conversational agents and how those usages lead to different semantics." }, { "code": null, "e": 4672, "s": 4542, "text": "Let’s begin with our Chris, our voice assistant in your car and see some typical user utterances in automotive conversational AI." }, { "code": null, "e": 4722, "s": 4672, "text": "Chris datasets include many imperative sentences:" }, { "code": null, "e": 4829, "s": 4722, "text": "navigatenavigate homestart navigationstop naviplay Britney Spearsplay musicsend a messageread my messages " }, { "code": null, "e": 4885, "s": 4829, "text": "Sometimes the utterance consists only of a noun phrase:" }, { "code": null, "e": 4917, "s": 4885, "text": "musicdie navigationnew messages" }, { "code": null, "e": 4986, "s": 4917, "text": "Particles are always a part of any voice assistant dialogue dataset:" }, { "code": null, "e": 5008, "s": 4986, "text": "yesnopleaseyes please" }, { "code": null, "e": 5089, "s": 5008, "text": "Of course, some cursing and insulting are included, some in the form of sarcasm:" }, { "code": null, "e": 5162, "s": 5089, "text": "you suckyou are dumbyou are miserablea**chlochyou are so intelligent (!)" }, { "code": null, "e": 5450, "s": 5162, "text": "Chris is a driver assistant, so it is pretty normal that the utterances are succinct and to the point. It is not due to rudeness or roughness, just because one needs to speak short while driving. Compare the following two sentences, obviously, the first one is easier if you are driving:" }, { "code": null, "e": 5515, "s": 5450, "text": "Hey Chris, drive me homeHey Chris, shall we drive home together?" }, { "code": null, "e": 5908, "s": 5515, "text": "Imperative sentences in SLU are very common and definitely does not mean rudeness nor related to any speaker sentiment. Nothing interesting here really, first groups of utterances have verbs in the imperative mood, active voice and unmarked aspect. No modal verbs, no modal expressions or past tense. Sentiment for a voice assistant, in this case, better be calculated from the speech signal." }, { "code": null, "e": 6327, "s": 5908, "text": "Spoken language may not be very exciting so far, then we can switch to written language which allows longer sentences hence more verb forms 😄 I used Women’s E-Commerce Clothing Reviews dataset to explore usage of verbal features. I will use lovely spaCy matcher (definitely not just because I am a contributor 😄) in this section. The dataset includes user reviews and ratings about purchases from a e-commerce website." }, { "code": null, "e": 6647, "s": 6327, "text": "Before starting, let’s remember the POS tags related to verbs as we will go over the verbs mostly. English verbs have five forms: the base (VB and VBP), -s (VBZ), -ing (VBG), past (VBD), and past participle (VBN). Again, future time has no marker. Modal verbs can , could , might , may , will , would admit the tag MD ." }, { "code": null, "e": 6839, "s": 6647, "text": "Let’s begin with Voice , matching patterns to passive voice are is/was adverb* past-participle-verb and have/has/had been adverb* past-participle-verb . Corresponding Matcher patterns can be:" }, { "code": null, "e": 6995, "s": 6839, "text": "{\"TEXT\": {\"REGEX\": \"(is|was)\"}}, {\"POS\": \"ADV\", \"OP\": \"*\"}, {\"TAG\": \"VBN\"}and {\"LEMMA\": \"have\"}, {\"TEXT\":\"been\"}, {\"POS\": \"ADV\", \"OP\": \"*\"}, {\"TAG\": \"VBN\"}" }, { "code": null, "e": 7224, "s": 6995, "text": "The first pattern is is/was , followed by any number of adverbs, then a past participle verb. POS is for UD POS tags and TAG is for extended POS. The second pattern is similar: have , has and had is represented by lemma : have ." }, { "code": null, "e": 7316, "s": 7224, "text": "I’ll first import spaCy, load English model then add these two rules to the Matcher object:" }, { "code": null, "e": 7660, "s": 7316, "text": "import spacyfrom spacy.matcher import Matchernlp = spacy.load(\"en_core_web_sm\")matcher = Matcher(nlp.vocab)pass1 = [{\"TEXT\": {\"REGEX\": \"(is|was)\"}}, {\"POS\": \"ADV\", \"OP\": \"*\"}, {\"TAG\": \"VBN\"}pass2 = [{\"LEMMA\": \"have\"}, {\"TEXT\":\"been\"}, {\"POS\": \"ADV\", \"OP\": \"*\"}, {\"TAG\": \"VBN\"}]matcher.add(\"pass1\", None, pass1)matcher.add(\"pass2\", None, pass2)" }, { "code": null, "e": 7786, "s": 7660, "text": "Then I run the Matcher against the dataset and here are some passive voice examples, both from positive and negative reviews:" }, { "code": null, "e": 8201, "s": 7786, "text": "one wash and this was ruined!washed them according to directions and they were ruined.this could not have been returned fasteri kept it anyway because the xs has been sold out, and got it taken in a bit.it is simply stunning and indeed appears to have been designed by an artist.would buy this again in several different colors if they were offeredif these were presented in other colors, i would buy those as well" }, { "code": null, "e": 8350, "s": 8201, "text": "How do the number of passive voice verbs in a review correlate to the review rating? First of all, let’s see the rating distribution of the reviews:" }, { "code": null, "e": 8547, "s": 8350, "text": "Next, we see the distribution of passive voice verb counts in reviews. Many reviews do not include passive voice at all, some have one passive verb and few have more than one passive construction." }, { "code": null, "e": 8722, "s": 8547, "text": "Do the number of passive voice verbs correlate to the review rating? From the below, indeed no (checking out the heatmap alone is enough, it points to no correlation at all)." }, { "code": null, "e": 9010, "s": 8722, "text": "No surprise looking at the corpus sentences, passive voice can be “designed by a famous designer” or “they are returned”. While referring to the cloths, how it is designed, tailored, done can be negative or positive; it is returned, ruined, presented can be negative or positive as well." }, { "code": null, "e": 9344, "s": 9010, "text": "Let’s see how the time of the verb tense and aspect correlates to the review rating. Remember past and present tense are easy to calculate (by looking at the verb inflection), and future is not really a tense since there is no inflection. We will count number of future time occurrences by counting wills, going tos and time adverbs." }, { "code": null, "e": 9416, "s": 9344, "text": "We can do the tense-aspect table again with Matcher patterns this time:" }, { "code": null, "e": 9639, "s": 9416, "text": "I will also count present perfect progressive tense (“have been doing”) and past perfect progressive tense (“had been doing”), they will contribute both perfective and progressive aspect counts for present and past tenses." }, { "code": null, "e": 9708, "s": 9639, "text": "Here are some examples of the tense and aspects used in the reviews:" }, { "code": null, "e": 10261, "s": 9708, "text": "I love, love, love this jumpsuit. it's fun, flirty, and fabulous! every time i wear it, i get nothing but great compliments!fits nicely! i'm 5'4, 130lb and pregnant so i bough t medium to grow into.I have been waiting for this sweater coat to ship for weeks and i was so excited for it to arrive. this coat is not true to size and made me look short and squat.I have been searching for the perfect denim jacket and this it!I had been eyeing this coat for a few weeks after it appeared in the email, and i finally decided to purchase it to treat myself." }, { "code": null, "e": 10447, "s": 10261, "text": "What about the future time? Since there is no morphological marker, we can get help from will , going to , plan to , in 2/5/10 days , next week/month/summer , the day after tomorrow ..." }, { "code": null, "e": 10486, "s": 10447, "text": "Corresponding Matcher patterns can be:" }, { "code": null, "e": 10823, "s": 10486, "text": "future_modal = [{\"TEXT\": \"will\", \"TAG\": \"MD\"}]future_adv = [{\"TEXT\": {\"REGEX\": \"(plan(ning) to|(am|is|are) going to)\"}}time_expr1 = [{\"TEXT\": {\"REGEX\": \"((next|oncoming)(week|month|year|summer|winter|autumn|fall|)|the day after tomorrow)\"}}]time_expr2 = [{\"TEXT\": \"in\"}, {\"LIKE_NUM\": True}, {\"TEXT\": {\"REGEX\":\"(day|week|month|year)s\"}}]" }, { "code": null, "e": 10857, "s": 10823, "text": "and examples from the corpus are:" }, { "code": null, "e": 12043, "s": 10857, "text": "sadly will be returning, but i'm sure i will find something to exchange it for!I love this shirt because when i first saw it, i wasn't sure if it was a shirt or dress. since it is see-through if you wear it like a dress you will need a slip or wear it with leggings.Just ordered this in a small for me (5'6\", 135, size 4) and medium for my mom (5'3\", 130, size 8) and it is gorgeous - beautifully draped, all the weight/warmth i'll need for houston fall and winter, looks polished snapped or unsnapped. age-appropriate for both my mom (60's) and myself (30's). will look amazing with skinny jeans or leggings.This will be perfect for the mild fall weather in texasThere's no extra buttons to replace the old one with and i'm worried more of the coat is going to fall apart.This is going to be my go to all season.i plan to wear it out to dinner for my birthday and to a house party on new years day....i am planning to exchange this and hoping it doesn't happen againit is nice addition to my wardrobe and i am planning to wear it to the multiple occasionthis is one of those rare dresses that looks good on me now and will still look good on me in 6 months when i've got a huge belly." }, { "code": null, "e": 12200, "s": 12043, "text": "According to the below counts, customers used past tense a lot. Present tense is also used widely, whereas future time is used once or twice in each review." }, { "code": null, "e": 12239, "s": 12200, "text": "Here are the corresponding histograms:" }, { "code": null, "e": 12621, "s": 12239, "text": "According to the heatmap below, usage present and future tense is not really correlated to the rating; both negative and positive ratings include these two tensed verbs. However, past tense looks a bit negatively correlated; more usage of the past tense means worse rating. Perfective and progressive aspects also do not look very bright, they are also a bit negatively correlated." }, { "code": null, "e": 13056, "s": 12621, "text": "The below ridgeline plot shows some information, better reviews tends to have a spike towards 0 usage of past tense; unhappier customers tend to have a smoother usage of past tense instead. A possible explanation might be customers complained a lot: “package came late”, “waistline didn’t fit”, “I couldn’t zip”, “I didn’t like it”; whereas happy customers look to the future 😄We all look to the future when we are happier, don’t we?😉" }, { "code": null, "e": 13210, "s": 13056, "text": "As we saw, modality is a semantic notion and the same modal can give different modalities. Let’s see different semantics could introduced for an example:" }, { "code": null, "e": 14031, "s": 13210, "text": "i love that i could dress it up for a party, or down for work. possibilitythe straps are very pretty and it could easily be nightwear too. possibilitythis is a light weight bra, could be a little more supportive. pretty color, with nice lines. irrealisI bought this and like other reviews, agree that the quality probably could be better, but i still love it enough to keep. irrealisgot it on sale, but it still could've been cheaper. irrealisBought a large, could barely pull up over my butt. ability" }, { "code": null, "e": 14201, "s": 14031, "text": "could is correlated to both negative and positive sentiment. Possibility mood looks like on the positive side, where irrealis looks like being both positive or negative." }, { "code": null, "e": 14420, "s": 14201, "text": "What about couldn't ? It is a whole another story, examples below show how much couldn't provides semantic richness to both negative and positive sentiment, though almost all examples include only one type of modality:" }, { "code": null, "e": 15692, "s": 14420, "text": "so small in fact that i could not zip it up! abilityi was so excited to get his dress for my wedding shower and then i couldn't wear it :( abilityi really tried because the fabric is wonderful and the shirt is light and breezy for summer, i just couldn't make it work abilityi simply couldn't resist! i could not be more pleased and regret not having bought this item earlier, since i would have enjoyed wearing it during the holidays.i could not be happier with the purchase and the keyhole in the back is a beautiful detail. emphasizing opinioni also thought that this was very heavy for a maxi dress and could not imagine wearing it in 80 degree weather. ability i think it's maybe a little too long (or short, i can't figure it out) but i couldn't pass up this skirt because the pattern is so pretty. ability i just wish it was more of a blue denim blue but nonetheless, i could not walk away from the store without this. ability" }, { "code": null, "e": 15792, "s": 15692, "text": "would and wouldn't might feel different but statistically, they are similar to could and couldn't :" }, { "code": null, "e": 15858, "s": 15792, "text": "Irrealis happens both in negative and positive reviews. Consider:" }, { "code": null, "e": 16032, "s": 15858, "text": "maybe if i weren't as small chested this wouldn't be an issue for me. i definitely recommend this tee.the neckline wouldn't even stay up on my upper body, it was that loose." }, { "code": null, "e": 16152, "s": 16032, "text": "Then no surprise that the presence of would/wouldn’t/could/couldn’t does not give away much about the review sentiment." }, { "code": null, "e": 16191, "s": 16152, "text": "Corresponding Matcher pattern would be" }, { "code": null, "e": 16257, "s": 16191, "text": "[{\"TEXT\": {\"REGEX\": \"(would|could|can|might|may)\"}, \"TAG\": \"MD\"}]" }, { "code": null, "e": 16307, "s": 16257, "text": "MD being the modal verb tag and we exclude will ." }, { "code": null, "e": 16893, "s": 16307, "text": "Dear readers, here we reach the end of this article. We had a great time with spaCy, haven’t we (as usual)? 😃 We process huge amounts of data every day but sometimes we forget to read what is written in the corpus. Language is not just a bunch of words coming together; it has many aspects, both statistical and linguistical. Today we enjoyed both. Next time we will continue with statistical discourse for voice assistants. Till next time, you can always visit Chris on https://chris.com. You can also visit me on https://duygua.github.io always. Meanwhile stay happy, safe and tuned!" } ]
Maximum Profit | Practice | GeeksforGeeks
In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of N days in an array A[ ] and a positive integer K, find out the maximum profit a person can make in at-most K transactions. A transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous transaction has been completed. Example 1: Input: K = 2, N = 6 A = {10, 22, 5, 75, 65, 80} Output: 87 Explaination: 1st transaction: buy at 10 and sell at 22. 2nd transaction : buy at 5 and sell at 80. Example 2: Input: K = 3, N = 4 A = {20, 580, 420, 900} Output: 1040 Explaination: The trader can make at most 2 transactions and giving him a profit of 1040. Example 3: Input: K = 1, N = 5 A = {100, 90, 80, 50, 25} Output: 0 Explaination: Selling price is decreasing daily. So seller cannot have profit. Your Task: You do not need to read input or print anything. Your task is to complete the function maxProfit() which takes the values K, N and the array A[] as input parameters and returns the maximum profit. Expected Time Complexity: O(N*K) Expected Auxiliary Space: O(N*K) Constraints: 1 ≤ N ≤ 500 1 ≤ K ≤ 200 1 ≤ A[ i ] ≤ 1000 0 milindprajapatmst191 week ago Total Time Taken: 0.03/1.17 Time Complexity: O(n*k) Space Complexity: O(n*k) const int N = 500, K = 200, INF = 1e6; int dp[N + 1][K + 1][2], f[] = {1, -1}; class Solution { public: int maxProfit(int k, int n, int arr[], int hold = 0) { if (k == 0 || n == 0) return hold ? -INF : 0; if (dp[n][k][hold] == -1) dp[n][k][hold] = max(maxProfit(k, n - 1, arr, hold), maxProfit(k - hold, n - 1, arr, 1 - hold) + f[hold] * arr[n - 1]); return dp[n][k][hold]; } Solution() { memset(dp, -1, sizeof(dp)); } }; 0 sandeep55211 month ago C++ Single 1-D array Space Optimized DP Solution(0.0 time taken) int maxProfit(int k, int n, int p[]) { int c=k*2; vector<int> dp(c+1,0); for(int i=n-1;i>=0;i--){ for(int j=c-1;j>=0;j--){ if(j%2) dp[j]=max(p[i]+dp[j+1],dp[j]); else dp[j]=max(dp[j+1]-p[i],dp[j]); } } return dp[0]; } 0 hamidnourashraf1 month ago #O(N^2*K) import math class Solution: def maxProfit(self, K, N, A): dp = [[0] *(K+1) for j in range(N+1)] for k in range(1, K+1): for i in range(1, N+1): _max = -math.inf for j in range(1, i): _max = max(_max, A[i-1] - A[j-1] + dp[j-1][k-1]) dp[i][k] = max(_max, dp[i-1][k]) return dp[N][K] #O(N*K) import math class Solution: def maxProfit(self, K, N, A): dp = [[0] *(K+1) for j in range(N+1)] for k in range(1, K+1): pre_diff = -math.inf for i in range(1, N+1): pre_diff = max(pre_diff, -A[i-1] + dp[i-1][k-1]) dp[i][k] = max(pre_diff + A[i-1], dp[i-1][k]) return dp[N][K] 0 jaideepsinghsheoran1 month ago int maxProfit(int k, int n, int p[]) { vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0)); for(int t = 1; t <= k; t++){ int preComp = INT_MIN; for(int i = 1; i <= n; i++){ preComp = max(preComp, dp[t-1][i-1] - p[i-1]); dp[t][i] = max(p[i-1] + preComp, dp[t][i-1]); } } return dp[k][n]; } 0 jaideepsinghsheoran1 month ago int maxProfit(int k, int n, int p[]) { vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0)); for(int t = 1; t <= k; t++){ for(int i = 1; i <= n; i++){ int maxProfitTill = INT_MIN; for(int j = 1; j < i; j++){ maxProfitTill = max(p[i-1] - p[j-1] + dp[t-1][j-1], maxProfitTill); } dp[t][i] = max(maxProfitTill, dp[t][i-1]); } } return dp[k][n]; } 0 aditya048482 months ago def maxProfit(self, k, n, prices): if n < 2: return 0 dp = [[0 for j in range(k+1)] for i in range(n)] for j in range(1, k+1): maxDiff = -prices[0] for i in range(1, n): dp[i][j] = max(dp[i][j], dp[i-1][j], prices[i]+maxDiff) maxDiff = max(maxDiff, dp[i-1][j-1] - prices[i]) return max(dp[n-1]) +1 aloksinghbais022 months ago C++ solution having time complexity as O(K*N) and space complexity as O(K*N) is as follows :- Execution Time :- 0.0 / 1.2 sec int maxProfit(int K, int N, int A[]) { vector<vector<int>> dp(K+1,vector<int>(N)); for(int i = 0; i <= K; i++){ for(int j = 0; j < N; j++){ if(i == 0 || j == 0) dp[i][j] = 0; } } for(int i = 1; i <= K; i++){ int maxDiff = INT_MIN; for(int j = 1; j < N; j++){ maxDiff = max(maxDiff,dp[i-1][j-1] - A[j-1]); dp[i][j] = max(dp[i][j-1],maxDiff+A[j]); } } return dp[K][N-1]; } 0 bhushan91682730332 months ago C++ DP uncomment to see dp table: int maxProfit(int K, int N, int A[]) { vector<vector<int>>dp(K + 1, vector<int>(N, 0)); for (int i = 1; i <= K; i++) { int maxDiff = INT_MIN; for (int j = 1; j < N; j++) { maxDiff = max(maxDiff, (dp[i - 1][j - 1] - A[j - 1])); dp[i][j] = max(dp[i][j - 1], (A[j] + maxDiff)); } } /* for (int i = 0; i <= K; i++) { for (int j = 0; j < N; j++) { cout << dp[i][j] << " "; } cout << endl; }*/ return dp[K][N - 1]; } 0 sumitanand43993 months ago BOTTOM-UP DP || class Solution { public: int maxProfit(int k, int n, int prices[]) { // code here int dp[n+1][k+1][2]; memset(dp,0,sizeof(dp)); //vector<vector<vector<int>>> dp(n+1, vector<vector<int>> (k+1, vector<int>(2,0))); for(int i=n-1; i>=0; i--) { for(int rem=1; rem<=k; rem++) { for(int hold=0; hold<2; hold++) { int no= dp[i+1][rem][hold]; int yes; if(hold==1) //selling stock { yes= prices[i] + dp[i+1][rem-1][0]; } else //(hold==0) buying stock { yes= -prices[i] + dp[i+1][rem][1]; } //recurrence relation dp[i][rem][hold]= max(no, yes); } } } return dp[0][k][0]; }}; 0 safetymantu3 months ago 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": 610, "s": 238, "text": "In the stock market, a person buys a stock and sells it on some future date. Given the stock prices of N days in an array A[ ] and a positive integer K, find out the maximum profit a person can make in at-most K transactions. A transaction is equivalent to (buying + selling) of a stock and new transaction can start only when the previous transaction has been completed." }, { "code": null, "e": 622, "s": 610, "text": "\nExample 1:" }, { "code": null, "e": 784, "s": 622, "text": "Input: K = 2, N = 6\nA = {10, 22, 5, 75, 65, 80}\nOutput: 87\nExplaination: \n1st transaction: buy at 10 and sell at 22. \n2nd transaction : buy at 5 and sell at 80.\n" }, { "code": null, "e": 795, "s": 784, "text": "Example 2:" }, { "code": null, "e": 944, "s": 795, "text": "Input: K = 3, N = 4\nA = {20, 580, 420, 900}\nOutput: 1040\nExplaination: The trader can make at most 2 \ntransactions and giving him a profit of 1040.\n" }, { "code": null, "e": 955, "s": 944, "text": "Example 3:" }, { "code": null, "e": 1091, "s": 955, "text": "Input: K = 1, N = 5\nA = {100, 90, 80, 50, 25}\nOutput: 0\nExplaination: Selling price is decreasing \ndaily. So seller cannot have profit." }, { "code": null, "e": 1300, "s": 1091, "text": "\nYour Task:\nYou do not need to read input or print anything. Your task is to complete the function maxProfit() which takes the values K, N and the array A[] as input parameters and returns the maximum profit." }, { "code": null, "e": 1367, "s": 1300, "text": "\nExpected Time Complexity: O(N*K)\nExpected Auxiliary Space: O(N*K)" }, { "code": null, "e": 1423, "s": 1367, "text": "\nConstraints:\n1 ≤ N ≤ 500\n1 ≤ K ≤ 200\n1 ≤ A[ i ] ≤ 1000" }, { "code": null, "e": 1425, "s": 1423, "text": "0" }, { "code": null, "e": 1455, "s": 1425, "text": "milindprajapatmst191 week ago" }, { "code": null, "e": 1483, "s": 1455, "text": "Total Time Taken: 0.03/1.17" }, { "code": null, "e": 1507, "s": 1483, "text": "Time Complexity: O(n*k)" }, { "code": null, "e": 1533, "s": 1507, "text": "Space Complexity: O(n*k) " }, { "code": null, "e": 2064, "s": 1533, "text": "const int N = 500, K = 200, INF = 1e6;\nint dp[N + 1][K + 1][2], f[] = {1, -1};\nclass Solution {\n public:\n int maxProfit(int k, int n, int arr[], int hold = 0) {\n if (k == 0 || n == 0)\n return hold ? -INF : 0;\n if (dp[n][k][hold] == -1)\n dp[n][k][hold] = max(maxProfit(k, n - 1, arr, hold), \n maxProfit(k - hold, n - 1, arr, 1 - hold) + f[hold] * arr[n - 1]);\n return dp[n][k][hold];\n\n }\n Solution() {\n memset(dp, -1, sizeof(dp));\n }\n};" }, { "code": null, "e": 2066, "s": 2064, "text": "0" }, { "code": null, "e": 2089, "s": 2066, "text": "sandeep55211 month ago" }, { "code": null, "e": 2154, "s": 2089, "text": "C++ Single 1-D array Space Optimized DP Solution(0.0 time taken)" }, { "code": null, "e": 2462, "s": 2154, "text": "int maxProfit(int k, int n, int p[]) {\n int c=k*2;\n vector<int> dp(c+1,0);\n for(int i=n-1;i>=0;i--){\n for(int j=c-1;j>=0;j--){\n if(j%2) dp[j]=max(p[i]+dp[j+1],dp[j]);\n else dp[j]=max(dp[j+1]-p[i],dp[j]);\n }\n }\n return dp[0];\n }" }, { "code": null, "e": 2464, "s": 2462, "text": "0" }, { "code": null, "e": 2491, "s": 2464, "text": "hamidnourashraf1 month ago" }, { "code": null, "e": 2895, "s": 2491, "text": "#O(N^2*K)\nimport math\nclass Solution:\n \n def maxProfit(self, K, N, A):\n dp = [[0] *(K+1) for j in range(N+1)]\n for k in range(1, K+1):\n for i in range(1, N+1):\n _max = -math.inf\n for j in range(1, i):\n _max = max(_max, A[i-1] - A[j-1] + dp[j-1][k-1])\n dp[i][k] = max(_max, dp[i-1][k])\n return dp[N][K]" }, { "code": null, "e": 3268, "s": 2895, "text": "#O(N*K)\nimport math\nclass Solution:\n \n def maxProfit(self, K, N, A):\n dp = [[0] *(K+1) for j in range(N+1)]\n for k in range(1, K+1):\n pre_diff = -math.inf\n for i in range(1, N+1):\n pre_diff = max(pre_diff, -A[i-1] + dp[i-1][k-1])\n dp[i][k] = max(pre_diff + A[i-1], dp[i-1][k])\n return dp[N][K]" }, { "code": null, "e": 3270, "s": 3268, "text": "0" }, { "code": null, "e": 3301, "s": 3270, "text": "jaideepsinghsheoran1 month ago" }, { "code": null, "e": 3711, "s": 3301, "text": "int maxProfit(int k, int n, int p[]) {\n vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));\n for(int t = 1; t <= k; t++){\n int preComp = INT_MIN;\n for(int i = 1; i <= n; i++){\n preComp = max(preComp, dp[t-1][i-1] - p[i-1]);\n \n dp[t][i] = max(p[i-1] + preComp, dp[t][i-1]);\n }\n }\n return dp[k][n];\n }" }, { "code": null, "e": 3713, "s": 3711, "text": "0" }, { "code": null, "e": 3744, "s": 3713, "text": "jaideepsinghsheoran1 month ago" }, { "code": null, "e": 4231, "s": 3744, "text": "int maxProfit(int k, int n, int p[]) {\n vector<vector<int>> dp(k + 1, vector<int>(n + 1, 0));\n for(int t = 1; t <= k; t++){\n for(int i = 1; i <= n; i++){\n int maxProfitTill = INT_MIN;\n for(int j = 1; j < i; j++){\n maxProfitTill = max(p[i-1] - p[j-1] + dp[t-1][j-1], maxProfitTill);\n }\n dp[t][i] = max(maxProfitTill, dp[t][i-1]);\n }\n }\n return dp[k][n];\n }" }, { "code": null, "e": 4233, "s": 4231, "text": "0" }, { "code": null, "e": 4257, "s": 4233, "text": "aditya048482 months ago" }, { "code": null, "e": 4679, "s": 4257, "text": "def maxProfit(self, k, n, prices):\n if n < 2:\n return 0\n dp = [[0 for j in range(k+1)] for i in range(n)]\n \n for j in range(1, k+1):\n maxDiff = -prices[0]\n for i in range(1, n):\n dp[i][j] = max(dp[i][j], dp[i-1][j], prices[i]+maxDiff)\n maxDiff = max(maxDiff, dp[i-1][j-1] - prices[i])\n \n return max(dp[n-1]) " }, { "code": null, "e": 4682, "s": 4679, "text": "+1" }, { "code": null, "e": 4710, "s": 4682, "text": "aloksinghbais022 months ago" }, { "code": null, "e": 4806, "s": 4710, "text": "C++ solution having time complexity as O(K*N) and space complexity as O(K*N) is as follows :- " }, { "code": null, "e": 4840, "s": 4808, "text": "Execution Time :- 0.0 / 1.2 sec" }, { "code": null, "e": 5375, "s": 4842, "text": "int maxProfit(int K, int N, int A[]) { vector<vector<int>> dp(K+1,vector<int>(N)); for(int i = 0; i <= K; i++){ for(int j = 0; j < N; j++){ if(i == 0 || j == 0) dp[i][j] = 0; } } for(int i = 1; i <= K; i++){ int maxDiff = INT_MIN; for(int j = 1; j < N; j++){ maxDiff = max(maxDiff,dp[i-1][j-1] - A[j-1]); dp[i][j] = max(dp[i][j-1],maxDiff+A[j]); } } return dp[K][N-1]; }" }, { "code": null, "e": 5377, "s": 5375, "text": "0" }, { "code": null, "e": 5407, "s": 5377, "text": "bhushan91682730332 months ago" }, { "code": null, "e": 5441, "s": 5407, "text": "C++ DP uncomment to see dp table:" }, { "code": null, "e": 5883, "s": 5441, "text": "int maxProfit(int K, int N, int A[]) {\n\tvector<vector<int>>dp(K + 1, vector<int>(N, 0));\n\n\n\tfor (int i = 1; i <= K; i++)\t{\n\t\tint maxDiff = INT_MIN;\n\t\tfor (int j = 1; j < N; j++)\t{\n\t\t\tmaxDiff = max(maxDiff, (dp[i - 1][j - 1] - A[j - 1]));\n\t\t\tdp[i][j] = max(dp[i][j - 1], (A[j] + maxDiff));\n\t\t}\n\t}\n\t/*\n\tfor (int i = 0; i <= K; i++)\t{\n\t\tfor (int j = 0; j < N; j++)\t{\n\t\t\tcout << dp[i][j] << \" \";\n\t\t}\n\t\tcout << endl;\n\t}*/\n\n\treturn dp[K][N - 1];\n}" }, { "code": null, "e": 5885, "s": 5883, "text": "0" }, { "code": null, "e": 5912, "s": 5885, "text": "sumitanand43993 months ago" }, { "code": null, "e": 5929, "s": 5912, "text": "BOTTOM-UP DP || " }, { "code": null, "e": 6864, "s": 5931, "text": "class Solution { public: int maxProfit(int k, int n, int prices[]) { // code here int dp[n+1][k+1][2]; memset(dp,0,sizeof(dp)); //vector<vector<vector<int>>> dp(n+1, vector<vector<int>> (k+1, vector<int>(2,0))); for(int i=n-1; i>=0; i--) { for(int rem=1; rem<=k; rem++) { for(int hold=0; hold<2; hold++) { int no= dp[i+1][rem][hold]; int yes; if(hold==1) //selling stock { yes= prices[i] + dp[i+1][rem-1][0]; } else //(hold==0) buying stock { yes= -prices[i] + dp[i+1][rem][1]; } //recurrence relation dp[i][rem][hold]= max(no, yes); } } } return dp[0][k][0]; }};" }, { "code": null, "e": 6870, "s": 6868, "text": "0" }, { "code": null, "e": 6894, "s": 6870, "text": "safetymantu3 months ago" }, { "code": null, "e": 7040, "s": 6894, "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": 7076, "s": 7040, "text": " Login to access your submissions. " }, { "code": null, "e": 7086, "s": 7076, "text": "\nProblem\n" }, { "code": null, "e": 7096, "s": 7086, "text": "\nContest\n" }, { "code": null, "e": 7159, "s": 7096, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7307, "s": 7159, "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": 7515, "s": 7307, "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": 7621, "s": 7515, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Large-scale Graph Mining with Spark: Part 2 | by Win Suen | Towards Data Science
A tutorial in 2 parts: Part 1: Graphs for unsupervised learning. Part 2 (you are here!): How you can wield magical graph powers. We’ll talk about label propagation, Spark GraphFrames, and results. Repo with sample graph and notebook here: https://github.com/wsuen/pygotham2018_graphmining In Part 1 (here), we saw how to solve unsupervised machine learning problems with graphs because communities are clusters. We can leverage edges between nodes as an indicator of similarity or relation, the same way distances in a feature space is used for other types of clustering. Here, we dive into the hows of community detection. We build and mine a large web graph, learning how to implement a community detection method called Label Propagation Algorithm (LPA) in Spark. Though there are many community detection techniques, I focus only on one: label propagation. For an overview of other methods, I recommend Santo Fortunato’s “Community Detection in Graphs”. Enter the Label Propagation Algorithm (LPA) proposed by Raghavan, Albert, and Kumara (2007). LPA is an iterative community detection solution whereby information “flows” through the graph based on underlying edge structure. Here’s how LPA works: At the beginning, each node starts in its own community.For each iteration, go through all your nodes randomly. For each node, update that node’s community label with the label of the majority of its neighbors. Randomly break any ties.If nodes are now labelled with the majority label of their neighbors, the algorithm has achieved the stop criterion. If not, repeat step 2. At the beginning, each node starts in its own community. For each iteration, go through all your nodes randomly. For each node, update that node’s community label with the label of the majority of its neighbors. Randomly break any ties. If nodes are now labelled with the majority label of their neighbors, the algorithm has achieved the stop criterion. If not, repeat step 2. Label propagation makes sense intuitively. Let’s say one day at work, someone gets a cold and “propagates” the illness until everyone in your workplace is as sick as their neighbors. Meanwhile, employees of FoobarCo across the street catch and spread the flu. There’s not much contact between you and FoobarCo, so “propagation” stops when members of each community have caught the ailment du jour. Convergence achieved! Too bad about the sniffling and headaches though. Labelled data is nice, but not required. Makes LPA suitable for our unsupervised machine learning use case. Parameter tuning is straightforward. LPA runs with a max_iterations parameter, and you can get some good results using the default value of 5. Raghavan and her coauthors tested LPA against several labelled networks. They discovered that at least 95% of nodes are correctly classified in 5 iterations. A priori number of clusters, cluster size, other metric not required. This is crucial if you don’t want to assume your graph has a certain structure or hierarchy. I had no a priori assumptions about the network structure of my web graph, the number of communities I had data for, or the expected sizes of these communities. Near linear runtime. Each iteration of LPA is O(m), linear in number of edges. The whole sequence of steps runs in near linear time, compared to O(n log n) or O(m+n) for some previous community detection solutions. Interpretability. When someone asks, you can explain why a node was grouped into a certain community. First, a quick and non-exhaustive breakdown of the tools landscape. I divided the tools based on graph size, whether the library plays nicely with Python, and how easily I could generate simple visualizations. A non-exhaustive menu of tools: For data that fit onto a single machine, the networkx Python package is a good choice for easy-to-use graph exploration. It implements the most common algorithms (including label propagation, PageRank, maximum clique detection, and much more!). Simple visualizations are also possible. Gephi is an open graph analysis tool. Gephi isn’t a Python package, but a standalone tool with a robust UI and impressive graph visualization capabilities. If you are working with smaller graphs, need strong visualizations, and prefer a UI to working in Python, give Gephi a try. Spark has 2 graph libraries, GraphX and GraphFrames. Spark is a great solution when you have graph data too large to fit onto a single machine (limited to amount of resources allocated to your Spark application), want to take advantage of parallel processing, and some of Spark’s built-in fault tolerance features. Pyspark, Spark’s Python API, is nicely suited for integrating into other libraries like scikit-learn, matplotlib, or networkx. Apache Giraph is the open-source implementation of Pregel, a graph processing architecture created by Google. Giraph had a higher barrier to entry compared to the previous solutions. While Giraph is very powerful for large scale graph analysis deployments, I chose something more lightweight that had both Scala and Python APIs. Neo4j is a graph database system. It does have a Python client, though you have to install Neo4j separately. Since my analysis was only a POC, I wanted to avoid maintaining and deploying an entirely separate tool that did not integrate with my existing code. Finally, you could in theory implement your own solution. For initial data science exploration, I would discourage this. Many bespoke graph mining algorithms are for very specific use cases (for instance— be super efficient at graph clustering only, not other things). If you do need to work with very, very large datasets, first consider sampling your graph, filtering subgraphs of interest, inferring relationships from examples, basically anything to get more mileage from one of the existing tools. Given the data size I was working with, I chose Spark GraphFrames. Remember: the best graph library for your project depends on languages, graph size, how you store your graph data, and personal preference! Great! I’m fully convinced how awesome graphs are, and they’re the coolest things ever! How do I get started using community detection on real data? -you 1. Obtain data: The Common Crawl dataset is an open web crawl corpus well-suited for web graph research. The crawl results are stored in WARC (Web Archive) format. In addition to page contents, the dataset contains crawl date, headers used, and other metadata. I sampled 100 files from the September 2017 crawl. The file warc.paths.gz contains pathnames; using these pathnames, download the respective files from s3. 2. Parse and clean data: As a first pass, we want the html content of each page. For each page, we collect the URL and the URLs of any links to create our graph. To extract edges from raw WARC files, I wrote some data cleaning code that probably should never see the light of day. At least it got the job done so I can focus on more fun things! My parsing code was written in Scala, but my demo is in pyspark. I used WarcReaderFactory and Jericho parser. For python, a library like warc looks like it could cover your data munging needs. After I had all the href links out of the html content, I drew edges between domains rather than full URLs. Instead of medium.com/foo/bar and medium.com/foobar, I only created one node, medium.com, that captured link relationships to and from other domains. I filtered out loops. Loops are edges that connect a node to itself, not useful for my purposes. No edges drawn if medium.com/foobar linked to same domain, say, medium.com/placeholderpage. I removed many of the most popular resource links, including popular CDNs, trackers, and assets. For my preliminary exploration, I only wanted to focus on webpages a human would likely visit. 3. Initialize a Spark Context: For those following along at home, see demo at https://github.com/wsuen/pygotham2018_graphmining. This demo only runs on your local machine. You won’t get all the computational resources of a distributed cluster, but you will get an idea of how to get started with Spark GraphFrames. I’ll be working with Spark 2.3. Import pyspark and other needed libraries, including graphframes. Then create a SparkContext, which will allow you to run a pyspark application. # add GraphFrames package to spark-submitimport osos.environ['PYSPARK_SUBMIT_ARGS'] = '--packages graphframes:graphframes:0.6.0-spark2.3-s_2.11 pyspark-shell'import pyspark# create SparkContext and Spark Sessionsc = pyspark.SparkContext("local[*]")spark = SparkSession.builder.appName('notebook').getOrCreate()# import GraphFramesfrom graphframes import * 4. Create a GraphFrame: Once you have your cleaned data, you can load your vertices and edges into Spark DataFrames. vertices contains an idfor each node, and the name of the node, which indicates the domain. edges contains my directed edges, from source domain src to the domain the source links to, dst. # show 10 nodesvertices.show(10)+--------+----------------+| id| name|+--------+----------------+|000db143| msn.com||51a48ea2|tradedoubler.com||31312317| microsoft.com||a45016f2| outlook.com||2f5bf4c8| bing.com|+--------+----------------+only showing top 5 rows# show 10 edgesedges.show(10)+--------+--------+| src| dst|+--------+--------+|000db143|51a48ea2||000db143|31312317||000db143|a45016f2||000db143|31312317||000db143|51a48ea2|+--------+--------+only showing top 5 rows You can then create a GraphFrame object with your vertices and edges. Voila! You have a graph! # create GraphFramegraph = GraphFrame(vertices, edges) 5. Running LPA: One line of code allows you to run LPA. Here, I run LPA with 5 iterations (maxIter). # run LPA with 5 iterationscommunities = graph.labelPropagation(maxIter=5)communities.persist().show(10)+--------+--------------------+-------------+| id| name| label|+--------+--------------------+-------------+|407ae1cc| coop.no| 781684047881||1b0357be| buenacuerdo.com.ar|1245540515843||acc8136a| toptenreviews.com|1537598291986||abdd63cd| liberoquotidiano.it| 317827579915||db5c0434| meetme.com| 712964571162||0f8dff85| ameblo.jp| 171798691842||b6b04a58| tlnk.io|1632087572480||5bcfd421| wowhead.com| 429496729618||b4d4008d|investingcontrari...| 919123001350||ce7a3185| pokemoncentral.it|1511828488194|+--------+--------------------+-------------+only showing top 10 rows Running graph.labelPropagation() returns a DataFrame with nodes and a label denoting which community that node belongs in. You can use label to understand distribution of community size and zoom in on areas of interest. For example, to discover every other website in the same community as pokemoncentral.it (and honestly, who wouldn’t?), filter for all other nodes where label = 1511828488194. What happened when I ran LPA on my sample Common Crawl web graph? I began with over 15 million web sites in my raw data. That’s a lot of nodes, many of which contained redundant information. The cleaning process I described condensed the graph into fewer, more meaningful edges. LPA discovered over 4,700 communities. However, over half of these communities contained only one or two nodes. On the other end of the size spectrum, the largest community was over 3,500 different websites! To give an idea of scope, this was around 5% of the nodes in my final graph post-filtering. The extremes in community size illustrate one drawback of LPA. Too much convergence, and there could be clusters that are too large (caused by certain labels dominating densely connected networks). Too little convergence and you may get more, smaller communities that are less useful. I found that the most interesting clusters ended up being somewhere between the two extremes. In my dataset, LPA did converge around 5 iterations. You can see the number of communities level off at about 4,700. Raghavan and her colleagues showed this property with their labelled graphs as well. One possible mechanism that explains this is the small-world network effect — the tendency for graphs to cluster, but also to have short path lengths compared to number of nodes. In other words, although graphs have clusters, but you would also expect to be able to travel from, say, one friend to another in your network within 5–6 jumps. Many real-world graphs, including the Internet and social networks, share this property. You may also know this as the six degrees of separation phenomenon. At a coarse level, let’s see some samples clusters. As with traditional unsupervised clustering, the communities can be a mix of different sites, although there are topics of interest that we would not have discovered without LPA! From left to right: E-learning sites: Sites related to or linking to e-learning pages. Time for me to find some new data science MOOCs! Bedbug sites: Sites related to real estate and bed bugs. All these sites used the same template/images, just with slightly different domain names. Don’t think I ever got to the bottom of this. Star Wars community: Sites that talk about Star Wars movies, events, and memorabilia frequently link to each other. It’s worth emphasizing that we obtained this clusters without text processing and feature selection, manual labelling, domain name features, or even knowing how many communities to find. We found communities of interest by leveraging the underlying network structure of the web graph! I’ve barely scratched the surface of web graph communities. There are so many directions future research could go. For example: Layer in and propagate metadata: If we add information such as edge weights, link types, or external labels to the data, how well can we propagate this information through the graph? Remove/add nodes and measure impact on communities: I’m curious how adding or taking away nodes of high edge centrality change effectiveness of LPA and quality of resulting communities. Observe web graph evolution over time: There is a new Common Crawl dataset each month! Would be interesting to see what clusters emerge over time. Conversely, what communities remain unchanged? As we know, the Internet isn’t static. The Github repo for the demo contains a small sample web graph of 10k nodes. There are also instructions for getting setup with Docker and running the pyspark notebooks. I hope this will be helpful in jump-starting experimentation with web graph data, and learning Spark GraphFrames for your own data science problems. Happy exploring! Thanks to Dr. Yana Volkovich for deepening my learning of graph theory and being a great mentor. Thanks also to my other colleagues who gave feedback on my talk. Adamic, Lada A., and Natalie Glance. “The political blogosphere and the 2004 US election: divided they blog.” Proceedings of the 3rd international workshop on Link discovery. ACM, 2005. Common Crawl dataset (September 2017). Farine, Damien R., et al. “Both nearest neighbours and long-term affiliates predict individual locations during collective movement in wild baboons.” Scientific reports 6 (2016): 27704 Fortunato, Santo. “Community detection in graphs.” Physics reports 486.3–5 (2010): 75–174. Girvan, Michelle, and Mark EJ Newman. “Community structure in social and biological networks.” Proceedings of the national academy of sciences 99.12 (2002): 7821–7826. Leskovec, Jure, Anand Rajaraman, and Jeffrey David Ullman. Mining of massive datasets. Cambridge University Press, 2014. Raghavan, Usha Nandini, Réka Albert, and Soundar Kumara. “Near linear time algorithm to detect community structures in large-scale networks.” Physical review E 76.3 (2007): 036106. Zachary karate club network dataset — KONECT, April 2017.
[ { "code": null, "e": 194, "s": 171, "text": "A tutorial in 2 parts:" }, { "code": null, "e": 236, "s": 194, "text": "Part 1: Graphs for unsupervised learning." }, { "code": null, "e": 460, "s": 236, "text": "Part 2 (you are here!): How you can wield magical graph powers. We’ll talk about label propagation, Spark GraphFrames, and results. Repo with sample graph and notebook here: https://github.com/wsuen/pygotham2018_graphmining" }, { "code": null, "e": 743, "s": 460, "text": "In Part 1 (here), we saw how to solve unsupervised machine learning problems with graphs because communities are clusters. We can leverage edges between nodes as an indicator of similarity or relation, the same way distances in a feature space is used for other types of clustering." }, { "code": null, "e": 938, "s": 743, "text": "Here, we dive into the hows of community detection. We build and mine a large web graph, learning how to implement a community detection method called Label Propagation Algorithm (LPA) in Spark." }, { "code": null, "e": 1129, "s": 938, "text": "Though there are many community detection techniques, I focus only on one: label propagation. For an overview of other methods, I recommend Santo Fortunato’s “Community Detection in Graphs”." }, { "code": null, "e": 1375, "s": 1129, "text": "Enter the Label Propagation Algorithm (LPA) proposed by Raghavan, Albert, and Kumara (2007). LPA is an iterative community detection solution whereby information “flows” through the graph based on underlying edge structure. Here’s how LPA works:" }, { "code": null, "e": 1750, "s": 1375, "text": "At the beginning, each node starts in its own community.For each iteration, go through all your nodes randomly. For each node, update that node’s community label with the label of the majority of its neighbors. Randomly break any ties.If nodes are now labelled with the majority label of their neighbors, the algorithm has achieved the stop criterion. If not, repeat step 2." }, { "code": null, "e": 1807, "s": 1750, "text": "At the beginning, each node starts in its own community." }, { "code": null, "e": 1987, "s": 1807, "text": "For each iteration, go through all your nodes randomly. For each node, update that node’s community label with the label of the majority of its neighbors. Randomly break any ties." }, { "code": null, "e": 2127, "s": 1987, "text": "If nodes are now labelled with the majority label of their neighbors, the algorithm has achieved the stop criterion. If not, repeat step 2." }, { "code": null, "e": 2597, "s": 2127, "text": "Label propagation makes sense intuitively. Let’s say one day at work, someone gets a cold and “propagates” the illness until everyone in your workplace is as sick as their neighbors. Meanwhile, employees of FoobarCo across the street catch and spread the flu. There’s not much contact between you and FoobarCo, so “propagation” stops when members of each community have caught the ailment du jour. Convergence achieved! Too bad about the sniffling and headaches though." }, { "code": null, "e": 2705, "s": 2597, "text": "Labelled data is nice, but not required. Makes LPA suitable for our unsupervised machine learning use case." }, { "code": null, "e": 3006, "s": 2705, "text": "Parameter tuning is straightforward. LPA runs with a max_iterations parameter, and you can get some good results using the default value of 5. Raghavan and her coauthors tested LPA against several labelled networks. They discovered that at least 95% of nodes are correctly classified in 5 iterations." }, { "code": null, "e": 3330, "s": 3006, "text": "A priori number of clusters, cluster size, other metric not required. This is crucial if you don’t want to assume your graph has a certain structure or hierarchy. I had no a priori assumptions about the network structure of my web graph, the number of communities I had data for, or the expected sizes of these communities." }, { "code": null, "e": 3545, "s": 3330, "text": "Near linear runtime. Each iteration of LPA is O(m), linear in number of edges. The whole sequence of steps runs in near linear time, compared to O(n log n) or O(m+n) for some previous community detection solutions." }, { "code": null, "e": 3647, "s": 3545, "text": "Interpretability. When someone asks, you can explain why a node was grouped into a certain community." }, { "code": null, "e": 3857, "s": 3647, "text": "First, a quick and non-exhaustive breakdown of the tools landscape. I divided the tools based on graph size, whether the library plays nicely with Python, and how easily I could generate simple visualizations." }, { "code": null, "e": 3889, "s": 3857, "text": "A non-exhaustive menu of tools:" }, { "code": null, "e": 4175, "s": 3889, "text": "For data that fit onto a single machine, the networkx Python package is a good choice for easy-to-use graph exploration. It implements the most common algorithms (including label propagation, PageRank, maximum clique detection, and much more!). Simple visualizations are also possible." }, { "code": null, "e": 4455, "s": 4175, "text": "Gephi is an open graph analysis tool. Gephi isn’t a Python package, but a standalone tool with a robust UI and impressive graph visualization capabilities. If you are working with smaller graphs, need strong visualizations, and prefer a UI to working in Python, give Gephi a try." }, { "code": null, "e": 4897, "s": 4455, "text": "Spark has 2 graph libraries, GraphX and GraphFrames. Spark is a great solution when you have graph data too large to fit onto a single machine (limited to amount of resources allocated to your Spark application), want to take advantage of parallel processing, and some of Spark’s built-in fault tolerance features. Pyspark, Spark’s Python API, is nicely suited for integrating into other libraries like scikit-learn, matplotlib, or networkx." }, { "code": null, "e": 5226, "s": 4897, "text": "Apache Giraph is the open-source implementation of Pregel, a graph processing architecture created by Google. Giraph had a higher barrier to entry compared to the previous solutions. While Giraph is very powerful for large scale graph analysis deployments, I chose something more lightweight that had both Scala and Python APIs." }, { "code": null, "e": 5485, "s": 5226, "text": "Neo4j is a graph database system. It does have a Python client, though you have to install Neo4j separately. Since my analysis was only a POC, I wanted to avoid maintaining and deploying an entirely separate tool that did not integrate with my existing code." }, { "code": null, "e": 5988, "s": 5485, "text": "Finally, you could in theory implement your own solution. For initial data science exploration, I would discourage this. Many bespoke graph mining algorithms are for very specific use cases (for instance— be super efficient at graph clustering only, not other things). If you do need to work with very, very large datasets, first consider sampling your graph, filtering subgraphs of interest, inferring relationships from examples, basically anything to get more mileage from one of the existing tools." }, { "code": null, "e": 6055, "s": 5988, "text": "Given the data size I was working with, I chose Spark GraphFrames." }, { "code": null, "e": 6195, "s": 6055, "text": "Remember: the best graph library for your project depends on languages, graph size, how you store your graph data, and personal preference!" }, { "code": null, "e": 6344, "s": 6195, "text": "Great! I’m fully convinced how awesome graphs are, and they’re the coolest things ever! How do I get started using community detection on real data?" }, { "code": null, "e": 6349, "s": 6344, "text": "-you" }, { "code": null, "e": 6610, "s": 6349, "text": "1. Obtain data: The Common Crawl dataset is an open web crawl corpus well-suited for web graph research. The crawl results are stored in WARC (Web Archive) format. In addition to page contents, the dataset contains crawl date, headers used, and other metadata." }, { "code": null, "e": 6766, "s": 6610, "text": "I sampled 100 files from the September 2017 crawl. The file warc.paths.gz contains pathnames; using these pathnames, download the respective files from s3." }, { "code": null, "e": 6928, "s": 6766, "text": "2. Parse and clean data: As a first pass, we want the html content of each page. For each page, we collect the URL and the URLs of any links to create our graph." }, { "code": null, "e": 7304, "s": 6928, "text": "To extract edges from raw WARC files, I wrote some data cleaning code that probably should never see the light of day. At least it got the job done so I can focus on more fun things! My parsing code was written in Scala, but my demo is in pyspark. I used WarcReaderFactory and Jericho parser. For python, a library like warc looks like it could cover your data munging needs." }, { "code": null, "e": 7360, "s": 7304, "text": "After I had all the href links out of the html content," }, { "code": null, "e": 7562, "s": 7360, "text": "I drew edges between domains rather than full URLs. Instead of medium.com/foo/bar and medium.com/foobar, I only created one node, medium.com, that captured link relationships to and from other domains." }, { "code": null, "e": 7751, "s": 7562, "text": "I filtered out loops. Loops are edges that connect a node to itself, not useful for my purposes. No edges drawn if medium.com/foobar linked to same domain, say, medium.com/placeholderpage." }, { "code": null, "e": 7943, "s": 7751, "text": "I removed many of the most popular resource links, including popular CDNs, trackers, and assets. For my preliminary exploration, I only wanted to focus on webpages a human would likely visit." }, { "code": null, "e": 8258, "s": 7943, "text": "3. Initialize a Spark Context: For those following along at home, see demo at https://github.com/wsuen/pygotham2018_graphmining. This demo only runs on your local machine. You won’t get all the computational resources of a distributed cluster, but you will get an idea of how to get started with Spark GraphFrames." }, { "code": null, "e": 8435, "s": 8258, "text": "I’ll be working with Spark 2.3. Import pyspark and other needed libraries, including graphframes. Then create a SparkContext, which will allow you to run a pyspark application." }, { "code": null, "e": 8791, "s": 8435, "text": "# add GraphFrames package to spark-submitimport osos.environ['PYSPARK_SUBMIT_ARGS'] = '--packages graphframes:graphframes:0.6.0-spark2.3-s_2.11 pyspark-shell'import pyspark# create SparkContext and Spark Sessionsc = pyspark.SparkContext(\"local[*]\")spark = SparkSession.builder.appName('notebook').getOrCreate()# import GraphFramesfrom graphframes import *" }, { "code": null, "e": 8908, "s": 8791, "text": "4. Create a GraphFrame: Once you have your cleaned data, you can load your vertices and edges into Spark DataFrames." }, { "code": null, "e": 9000, "s": 8908, "text": "vertices contains an idfor each node, and the name of the node, which indicates the domain." }, { "code": null, "e": 9097, "s": 9000, "text": "edges contains my directed edges, from source domain src to the domain the source links to, dst." }, { "code": null, "e": 9619, "s": 9097, "text": "# show 10 nodesvertices.show(10)+--------+----------------+| id| name|+--------+----------------+|000db143| msn.com||51a48ea2|tradedoubler.com||31312317| microsoft.com||a45016f2| outlook.com||2f5bf4c8| bing.com|+--------+----------------+only showing top 5 rows# show 10 edgesedges.show(10)+--------+--------+| src| dst|+--------+--------+|000db143|51a48ea2||000db143|31312317||000db143|a45016f2||000db143|31312317||000db143|51a48ea2|+--------+--------+only showing top 5 rows" }, { "code": null, "e": 9714, "s": 9619, "text": "You can then create a GraphFrame object with your vertices and edges. Voila! You have a graph!" }, { "code": null, "e": 9769, "s": 9714, "text": "# create GraphFramegraph = GraphFrame(vertices, edges)" }, { "code": null, "e": 9870, "s": 9769, "text": "5. Running LPA: One line of code allows you to run LPA. Here, I run LPA with 5 iterations (maxIter)." }, { "code": null, "e": 10629, "s": 9870, "text": "# run LPA with 5 iterationscommunities = graph.labelPropagation(maxIter=5)communities.persist().show(10)+--------+--------------------+-------------+| id| name| label|+--------+--------------------+-------------+|407ae1cc| coop.no| 781684047881||1b0357be| buenacuerdo.com.ar|1245540515843||acc8136a| toptenreviews.com|1537598291986||abdd63cd| liberoquotidiano.it| 317827579915||db5c0434| meetme.com| 712964571162||0f8dff85| ameblo.jp| 171798691842||b6b04a58| tlnk.io|1632087572480||5bcfd421| wowhead.com| 429496729618||b4d4008d|investingcontrari...| 919123001350||ce7a3185| pokemoncentral.it|1511828488194|+--------+--------------------+-------------+only showing top 10 rows" }, { "code": null, "e": 11024, "s": 10629, "text": "Running graph.labelPropagation() returns a DataFrame with nodes and a label denoting which community that node belongs in. You can use label to understand distribution of community size and zoom in on areas of interest. For example, to discover every other website in the same community as pokemoncentral.it (and honestly, who wouldn’t?), filter for all other nodes where label = 1511828488194." }, { "code": null, "e": 11090, "s": 11024, "text": "What happened when I ran LPA on my sample Common Crawl web graph?" }, { "code": null, "e": 11303, "s": 11090, "text": "I began with over 15 million web sites in my raw data. That’s a lot of nodes, many of which contained redundant information. The cleaning process I described condensed the graph into fewer, more meaningful edges." }, { "code": null, "e": 11415, "s": 11303, "text": "LPA discovered over 4,700 communities. However, over half of these communities contained only one or two nodes." }, { "code": null, "e": 11603, "s": 11415, "text": "On the other end of the size spectrum, the largest community was over 3,500 different websites! To give an idea of scope, this was around 5% of the nodes in my final graph post-filtering." }, { "code": null, "e": 11982, "s": 11603, "text": "The extremes in community size illustrate one drawback of LPA. Too much convergence, and there could be clusters that are too large (caused by certain labels dominating densely connected networks). Too little convergence and you may get more, smaller communities that are less useful. I found that the most interesting clusters ended up being somewhere between the two extremes." }, { "code": null, "e": 12184, "s": 11982, "text": "In my dataset, LPA did converge around 5 iterations. You can see the number of communities level off at about 4,700. Raghavan and her colleagues showed this property with their labelled graphs as well." }, { "code": null, "e": 12681, "s": 12184, "text": "One possible mechanism that explains this is the small-world network effect — the tendency for graphs to cluster, but also to have short path lengths compared to number of nodes. In other words, although graphs have clusters, but you would also expect to be able to travel from, say, one friend to another in your network within 5–6 jumps. Many real-world graphs, including the Internet and social networks, share this property. You may also know this as the six degrees of separation phenomenon." }, { "code": null, "e": 12932, "s": 12681, "text": "At a coarse level, let’s see some samples clusters. As with traditional unsupervised clustering, the communities can be a mix of different sites, although there are topics of interest that we would not have discovered without LPA! From left to right:" }, { "code": null, "e": 13048, "s": 12932, "text": "E-learning sites: Sites related to or linking to e-learning pages. Time for me to find some new data science MOOCs!" }, { "code": null, "e": 13241, "s": 13048, "text": "Bedbug sites: Sites related to real estate and bed bugs. All these sites used the same template/images, just with slightly different domain names. Don’t think I ever got to the bottom of this." }, { "code": null, "e": 13357, "s": 13241, "text": "Star Wars community: Sites that talk about Star Wars movies, events, and memorabilia frequently link to each other." }, { "code": null, "e": 13642, "s": 13357, "text": "It’s worth emphasizing that we obtained this clusters without text processing and feature selection, manual labelling, domain name features, or even knowing how many communities to find. We found communities of interest by leveraging the underlying network structure of the web graph!" }, { "code": null, "e": 13770, "s": 13642, "text": "I’ve barely scratched the surface of web graph communities. There are so many directions future research could go. For example:" }, { "code": null, "e": 13953, "s": 13770, "text": "Layer in and propagate metadata: If we add information such as edge weights, link types, or external labels to the data, how well can we propagate this information through the graph?" }, { "code": null, "e": 14139, "s": 13953, "text": "Remove/add nodes and measure impact on communities: I’m curious how adding or taking away nodes of high edge centrality change effectiveness of LPA and quality of resulting communities." }, { "code": null, "e": 14372, "s": 14139, "text": "Observe web graph evolution over time: There is a new Common Crawl dataset each month! Would be interesting to see what clusters emerge over time. Conversely, what communities remain unchanged? As we know, the Internet isn’t static." }, { "code": null, "e": 14691, "s": 14372, "text": "The Github repo for the demo contains a small sample web graph of 10k nodes. There are also instructions for getting setup with Docker and running the pyspark notebooks. I hope this will be helpful in jump-starting experimentation with web graph data, and learning Spark GraphFrames for your own data science problems." }, { "code": null, "e": 14708, "s": 14691, "text": "Happy exploring!" }, { "code": null, "e": 14870, "s": 14708, "text": "Thanks to Dr. Yana Volkovich for deepening my learning of graph theory and being a great mentor. Thanks also to my other colleagues who gave feedback on my talk." } ]
Sentiment Classifier Using NLP in Python | by Shivangi Sareen | Towards Data Science
The aim is to train a supervised Stochastic Gradient Descent classifier on a training set containing reviews of movies from IMDB, with labels, 0 for a negative review and 1 for a positive review. We’ll use the trained model to predict the polarity of reviews in our testing set. We’ll be training the model using a unigram, bigram, unigram with tf-idf and bigram with tf-idf approach. Read onward to see what it’s all about! The dataset consists of 50,000 reviews from IMDB. Number of positive and negative reviews are equal, at 25k. Negative reviews have scores ≤ 4 out of 10 while a positive review ≥ 7 out of 10; neutral reviews are not included. The overall distribution of labels is balanced (25k pos and 25k neg). The dataset can be found here. There is also an additional 50,000 unlabelled documents for unsupervised learning, however, we will be focussing on supervised learning techniques here. There’s a train/ and test/ folder, each with pos/ and neg/ directories containing text files of reviews named named as [[id]_[rating].txt] where [id] is a unique id and [rating] is the rating corresponding to the review on a 1–10 scale. Focussing only on supervised learning, the unsup/ directories can be ignored. We’ll be using Python’s sci-kit learn library to train a Stochastic Gradient Descent classifier. In both SGD (Stochastic Gradient Descent) and GD (Gradient Descent), we update parameters iteratively to minimise the loss function. In GD, we run through the whole training data per epoch to update one set of parameters in a given iteration. On the other hand, SGD, as the name suggests (stochastic), randomly chooses only a single training example per epoch to update the parameter in a particular iteration. Mini-batch Gradient Descent lies in between GD and SGD where a small number of training samples (subset) are used per epoch. Here is a very helpful video and article on SGD. The aim is to train our SGD classifier on 25k training samples and then use that to predict the polarity (0 for negative review and 1 for positive review) of the test data. We’ll do some data preprocessing first — to combine the pos/ and neg/ data to create a training and testing file. Next we’ll do some data cleaning to get rid of any noise in the data. SGD has to be fitted with two arrays: an array X of shape (n_samples, n_features) holding the training samples, and an array y of shape (n_samples,) holding the target values (class labels) for the training samples. To convert our text data into such numerical form, we use Bag-of-Words models. “The bag-of-words model is commonly used in methods of document classification where the (frequency of) occurrence of each word is used as a feature for training a classifier.” [source] The most common type of feature extracted from the Bag-of-words model is term frequency, i.e., the number of times a term appears in the text. In our case of sentiment analysis, the more times a word like ‘dislike’, ‘hate’, ‘suck’, etc, the more likely its polarity be 0 (negative). And so this is how we’ll be training our model. In our case, each review is considered a documentEach document is split into words or tokensWe then assign a weight to each token as its frequency of appearance in the documentFinally, we create a document-term matrix representing exactly the above, of shape (n_samples, n_features) with each samples representing a documents and each features representing a the tokenised word In our case, each review is considered a document Each document is split into words or tokens We then assign a weight to each token as its frequency of appearance in the document Finally, we create a document-term matrix representing exactly the above, of shape (n_samples, n_features) with each samples representing a documents and each features representing a the tokenised word In BoW models, only the count of the words matter. As an alternative, we tend to look at n-gram models. An n-gram model considers the frequency of a word given the previous n-1 words have occurred. So instead of using the whole sequence of words in a sentence, we approximate using the last n-1 words. Let’s look at a uni-gram model. Here, the frequency of a word is irrespective of any other word. So this model simply corresponds to calculating the number of times each appears in the document. This is the most basic type of representation and does not take into account the context of any word. This unigram model fits into the BoW representation. We can also view this as a special case of the n-gram model with n=1. In the bi-gram model, we will be looking at n-1 = 1 past words. E.g. document: I love going swimming. The bi-gram model will split the whole document into units: (I, love), (love, going), (going, swimming), and store the term frequency of each unit as before. Sci-kit learn vectorizers are one of the most efficient ways to achieve the above document-term matrix steps, including specifying which n-gram model, all in one. They come in three forms: CountVectorizer: It counts the number of times a word shows up in the document and uses this value as its weight. HashingVectorizer: This serves the same purpose as CountVectorizer but is as memory efficient as possible. It uses a hashing trick to find the token string name to feature integer index mapping. Although there are cons with using this vectorizer over an in-memory implemented CountVectorizer. TfidfVectorizer: This is equivalent to CountVectorizer followed by TfidfTransformer. Tf-idf stands for term frequency-inverse document frequency. The tf-idf score of a word is the product of its tf and idf scores: the number of times a word appears in a document, and the inverse document frequency of the word across a set of documents. The whole idea is to weigh down the frequent terms while scaling up the rare ones. Tf-idf is one of the most popular term-weighting schemes today. Let’s get right into the code now. import csvimport reimport osfrom tqdm import tqdmfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import SGDClassifierfrom sklearn.metrics import accuracy_score The csv library in Python is used for CSV file reading and writing. We’ll be writing our data to a csv file and then reading from it The re library is for regex that is used for data cleaning The os library provides a portable way of using operating system dependent functionality tqdm instantly makes loops show a smart progress meter — just wrap any iterable with tqdm(iterable) CountVectorizer is used to convert a collection of text to a matrix of token counts TfidfVectorizer is used to convert a collection of text to a matrix of TF-IDF features SGDClassifier is fitted with two arrays: an array X of shape (n_samples, n_features) holding the training samples, and an array y of shape (n_samples,) holding the target values (class labels) for the training samples accuracy_score is used to calculate the accuracy of the model The below function is defined so as to create both test and training csv files. If train = True then it will use the training data path. If False, then it will use the path to the test data. In both train/ and test/ directories, there are pos/ and neg/ folders with .txt files containing the review. Each .txt file is read and then written to the respective training or test file. We are also including the polarity header for the test file to get the true values of the reviews that we will later compare with the predicted values. def create_csv_file(filename, train=True): header = ['row_number', 'text', 'polarity'] if train == True: path_to_pos = "aclImdb/train/pos/" path_to_neg = "aclImdb/train/neg/" else: path_to_pos = "aclImdb/test/pos/" path_to_neg = "aclImdb/test/neg/" count = 0 with open(filename, "w", newline = '') as f1: writer = csv.writer(f1, delimiter = ',') writer.writerow(header) for f in os.listdir(path_to_pos): polarity = 1 if f.endswith(".txt"): open_file = open(path_to_pos+f, "r") data = open_file.read() writer.writerow([count, f'"{data}"', polarity]) count += 1 open_file.close() for f in os.listdir(path_to_neg): polarity = 0 if f.endswith(".txt"): open_file = open(path_to_neg+f, "r") data = open_file.read() writer.writerow([count, f'"{data}"', polarity]) count += 1 open_file.close() We use the below function to create X_train (list of all the reviews) and y_train (the polarity label for each of the training reviews) from the training csv file. From the test csv file, we create X_test (list of all the reviews whose sentiment we want to predict) and the true polarities of the test review as y_test_true. def create_list_of_docs(filename): docs = [] polarity = [] with open(filename,'r') as csvfile: reader = csv.reader(csvfile, delimiter = ',') next(reader, None) #this skips the header row for row in tqdm(reader): docs.append(row[1]) polarity.append(row[2]) return docs, polarity The function remove_special_chars is used to clean up the data. The first regex sub removes html tags and everything in between them. The second regex sub removes anything but characters and a period. def remove_special_chars (strs): strs = re.sub(r'<.*?>', '', strs) strs = re.sub(r'[^a-zA-Z. ]', '', strs) return strs The function data_preprocess applies the function remove_special_chars to each row of a list of strings and replaces the original row with the cleaned string def data_preprocess(docs): for index, row in tqdm(enumerate(docs)): docs[index] = remove_special_chars(row) return docs Now let’s start using the above functions! First let’s call create_csv_file to create the training file. Let’s call it imdb_tr.csv. create_csv_file("imdb_tr.csv", train = True) Next, let’s create the test file called imdb_te.csv. create_csv_file("imdb_te.csv", train = False) Now, we’ll call the create_list_of_docs function on both imdb_tr.csv and imdb_te.csv. docs_train, y_train = create_list_of_docs("imdb_tr.csv")docs_test, y_test_true = create_list_of_docs("imdb_te.csv") docs_train is a list of all the reviews for training; docs_test contains the reviews for testing; y_train contains the polarity of the reviews in docs_train and y_test_true contains the true polarity of the reviews in docs_test. You’ll also notice the progress of the loop with the help of tqdm. Next, we’re going to clean the string reviews in docs_train and docs_test. docs_train = data_preprocess(docs_train)docs_test = data_preprocess(docs_test) We’ll also convert y_train and y_test_true to a list of integers as the polarity got appended as strings. y_train = list(map(int, y_train))y_test_true = list(map(int, y_test_true)) What about the stop-words you may ask? Read on to find out. We’ve got our data all ready now! Onto the classifier! As mentioned before, we’ll be using a stochastic gradient descent classifier, which requires an array X of shape (n_samples, n_features) holding the training samples, and an array y of shape (n_samples,) holding the target values (class labels) for the training samples. Recall in the above theory, we achieve numerical representation of our text data using Bag-of-Word models or n-grams. And sci-kit learn vectorizers help us do just that. We’ll be using CountVectorizer and TfidfVectorizer. The steps for both are the same. Initialise the vectorizer and give it certain parameters that we want- Initialise the vectorizer and give it certain parameters that we want- This is where we remove the stop-words — by declaring stop_words = 'english', a built-in stop word list for English is used. We can also create a custom stop-words list that can be used in place of 'english'. This only applies if analyzer == 'word'. lowercase = True is by default. It converts all characters to lowercase before tokenizing ngram_range = ngram_range : The lower and upper boundary of the range of n-values for different word n-grams to be extracted. For example an ngram_range of (1, 1) means only unigrams, (1, 2) means unigrams and bigrams, and (2, 2) means only bigrams. use_idf = True is only for TfidfVectorizer. It is True by default. This is to enable inverse-document-frequency re-weighting. 2. fit_transform on the training data learns the vocabulary dictionary and returns document-term matrix. Stored as X_train. 3. transform transforms the test data to the document-term matrix. Stored as X_test. Finally, we’ll initialise the SDGClassifier. I’ve given it a loss = "hinge" and penalty = "l1". The loss function defaults to 'hinge', which gives a linear SVM. The penalty is the regularization term to be used. It defaults to 'l2' which is the standard regularizer for linear SVM models. Next, we use the fit method on X_train and y_train to fit linear model with Stochastic Gradient Descent. And then we use the predict method to predict class labels for samples in X_test. The below function covers both TfidfVectorizer and CountVectorizer by using tfidf = True and tfidf = False respectively. def ngram_classifier (docs_train, y_train, docs_test, ngram_range, tfidf): if tfidf == True: tfidfvec = TfidfVectorizer(stop_words = "english", analyzer = 'word', lowercase = True, use_idf = True, ngram_range = ngram_range) X_train = tfidfvec.fit_transform(docs_train) X_test = tfidfvec.transform(docs_test) else: cvec = CountVectorizer(stop_words = "english", analyzer = 'word', lowercase = True, ngram_range = ngram_range) X_train = cvec.fit_transform(docs_train) X_test = cvec.transform(docs_test) clf = SGDClassifier(loss = "hinge", penalty = "l1") clf.fit(X_train, y_train) prediction = clf.predict(X_test) return prediction Finally, we’ll predict using different n-gram combinations and get the accuracy of the model. We get an accuracy of 83.6% for the below unigram without tfidf. y_pred_unigram = ngram_classifier(docs_train, y_train, docs_test, (1,1), tfidf = False)accuracy_score(y_test_true, y_pred_unigram) We get an accuracy of 84.04% for the below bigram without tfidf. y_pred_bigram = ngram_classifier(docs_train, y_train, docs_test, (1,2), tfidf = False)accuracy_score(y_test_true, y_pred_bigram) We get an accuracy of 86.94% for the below unigram with tfidf. y_pred_unigram_tfidf = ngram_classifier(docs_train, y_train, docs_test, (1,1), tfidf = True)accuracy_score(y_test_true, y_pred_unigram_tfidf) We get an accuracy of 85.77% for the below unigram with tfidf. y_pred_bigram_tfidf = ngram_classifier(docs_train, y_train, docs_test, (1,2), tfidf = True)accuracy_score(y_test_true, y_pred_bigram_tfidf) Tfidf scales down frequent words and scales up rarer ones. The tdfidf value of stop-words will be very low. So the argument is that do we really need to remove stop-words when using the TfidfVectorizer? The answer is yes. Even though stop-words removal may not help the unigram model (give it a try), in the higher n-gram models like bigrams and trigrams, it surely has an effect. Keeping the stop-words can create noise. There you have it! I highly recommend if you’re reading this, that you follow along in Jupyter Notebook just to see what the output looks like at each stage, from combining to create training and test data, to cleaning it, and finally getting the predictions. How about try and see how the above classifier be improved? There are many more parameters to TfidfVectorizer, CountVectorizer and the SGDClassifier. Also add some more steps to data preprocessing — use a lemmatizer and stemmer and see what the results are. Thank you for taking out the time to read this. Hope this helped!
[ { "code": null, "e": 597, "s": 172, "text": "The aim is to train a supervised Stochastic Gradient Descent classifier on a training set containing reviews of movies from IMDB, with labels, 0 for a negative review and 1 for a positive review. We’ll use the trained model to predict the polarity of reviews in our testing set. We’ll be training the model using a unigram, bigram, unigram with tf-idf and bigram with tf-idf approach. Read onward to see what it’s all about!" }, { "code": null, "e": 923, "s": 597, "text": "The dataset consists of 50,000 reviews from IMDB. Number of positive and negative reviews are equal, at 25k. Negative reviews have scores ≤ 4 out of 10 while a positive review ≥ 7 out of 10; neutral reviews are not included. The overall distribution of labels is balanced (25k pos and 25k neg). The dataset can be found here." }, { "code": null, "e": 1076, "s": 923, "text": "There is also an additional 50,000 unlabelled documents for unsupervised learning, however, we will be focussing on supervised learning techniques here." }, { "code": null, "e": 1313, "s": 1076, "text": "There’s a train/ and test/ folder, each with pos/ and neg/ directories containing text files of reviews named named as [[id]_[rating].txt] where [id] is a unique id and [rating] is the rating corresponding to the review on a 1–10 scale." }, { "code": null, "e": 1391, "s": 1313, "text": "Focussing only on supervised learning, the unsup/ directories can be ignored." }, { "code": null, "e": 1488, "s": 1391, "text": "We’ll be using Python’s sci-kit learn library to train a Stochastic Gradient Descent classifier." }, { "code": null, "e": 2024, "s": 1488, "text": "In both SGD (Stochastic Gradient Descent) and GD (Gradient Descent), we update parameters iteratively to minimise the loss function. In GD, we run through the whole training data per epoch to update one set of parameters in a given iteration. On the other hand, SGD, as the name suggests (stochastic), randomly chooses only a single training example per epoch to update the parameter in a particular iteration. Mini-batch Gradient Descent lies in between GD and SGD where a small number of training samples (subset) are used per epoch." }, { "code": null, "e": 2073, "s": 2024, "text": "Here is a very helpful video and article on SGD." }, { "code": null, "e": 2246, "s": 2073, "text": "The aim is to train our SGD classifier on 25k training samples and then use that to predict the polarity (0 for negative review and 1 for positive review) of the test data." }, { "code": null, "e": 2430, "s": 2246, "text": "We’ll do some data preprocessing first — to combine the pos/ and neg/ data to create a training and testing file. Next we’ll do some data cleaning to get rid of any noise in the data." }, { "code": null, "e": 2646, "s": 2430, "text": "SGD has to be fitted with two arrays: an array X of shape (n_samples, n_features) holding the training samples, and an array y of shape (n_samples,) holding the target values (class labels) for the training samples." }, { "code": null, "e": 2725, "s": 2646, "text": "To convert our text data into such numerical form, we use Bag-of-Words models." }, { "code": null, "e": 2911, "s": 2725, "text": "“The bag-of-words model is commonly used in methods of document classification where the (frequency of) occurrence of each word is used as a feature for training a classifier.” [source]" }, { "code": null, "e": 3242, "s": 2911, "text": "The most common type of feature extracted from the Bag-of-words model is term frequency, i.e., the number of times a term appears in the text. In our case of sentiment analysis, the more times a word like ‘dislike’, ‘hate’, ‘suck’, etc, the more likely its polarity be 0 (negative). And so this is how we’ll be training our model." }, { "code": null, "e": 3620, "s": 3242, "text": "In our case, each review is considered a documentEach document is split into words or tokensWe then assign a weight to each token as its frequency of appearance in the documentFinally, we create a document-term matrix representing exactly the above, of shape (n_samples, n_features) with each samples representing a documents and each features representing a the tokenised word" }, { "code": null, "e": 3670, "s": 3620, "text": "In our case, each review is considered a document" }, { "code": null, "e": 3714, "s": 3670, "text": "Each document is split into words or tokens" }, { "code": null, "e": 3799, "s": 3714, "text": "We then assign a weight to each token as its frequency of appearance in the document" }, { "code": null, "e": 4001, "s": 3799, "text": "Finally, we create a document-term matrix representing exactly the above, of shape (n_samples, n_features) with each samples representing a documents and each features representing a the tokenised word" }, { "code": null, "e": 4105, "s": 4001, "text": "In BoW models, only the count of the words matter. As an alternative, we tend to look at n-gram models." }, { "code": null, "e": 4303, "s": 4105, "text": "An n-gram model considers the frequency of a word given the previous n-1 words have occurred. So instead of using the whole sequence of words in a sentence, we approximate using the last n-1 words." }, { "code": null, "e": 4723, "s": 4303, "text": "Let’s look at a uni-gram model. Here, the frequency of a word is irrespective of any other word. So this model simply corresponds to calculating the number of times each appears in the document. This is the most basic type of representation and does not take into account the context of any word. This unigram model fits into the BoW representation. We can also view this as a special case of the n-gram model with n=1." }, { "code": null, "e": 4787, "s": 4723, "text": "In the bi-gram model, we will be looking at n-1 = 1 past words." }, { "code": null, "e": 4983, "s": 4787, "text": "E.g. document: I love going swimming. The bi-gram model will split the whole document into units: (I, love), (love, going), (going, swimming), and store the term frequency of each unit as before." }, { "code": null, "e": 5172, "s": 4983, "text": "Sci-kit learn vectorizers are one of the most efficient ways to achieve the above document-term matrix steps, including specifying which n-gram model, all in one. They come in three forms:" }, { "code": null, "e": 5286, "s": 5172, "text": "CountVectorizer: It counts the number of times a word shows up in the document and uses this value as its weight." }, { "code": null, "e": 5579, "s": 5286, "text": "HashingVectorizer: This serves the same purpose as CountVectorizer but is as memory efficient as possible. It uses a hashing trick to find the token string name to feature integer index mapping. Although there are cons with using this vectorizer over an in-memory implemented CountVectorizer." }, { "code": null, "e": 6064, "s": 5579, "text": "TfidfVectorizer: This is equivalent to CountVectorizer followed by TfidfTransformer. Tf-idf stands for term frequency-inverse document frequency. The tf-idf score of a word is the product of its tf and idf scores: the number of times a word appears in a document, and the inverse document frequency of the word across a set of documents. The whole idea is to weigh down the frequent terms while scaling up the rare ones. Tf-idf is one of the most popular term-weighting schemes today." }, { "code": null, "e": 6099, "s": 6064, "text": "Let’s get right into the code now." }, { "code": null, "e": 6355, "s": 6099, "text": "import csvimport reimport osfrom tqdm import tqdmfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.linear_model import SGDClassifierfrom sklearn.metrics import accuracy_score" }, { "code": null, "e": 6488, "s": 6355, "text": "The csv library in Python is used for CSV file reading and writing. We’ll be writing our data to a csv file and then reading from it" }, { "code": null, "e": 6547, "s": 6488, "text": "The re library is for regex that is used for data cleaning" }, { "code": null, "e": 6636, "s": 6547, "text": "The os library provides a portable way of using operating system dependent functionality" }, { "code": null, "e": 6736, "s": 6636, "text": "tqdm instantly makes loops show a smart progress meter — just wrap any iterable with tqdm(iterable)" }, { "code": null, "e": 6820, "s": 6736, "text": "CountVectorizer is used to convert a collection of text to a matrix of token counts" }, { "code": null, "e": 6907, "s": 6820, "text": "TfidfVectorizer is used to convert a collection of text to a matrix of TF-IDF features" }, { "code": null, "e": 7125, "s": 6907, "text": "SGDClassifier is fitted with two arrays: an array X of shape (n_samples, n_features) holding the training samples, and an array y of shape (n_samples,) holding the target values (class labels) for the training samples" }, { "code": null, "e": 7187, "s": 7125, "text": "accuracy_score is used to calculate the accuracy of the model" }, { "code": null, "e": 7378, "s": 7187, "text": "The below function is defined so as to create both test and training csv files. If train = True then it will use the training data path. If False, then it will use the path to the test data." }, { "code": null, "e": 7487, "s": 7378, "text": "In both train/ and test/ directories, there are pos/ and neg/ folders with .txt files containing the review." }, { "code": null, "e": 7720, "s": 7487, "text": "Each .txt file is read and then written to the respective training or test file. We are also including the polarity header for the test file to get the true values of the reviews that we will later compare with the predicted values." }, { "code": null, "e": 8791, "s": 7720, "text": "def create_csv_file(filename, train=True): header = ['row_number', 'text', 'polarity'] if train == True: path_to_pos = \"aclImdb/train/pos/\" path_to_neg = \"aclImdb/train/neg/\" else: path_to_pos = \"aclImdb/test/pos/\" path_to_neg = \"aclImdb/test/neg/\" count = 0 with open(filename, \"w\", newline = '') as f1: writer = csv.writer(f1, delimiter = ',') writer.writerow(header) for f in os.listdir(path_to_pos): polarity = 1 if f.endswith(\".txt\"): open_file = open(path_to_pos+f, \"r\") data = open_file.read() writer.writerow([count, f'\"{data}\"', polarity]) count += 1 open_file.close() for f in os.listdir(path_to_neg): polarity = 0 if f.endswith(\".txt\"): open_file = open(path_to_neg+f, \"r\") data = open_file.read() writer.writerow([count, f'\"{data}\"', polarity]) count += 1 open_file.close()" }, { "code": null, "e": 9116, "s": 8791, "text": "We use the below function to create X_train (list of all the reviews) and y_train (the polarity label for each of the training reviews) from the training csv file. From the test csv file, we create X_test (list of all the reviews whose sentiment we want to predict) and the true polarities of the test review as y_test_true." }, { "code": null, "e": 9469, "s": 9116, "text": "def create_list_of_docs(filename): docs = [] polarity = [] with open(filename,'r') as csvfile: reader = csv.reader(csvfile, delimiter = ',') next(reader, None) #this skips the header row for row in tqdm(reader): docs.append(row[1]) polarity.append(row[2]) return docs, polarity" }, { "code": null, "e": 9670, "s": 9469, "text": "The function remove_special_chars is used to clean up the data. The first regex sub removes html tags and everything in between them. The second regex sub removes anything but characters and a period." }, { "code": null, "e": 9803, "s": 9670, "text": "def remove_special_chars (strs): strs = re.sub(r'<.*?>', '', strs) strs = re.sub(r'[^a-zA-Z. ]', '', strs) return strs" }, { "code": null, "e": 9961, "s": 9803, "text": "The function data_preprocess applies the function remove_special_chars to each row of a list of strings and replaces the original row with the cleaned string" }, { "code": null, "e": 10094, "s": 9961, "text": "def data_preprocess(docs): for index, row in tqdm(enumerate(docs)): docs[index] = remove_special_chars(row) return docs" }, { "code": null, "e": 10137, "s": 10094, "text": "Now let’s start using the above functions!" }, { "code": null, "e": 10226, "s": 10137, "text": "First let’s call create_csv_file to create the training file. Let’s call it imdb_tr.csv." }, { "code": null, "e": 10271, "s": 10226, "text": "create_csv_file(\"imdb_tr.csv\", train = True)" }, { "code": null, "e": 10324, "s": 10271, "text": "Next, let’s create the test file called imdb_te.csv." }, { "code": null, "e": 10370, "s": 10324, "text": "create_csv_file(\"imdb_te.csv\", train = False)" }, { "code": null, "e": 10456, "s": 10370, "text": "Now, we’ll call the create_list_of_docs function on both imdb_tr.csv and imdb_te.csv." }, { "code": null, "e": 10572, "s": 10456, "text": "docs_train, y_train = create_list_of_docs(\"imdb_tr.csv\")docs_test, y_test_true = create_list_of_docs(\"imdb_te.csv\")" }, { "code": null, "e": 10801, "s": 10572, "text": "docs_train is a list of all the reviews for training; docs_test contains the reviews for testing; y_train contains the polarity of the reviews in docs_train and y_test_true contains the true polarity of the reviews in docs_test." }, { "code": null, "e": 10868, "s": 10801, "text": "You’ll also notice the progress of the loop with the help of tqdm." }, { "code": null, "e": 10943, "s": 10868, "text": "Next, we’re going to clean the string reviews in docs_train and docs_test." }, { "code": null, "e": 11022, "s": 10943, "text": "docs_train = data_preprocess(docs_train)docs_test = data_preprocess(docs_test)" }, { "code": null, "e": 11128, "s": 11022, "text": "We’ll also convert y_train and y_test_true to a list of integers as the polarity got appended as strings." }, { "code": null, "e": 11203, "s": 11128, "text": "y_train = list(map(int, y_train))y_test_true = list(map(int, y_test_true))" }, { "code": null, "e": 11263, "s": 11203, "text": "What about the stop-words you may ask? Read on to find out." }, { "code": null, "e": 11318, "s": 11263, "text": "We’ve got our data all ready now! Onto the classifier!" }, { "code": null, "e": 11589, "s": 11318, "text": "As mentioned before, we’ll be using a stochastic gradient descent classifier, which requires an array X of shape (n_samples, n_features) holding the training samples, and an array y of shape (n_samples,) holding the target values (class labels) for the training samples." }, { "code": null, "e": 11759, "s": 11589, "text": "Recall in the above theory, we achieve numerical representation of our text data using Bag-of-Word models or n-grams. And sci-kit learn vectorizers help us do just that." }, { "code": null, "e": 11844, "s": 11759, "text": "We’ll be using CountVectorizer and TfidfVectorizer. The steps for both are the same." }, { "code": null, "e": 11915, "s": 11844, "text": "Initialise the vectorizer and give it certain parameters that we want-" }, { "code": null, "e": 11986, "s": 11915, "text": "Initialise the vectorizer and give it certain parameters that we want-" }, { "code": null, "e": 12236, "s": 11986, "text": "This is where we remove the stop-words — by declaring stop_words = 'english', a built-in stop word list for English is used. We can also create a custom stop-words list that can be used in place of 'english'. This only applies if analyzer == 'word'." }, { "code": null, "e": 12326, "s": 12236, "text": "lowercase = True is by default. It converts all characters to lowercase before tokenizing" }, { "code": null, "e": 12576, "s": 12326, "text": "ngram_range = ngram_range : The lower and upper boundary of the range of n-values for different word n-grams to be extracted. For example an ngram_range of (1, 1) means only unigrams, (1, 2) means unigrams and bigrams, and (2, 2) means only bigrams." }, { "code": null, "e": 12702, "s": 12576, "text": "use_idf = True is only for TfidfVectorizer. It is True by default. This is to enable inverse-document-frequency re-weighting." }, { "code": null, "e": 12826, "s": 12702, "text": "2. fit_transform on the training data learns the vocabulary dictionary and returns document-term matrix. Stored as X_train." }, { "code": null, "e": 12911, "s": 12826, "text": "3. transform transforms the test data to the document-term matrix. Stored as X_test." }, { "code": null, "e": 13007, "s": 12911, "text": "Finally, we’ll initialise the SDGClassifier. I’ve given it a loss = \"hinge\" and penalty = \"l1\"." }, { "code": null, "e": 13072, "s": 13007, "text": "The loss function defaults to 'hinge', which gives a linear SVM." }, { "code": null, "e": 13200, "s": 13072, "text": "The penalty is the regularization term to be used. It defaults to 'l2' which is the standard regularizer for linear SVM models." }, { "code": null, "e": 13305, "s": 13200, "text": "Next, we use the fit method on X_train and y_train to fit linear model with Stochastic Gradient Descent." }, { "code": null, "e": 13387, "s": 13305, "text": "And then we use the predict method to predict class labels for samples in X_test." }, { "code": null, "e": 13508, "s": 13387, "text": "The below function covers both TfidfVectorizer and CountVectorizer by using tfidf = True and tfidf = False respectively." }, { "code": null, "e": 14484, "s": 13508, "text": "def ngram_classifier (docs_train, y_train, docs_test, ngram_range, tfidf): if tfidf == True: tfidfvec = TfidfVectorizer(stop_words = \"english\", analyzer = 'word', lowercase = True, use_idf = True, ngram_range = ngram_range) X_train = tfidfvec.fit_transform(docs_train) X_test = tfidfvec.transform(docs_test) else: cvec = CountVectorizer(stop_words = \"english\", analyzer = 'word', lowercase = True, ngram_range = ngram_range) X_train = cvec.fit_transform(docs_train) X_test = cvec.transform(docs_test) clf = SGDClassifier(loss = \"hinge\", penalty = \"l1\") clf.fit(X_train, y_train) prediction = clf.predict(X_test) return prediction" }, { "code": null, "e": 14578, "s": 14484, "text": "Finally, we’ll predict using different n-gram combinations and get the accuracy of the model." }, { "code": null, "e": 14643, "s": 14578, "text": "We get an accuracy of 83.6% for the below unigram without tfidf." }, { "code": null, "e": 14909, "s": 14643, "text": "y_pred_unigram = ngram_classifier(docs_train, y_train, docs_test, (1,1), tfidf = False)accuracy_score(y_test_true, y_pred_unigram)" }, { "code": null, "e": 14974, "s": 14909, "text": "We get an accuracy of 84.04% for the below bigram without tfidf." }, { "code": null, "e": 15235, "s": 14974, "text": "y_pred_bigram = ngram_classifier(docs_train, y_train, docs_test, (1,2), tfidf = False)accuracy_score(y_test_true, y_pred_bigram)" }, { "code": null, "e": 15298, "s": 15235, "text": "We get an accuracy of 86.94% for the below unigram with tfidf." }, { "code": null, "e": 15600, "s": 15298, "text": "y_pred_unigram_tfidf = ngram_classifier(docs_train, y_train, docs_test, (1,1), tfidf = True)accuracy_score(y_test_true, y_pred_unigram_tfidf)" }, { "code": null, "e": 15663, "s": 15600, "text": "We get an accuracy of 85.77% for the below unigram with tfidf." }, { "code": null, "e": 15959, "s": 15663, "text": "y_pred_bigram_tfidf = ngram_classifier(docs_train, y_train, docs_test, (1,2), tfidf = True)accuracy_score(y_test_true, y_pred_bigram_tfidf)" }, { "code": null, "e": 16381, "s": 15959, "text": "Tfidf scales down frequent words and scales up rarer ones. The tdfidf value of stop-words will be very low. So the argument is that do we really need to remove stop-words when using the TfidfVectorizer? The answer is yes. Even though stop-words removal may not help the unigram model (give it a try), in the higher n-gram models like bigrams and trigrams, it surely has an effect. Keeping the stop-words can create noise." }, { "code": null, "e": 16641, "s": 16381, "text": "There you have it! I highly recommend if you’re reading this, that you follow along in Jupyter Notebook just to see what the output looks like at each stage, from combining to create training and test data, to cleaning it, and finally getting the predictions." }, { "code": null, "e": 16899, "s": 16641, "text": "How about try and see how the above classifier be improved? There are many more parameters to TfidfVectorizer, CountVectorizer and the SGDClassifier. Also add some more steps to data preprocessing — use a lemmatizer and stemmer and see what the results are." } ]
How to create a speed converter with HTML and JavaScript?
To create a speed converter with HTML and JavaScript, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } input, span { font-size: 20px; } </style> </head> <body> <h1>Speed Converter</h1> <h2>Type speed in Kilometer per hour to convert it into meter per hour</h2> <p> <label>Kilometer Per Hour</label> <input id="inputKm" type="number" placeholder="KilometersPerHour" oninput="KmphtoMphConverter(this.value)" onchange="KmphtoMphConverter(this.value)"/> </p> <p>Meters Per second: <span class="metersPerSecond"></span></p> <script> function KmphtoMphConverter(speed) { document.querySelector(".metersPerSecond").innerHTML = speed * 0.277778; } </script> </body> </html> The above code will produce the following output − On entering some speed in kph −
[ { "code": null, "e": 1141, "s": 1062, "text": "To create a speed converter with HTML and JavaScript, the code is as follows −" }, { "code": null, "e": 1152, "s": 1141, "text": " Live Demo" }, { "code": null, "e": 1860, "s": 1152, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n input, span {\n font-size: 20px;\n }\n</style>\n</head>\n<body>\n<h1>Speed Converter</h1>\n<h2>Type speed in Kilometer per hour to convert it into meter per hour</h2>\n<p>\n<label>Kilometer Per Hour</label>\n<input\nid=\"inputKm\"\ntype=\"number\"\nplaceholder=\"KilometersPerHour\"\noninput=\"KmphtoMphConverter(this.value)\"\nonchange=\"KmphtoMphConverter(this.value)\"/>\n</p>\n<p>Meters Per second: <span class=\"metersPerSecond\"></span></p>\n<script>\n function KmphtoMphConverter(speed) {\n document.querySelector(\".metersPerSecond\").innerHTML = speed * 0.277778;\n }\n</script>\n</body>\n</html>" }, { "code": null, "e": 1911, "s": 1860, "text": "The above code will produce the following output −" }, { "code": null, "e": 1943, "s": 1911, "text": "On entering some speed in kph −" } ]
How can we create and use ENUM columns in MySQL?
For creating an ENUM column, the enumeration value must be a quoted string literals. We can create ENUM columns in MySQL with the help of the following syntax − CREATE TABLE table_name( ... Col ENUM(‘Value1’,’Value2’,’Value3’), ... ); In the above syntax, we have three enumeration values. It can be more than three also. Following is an example of creating a table with ENUM column − mysql> Create table marks(id int Primary key NOT NULL, Name Varchar(255) NOT NULL, Result ENUM('Pass', 'Fail') NOT NULL); Query OK, 0 rows affected (0.18 sec) The query above will create a table named marks with an ENUM field. mysql> Insert into marks(id, name, result) values(101,'Aarav','Pass'); Query OK, 1 row affected (0.07 sec) mysql> Insert into marks(id, name, result) values(102,'Yashraj','Fail'); Query OK, 1 row affected (0.02 sec) With the help of queries above we can insert the values in the table. mysql> Select * from marks; +-----+---------+--------+ | id | Name | Result | +-----+---------+--------+ | 101 | Aarav | Pass | | 102 | Yashraj | Fail | +-----+---------+--------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1223, "s": 1062, "text": "For creating an ENUM column, the enumeration value must be a quoted string literals. We can create ENUM columns in MySQL with the help of the following syntax −" }, { "code": null, "e": 1306, "s": 1223, "text": "CREATE TABLE table_name(\n ...\n Col ENUM(‘Value1’,’Value2’,’Value3’),\n ...\n);" }, { "code": null, "e": 1393, "s": 1306, "text": "In the above syntax, we have three enumeration values. It can be more than three also." }, { "code": null, "e": 1457, "s": 1393, "text": " Following is an example of creating a table with ENUM column −" }, { "code": null, "e": 1616, "s": 1457, "text": "mysql> Create table marks(id int Primary key NOT NULL, Name Varchar(255) NOT NULL, Result ENUM('Pass', 'Fail') NOT NULL);\nQuery OK, 0 rows affected (0.18 sec)" }, { "code": null, "e": 1684, "s": 1616, "text": "The query above will create a table named marks with an ENUM field." }, { "code": null, "e": 1901, "s": 1684, "text": "mysql> Insert into marks(id, name, result) values(101,'Aarav','Pass');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> Insert into marks(id, name, result) values(102,'Yashraj','Fail');\nQuery OK, 1 row affected (0.02 sec)" }, { "code": null, "e": 1971, "s": 1901, "text": "With the help of queries above we can insert the values in the table." }, { "code": null, "e": 2186, "s": 1971, "text": "mysql> Select * from marks;\n+-----+---------+--------+\n| id | Name | Result |\n+-----+---------+--------+\n| 101 | Aarav | Pass |\n| 102 | Yashraj | Fail |\n+-----+---------+--------+\n2 rows in set (0.00 sec)" } ]
PyQt5 – How to align Text of Label - GeeksforGeeks
17 Jan, 2022 In this article, we will see how we can align text of labels in PyQt5 application, we can align text in three different ways which are left, right and Center.Syntax : label.setAlignment(QtCore.Qt.AlignLeft) label.setAlignment(QtCore.Qt.AlignCenter) label.setAlignment(QtCore.Qt.AlignRight) In order to use use this we have to import Qtcore from PyQt5 from PyQt5 import QtCore Below is the implementation : Python3 # importing the required libraries from PyQt5.QtWidgets import *from PyQt5 import QtCorefrom PyQt5.QtGui import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Label") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel('Left', self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet("border: 1px solid black;") # setting alignment to left self.label_1.setAlignment(QtCore.Qt.AlignLeft) # creating a label widget self.label_2 = QLabel('Center', self) # moving position self.label_2.move(100, 130) # setting up border self.label_2.setStyleSheet("border: 1px solid black;") # setting alignment to center self.label_2.setAlignment(QtCore.Qt.AlignCenter) # creating a label widget self.label_3 = QLabel('Right', self) # moving position self.label_3.move(100, 160) # setting up border self.label_3.setStyleSheet("border: 1px solid black;") # setting alignment to right self.label_3.setAlignment(QtCore.Qt.AlignRight) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : sagartomar9927 Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24517, "s": 24489, "text": "\n17 Jan, 2022" }, { "code": null, "e": 24686, "s": 24517, "text": "In this article, we will see how we can align text of labels in PyQt5 application, we can align text in three different ways which are left, right and Center.Syntax : " }, { "code": null, "e": 24809, "s": 24686, "text": "label.setAlignment(QtCore.Qt.AlignLeft)\nlabel.setAlignment(QtCore.Qt.AlignCenter)\nlabel.setAlignment(QtCore.Qt.AlignRight)" }, { "code": null, "e": 24872, "s": 24809, "text": "In order to use use this we have to import Qtcore from PyQt5 " }, { "code": null, "e": 24897, "s": 24872, "text": "from PyQt5 import QtCore" }, { "code": null, "e": 24928, "s": 24897, "text": "Below is the implementation : " }, { "code": null, "e": 24936, "s": 24928, "text": "Python3" }, { "code": "# importing the required libraries from PyQt5.QtWidgets import *from PyQt5 import QtCorefrom PyQt5.QtGui import *import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Label\") # setting the geometry of window self.setGeometry(0, 0, 400, 300) # creating a label widget self.label_1 = QLabel('Left', self) # moving position self.label_1.move(100, 100) # setting up border self.label_1.setStyleSheet(\"border: 1px solid black;\") # setting alignment to left self.label_1.setAlignment(QtCore.Qt.AlignLeft) # creating a label widget self.label_2 = QLabel('Center', self) # moving position self.label_2.move(100, 130) # setting up border self.label_2.setStyleSheet(\"border: 1px solid black;\") # setting alignment to center self.label_2.setAlignment(QtCore.Qt.AlignCenter) # creating a label widget self.label_3 = QLabel('Right', self) # moving position self.label_3.move(100, 160) # setting up border self.label_3.setStyleSheet(\"border: 1px solid black;\") # setting alignment to right self.label_3.setAlignment(QtCore.Qt.AlignRight) # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 26429, "s": 24936, "text": null }, { "code": null, "e": 26440, "s": 26429, "text": "Output : " }, { "code": null, "e": 26457, "s": 26442, "text": "sagartomar9927" }, { "code": null, "e": 26468, "s": 26457, "text": "Python-gui" }, { "code": null, "e": 26480, "s": 26468, "text": "Python-PyQt" }, { "code": null, "e": 26487, "s": 26480, "text": "Python" }, { "code": null, "e": 26585, "s": 26487, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26594, "s": 26585, "text": "Comments" }, { "code": null, "e": 26607, "s": 26594, "text": "Old Comments" }, { "code": null, "e": 26625, "s": 26607, "text": "Python Dictionary" }, { "code": null, "e": 26660, "s": 26625, "text": "Read a file line by line in Python" }, { "code": null, "e": 26682, "s": 26660, "text": "Enumerate() in Python" }, { "code": null, "e": 26714, "s": 26682, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26744, "s": 26714, "text": "Iterate over a list in Python" }, { "code": null, "e": 26786, "s": 26744, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26812, "s": 26786, "text": "Python String | replace()" }, { "code": null, "e": 26855, "s": 26812, "text": "Python program to convert a list to string" }, { "code": null, "e": 26899, "s": 26855, "text": "Reading and Writing to text files in Python" } ]
Java Examples - Method Overloading
How to overload methods ? This example displays the way of overloading a method depending on type and number of parameters. class MyClass { int height; MyClass() { System.out.println("bricks"); height = 0; } MyClass(int i) { System.out.println("Building new House that is " + i + " feet tall"); height = i; } void info() { System.out.println("House is " + height + " feet tall"); } void info(String s) { System.out.println(s + ": House is " + height + " feet tall"); } } public class MainClass { public static void main(String[] args) { MyClass t = new MyClass(0); t.info(); t.info("overloaded method"); //Overloaded constructor: new MyClass(); } } The above code sample will produce the following result. Building new House that is 0 feet tall. House is 0 feet tall. Overloaded method: House is 0 feet tall. bricks The following is an another sample example of Method Overloading public class Calculation { void sum(int a,int b){System.out.println(a+b);} void sum(int a,int b,int c){System.out.println(a+b+c);} public static void main(String args[]){ Calculation cal = new Calculation(); cal.sum(20,30,60); cal.sum(20,20); } } The above code sample will produce the following result. 110 40 Print Add Notes Bookmark this page
[ { "code": null, "e": 2094, "s": 2068, "text": "How to overload methods ?" }, { "code": null, "e": 2192, "s": 2094, "text": "This example displays the way of overloading a method depending on type and number of parameters." }, { "code": null, "e": 2823, "s": 2192, "text": "class MyClass {\n int height;\n MyClass() {\n System.out.println(\"bricks\");\n height = 0;\n }\n MyClass(int i) {\n System.out.println(\"Building new House that is \" + i + \" feet tall\");\n height = i;\n }\n void info() {\n System.out.println(\"House is \" + height + \" feet tall\");\n }\n void info(String s) {\n System.out.println(s + \": House is \" + height + \" feet tall\");\n }\n}\npublic class MainClass {\n public static void main(String[] args) {\n MyClass t = new MyClass(0);\n t.info();\n t.info(\"overloaded method\");\n \n //Overloaded constructor:\n new MyClass();\n }\n}" }, { "code": null, "e": 2880, "s": 2823, "text": "The above code sample will produce the following result." }, { "code": null, "e": 2992, "s": 2880, "text": "Building new House that is 0 feet tall.\nHouse is 0 feet tall.\nOverloaded method: House is 0 feet tall.\nbricks\n" }, { "code": null, "e": 3057, "s": 2992, "text": "The following is an another sample example of Method Overloading" }, { "code": null, "e": 3335, "s": 3057, "text": "public class Calculation {\n void sum(int a,int b){System.out.println(a+b);}\n void sum(int a,int b,int c){System.out.println(a+b+c);}\n\n public static void main(String args[]){\n Calculation cal = new Calculation();\n cal.sum(20,30,60);\n cal.sum(20,20);\n }\n}" }, { "code": null, "e": 3392, "s": 3335, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3400, "s": 3392, "text": "110\n40\n" }, { "code": null, "e": 3407, "s": 3400, "text": " Print" }, { "code": null, "e": 3418, "s": 3407, "text": " Add Notes" } ]
All possible strings of any length that can be formed from a given string?
In this section we will see how to generate all possible strings of any length, this will take each combination of characters to make string. For example, if the string is ABC, then it will generate − {A, B, C, AB, BA, BC, CB, CA, AC, ABC, ACB, BAC, BCA, CAB, CBA} Let us see the example to get the idea. Begin n := length of the string str count is 2^n – 1 for each number 0 to count, do sub_str := empty string for j in range 0 to n, do if jth bit of the counter is set, then concatenate jth character of str with sub_str end if done repeat: print sub_string until next permutation of sub_string is not completed done End #include <iostream> #include <algorithm> #include <cmath> using namespace std; void printAllString(string str) { int n = str.size(); unsigned int count = pow(2, n); for (int counter = 1; counter <count; counter++) { //generate 2^n - 1 strings string subs = ""; for (int j = 0; j < n; j++) { if (counter & (1<<j)) //when the jth bit is set, then add jth character subs.push_back(str[j]); } do{ cout << subs << endl; } while (next_permutation(subs.begin(), subs.end())); } } A B AB BA C AC CA BC CB ABC ACB BAC BCA CAB CBA D AD DA BD DB ABD ADB BAD BDA DAB DBA CD DC ACD ADC CAD CDA DAC DCA BCD BDC CBD CDB DBC DCB ABCD ABDC ACBD ACDB ADBC ADCB BACD BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB CDBA DABC DACB DBAC DBCA DCAB DCBA
[ { "code": null, "e": 1327, "s": 1062, "text": "In this section we will see how to generate all possible strings of any length, this will take each combination of characters to make string. For example, if the string is ABC, then it will generate − {A, B, C, AB, BA, BC, CB, CA, AC, ABC, ACB, BAC, BCA, CAB, CBA}" }, { "code": null, "e": 1367, "s": 1327, "text": "Let us see the example to get the idea." }, { "code": null, "e": 1767, "s": 1367, "text": "Begin\n n := length of the string str\n count is 2^n – 1\n for each number 0 to count, do\n sub_str := empty string\n for j in range 0 to n, do\n if jth bit of the counter is set, then\n concatenate jth character of str with sub_str\n end if\n done\n repeat:\n print sub_string\n until next permutation of sub_string is not completed\n done\nEnd" }, { "code": null, "e": 2318, "s": 1767, "text": "#include <iostream>\n#include <algorithm>\n#include <cmath>\nusing namespace std;\nvoid printAllString(string str) {\n int n = str.size();\n unsigned int count = pow(2, n);\n for (int counter = 1; counter <count; counter++) { //generate 2^n - 1 strings\n string subs = \"\";\n for (int j = 0; j < n; j++) {\n if (counter & (1<<j)) //when the jth bit is set, then add jth character\n subs.push_back(str[j]);\n }\n do{\n cout << subs << endl;\n }\n while (next_permutation(subs.begin(), subs.end()));\n }\n}" }, { "code": null, "e": 2578, "s": 2318, "text": "A\nB\nAB\nBA\nC\nAC\nCA\nBC\nCB\nABC\nACB\nBAC\nBCA\nCAB\nCBA\nD\nAD\nDA\nBD\nDB\nABD\nADB\nBAD\nBDA\nDAB\nDBA\nCD\nDC\nACD\nADC\nCAD\nCDA\nDAC\nDCA\nBCD\nBDC\nCBD\nCDB\nDBC\nDCB\nABCD\nABDC\nACBD\nACDB\nADBC\nADCB\nBACD\nBADC\nBCAD\nBCDA\nBDAC\nBDCA\nCABD\nCADB\nCBAD\nCBDA\nCDAB\nCDBA\nDABC\nDACB\nDBAC\nDBCA\nDCAB\nDCBA" } ]
Grant a user permission to only view a MySQL view?
To grant a user permission to only view a MySQL view, use the below syntax GRANT SELECT ON yourDatabaseName.yourViewName TO ' yourUserName@'yourLocalHost'; First you need to display all the view names from a table. The syntax is as follows − SHOW FULL TABLES IN yourDatabaseName WHERE TABLE_TYPE LIKE 'VIEW'; Now implement the above syntax to display all views from a database. Here I am using the database name ‘test’. The query is as follows − mysql> SHOW FULL TABLES IN test WHERE TABLE_TYPE LIKE 'VIEW'; The following is the output − +-------------------------------+------------+ | Tables_in_test | Table_type | +-------------------------------+------------+ | empidandempname_view | VIEW | | empinfoview | VIEW | | lookuptable | VIEW | | view_student | VIEW | | viewemployeeidandemployeename | VIEW | +-------------------------------+------------+ 5 rows in set (0.00 sec) Display all user name and host from MySQL.user table. The query is as follows − mysql> select user,host from MySQL.user; The following is the output − +------------------+-----------+ | user | host | +------------------+-----------+ | Manish | % | | User2 | % | | mysql.infoschema | % | | mysql.session | % | | mysql.sys | % | | root | % | | Adam Smith | localhost | | User1 | localhost | | am | localhost | +------------------+-----------+ 9 rows in set (0.00 sec) Grant the user as well as host. Now, use the database ‘test’ and view is ‘viewemployeeidandemployeename’. To grant it to ‘Adam Smith'@'localhost’, the following is the query − mysql> GRANT SELECT ON test. viewemployeeidandemployeename TO ' Adam Smith'@'localhost'; Query OK, 0 rows affected (0.18 sec)
[ { "code": null, "e": 1137, "s": 1062, "text": "To grant a user permission to only view a MySQL view, use the below syntax" }, { "code": null, "e": 1218, "s": 1137, "text": "GRANT SELECT ON yourDatabaseName.yourViewName TO ' yourUserName@'yourLocalHost';" }, { "code": null, "e": 1304, "s": 1218, "text": "First you need to display all the view names from a table. The syntax is as follows −" }, { "code": null, "e": 1371, "s": 1304, "text": "SHOW FULL TABLES IN yourDatabaseName WHERE TABLE_TYPE LIKE 'VIEW';" }, { "code": null, "e": 1508, "s": 1371, "text": "Now implement the above syntax to display all views from a database. Here I am using the database name ‘test’. The query is as follows −" }, { "code": null, "e": 1570, "s": 1508, "text": "mysql> SHOW FULL TABLES IN test WHERE TABLE_TYPE LIKE 'VIEW';" }, { "code": null, "e": 1600, "s": 1570, "text": "The following is the output −" }, { "code": null, "e": 2048, "s": 1600, "text": "+-------------------------------+------------+\n| Tables_in_test | Table_type |\n+-------------------------------+------------+\n| empidandempname_view | VIEW |\n| empinfoview | VIEW |\n| lookuptable | VIEW |\n| view_student | VIEW |\n| viewemployeeidandemployeename | VIEW |\n+-------------------------------+------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2128, "s": 2048, "text": "Display all user name and host from MySQL.user table. The query is as follows −" }, { "code": null, "e": 2169, "s": 2128, "text": "mysql> select user,host from MySQL.user;" }, { "code": null, "e": 2199, "s": 2169, "text": "The following is the output −" }, { "code": null, "e": 2653, "s": 2199, "text": "+------------------+-----------+\n| user | host |\n+------------------+-----------+\n| Manish | % |\n| User2 | % |\n| mysql.infoschema | % |\n| mysql.session | % |\n| mysql.sys | % |\n| root | % |\n| Adam Smith | localhost |\n| User1 | localhost |\n| am | localhost |\n+------------------+-----------+\n9 rows in set (0.00 sec)" }, { "code": null, "e": 2829, "s": 2653, "text": "Grant the user as well as host. Now, use the database ‘test’ and view is ‘viewemployeeidandemployeename’. To grant it to ‘Adam Smith'@'localhost’, the following is the query −" }, { "code": null, "e": 2955, "s": 2829, "text": "mysql> GRANT SELECT ON test. viewemployeeidandemployeename TO ' Adam Smith'@'localhost';\nQuery OK, 0 rows affected (0.18 sec)" } ]
How to perform mouseover function in Selenium WebDriver using Java?
A mouse hover is done on an element to fire an event on that element. If we hover on the menus of a webpage the submenus appears. Thus this event gets triggered on hovering on an element. It is evident from the above image that on hovering over the Packages menu the color of the text changed along with the tooltip display. Selenium has the Actions class that contains multiple APIs for mouse cursor movement. The moveToElement() method is used to perform mouse movement. We have to import org.openqa.selenium.interactions.Actions for Action class. Along with moveToElement() we have to use the perform() method to make the mouse movement. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.interactions.Actions; public class MouseHover{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify element WebElement l=driver.findElement(By.xpath("//span[text()='Jobs']")); // Actions class with moveToElement() Actions a = new Actions(driver); a.moveToElement(l).perform(); System.out.println("Tooltip: "+ l.getText()); driver.quit(); } }
[ { "code": null, "e": 1250, "s": 1062, "text": "A mouse hover is done on an element to fire an event on that element. If we hover on the menus of a webpage the submenus appears. Thus this event gets triggered on hovering on an element." }, { "code": null, "e": 1473, "s": 1250, "text": "It is evident from the above image that on hovering over the Packages menu the color of the text changed along with the tooltip display. Selenium has the Actions class that contains multiple APIs for mouse cursor movement." }, { "code": null, "e": 1703, "s": 1473, "text": "The moveToElement() method is used to perform mouse movement. We have to import org.openqa.selenium.interactions.Actions for Action class. Along with moveToElement() we have to use the perform() method to make the mouse movement." }, { "code": null, "e": 1724, "s": 1703, "text": "Code Implementation." }, { "code": null, "e": 2645, "s": 1724, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport org.openqa.selenium.interactions.Actions;\npublic class MouseHover{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // identify element\n WebElement l=driver.findElement(By.xpath(\"//span[text()='Jobs']\"));\n // Actions class with moveToElement()\n Actions a = new Actions(driver);\n a.moveToElement(l).perform();\n System.out.println(\"Tooltip: \"+ l.getText());\n driver.quit();\n }\n}" } ]
How to Remove the computer from the AD domain using PowerShell?
To remove the computer from the domain we need to use the Remove-Computer command. Remove-Computer -ComputerName Test1-win2k16 ` -UnjoinDomainCredential Labdomain\Administrator ` -WorkgroupName WG -Restart -Force -PassThru In the above example, the Computer name Test1-Win2k16 is going to remove from the domain with the domain credentials and it will be joined to WorkGroup named WG. If the system doesn’t restart due to any reason, you need to reboot the system manually. Here the computer name is the String[]. So you can provide multiple computers to remove from the domain. For example, Remove-Computer -ComputerName Test1-win2k16, Test1-Win2k12 ` -UnjoinDomainCredential Labdomain\Administrator ` -WorkgroupName WG -Restart -Force -PassThru
[ { "code": null, "e": 1145, "s": 1062, "text": "To remove the computer from the domain we need to use the Remove-Computer command." }, { "code": null, "e": 1317, "s": 1145, "text": "Remove-Computer -ComputerName Test1-win2k16 `\n -UnjoinDomainCredential Labdomain\\Administrator `\n -WorkgroupName WG -Restart -Force -PassThru" }, { "code": null, "e": 1568, "s": 1317, "text": "In the above example, the Computer name Test1-Win2k16 is going to remove from the domain with the domain credentials and it will be joined to WorkGroup named WG. If the system doesn’t restart due to any reason, you need to reboot the system manually." }, { "code": null, "e": 1686, "s": 1568, "text": "Here the computer name is the String[]. So you can provide multiple computers to remove from the domain. For example," }, { "code": null, "e": 1873, "s": 1686, "text": "Remove-Computer -ComputerName Test1-win2k16, Test1-Win2k12 `\n -UnjoinDomainCredential Labdomain\\Administrator `\n -WorkgroupName WG -Restart -Force -PassThru" } ]
GATE | GATE CS 2008 | Question 55 - GeeksforGeeks
14 Sep, 2021 An LALR(1) parser for a grammar G can have shift-reduce (S-R) conflicts if and only if(A) the SLR(1) parser for G has S-R conflicts(B) the LR(1) parser for G has S-R conflicts(C) the LR(0) parser for G has S-R conflicts(D) the LALR(1) parser for G has reduce-reduce conflictsAnswer: (B)Explanation:Both LALR(1) and LR(1) parser uses LR(1) set of items to form their parsing tables. And LALR(1) states can be find by merging LR(1) states of LR(1) parser that have the same set of first components of their items. i.e. if LR(1) parser has 2 states I and J with items A->a.bP,x and A->a.bP,y respectively, where x and y are look ahead symbols, then as these items are same with respect to their first component, they can be merged together and form one single state, let’s say K. Here we have to take union of look ahead symbols. After merging, State K will have one single item as A->a.bP,x,y . This way LALR(1) states are formed ( i.e. after merging the states of LR(1) ). Now, S-R conflict in LR(1) items can be there whenever a state has items of the form : A-> a.bB , p C-> d. , b i.e. it is getting both shift and reduce at symbol b, hence a conflict. Now, as LALR(1) have items similar to LR(1) in terms of their first component, shift-reduce form will only take place if it is already there in LR(1) states. If there is no S-R conflict in LR(1) state it will never be reflected in the LALR(1) state obtained by combining LR(1) states. Note: But this process of merging may introduce R-R conflict, and then the Grammar won’t be LALR(1). YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0016:55 / 58:40•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=LdMTs93sekg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2008 GATE-GATE CS 2008 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments GATE | GATE-IT-2004 | Question 71 GATE | GATE CS 2011 | Question 7 GATE | GATE-CS-2016 (Set 2) | Question 48 GATE | GATE CS 2010 | Question 24 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2016 (Set 1) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 38 GATE | GATE CS 2018 | Question 37 GATE | GATE-IT-2004 | Question 83 GATE | GATE-CS-2016 (Set 1) | Question 63
[ { "code": null, "e": 24432, "s": 24404, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24944, "s": 24432, "text": "An LALR(1) parser for a grammar G can have shift-reduce (S-R) conflicts if and only if(A) the SLR(1) parser for G has S-R conflicts(B) the LR(1) parser for G has S-R conflicts(C) the LR(0) parser for G has S-R conflicts(D) the LALR(1) parser for G has reduce-reduce conflictsAnswer: (B)Explanation:Both LALR(1) and LR(1) parser uses LR(1) set of items to form their parsing tables. And LALR(1) states can be find by merging LR(1) states of LR(1) parser that have the same set of first components of their items." }, { "code": null, "e": 25404, "s": 24944, "text": "i.e. if LR(1) parser has 2 states I and J with items A->a.bP,x and A->a.bP,y respectively, where x and y are look ahead symbols, then as these items are same with respect to their first component, they can be merged together and form one single state, let’s say K. Here we have to take union of look ahead symbols. After merging, State K will have one single item as A->a.bP,x,y . This way LALR(1) states are formed ( i.e. after merging the states of LR(1) )." }, { "code": null, "e": 25491, "s": 25404, "text": "Now, S-R conflict in LR(1) items can be there whenever a state has items of the form :" }, { "code": null, "e": 25591, "s": 25491, "text": "\nA-> a.bB , p\nC-> d. , b\n\ni.e. it is getting both shift and reduce at symbol b, \nhence a conflict. " }, { "code": null, "e": 25876, "s": 25591, "text": "Now, as LALR(1) have items similar to LR(1) in terms of their first component, shift-reduce form will only take place if it is already there in LR(1) states. If there is no S-R conflict in LR(1) state it will never be reflected in the LALR(1) state obtained by combining LR(1) states." }, { "code": null, "e": 25977, "s": 25876, "text": "Note: But this process of merging may introduce R-R conflict, and then the Grammar won’t be LALR(1)." }, { "code": null, "e": 26890, "s": 25977, "text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) Part 4 with Joyojyoti Acharya | GeeksforGeeks GATEWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:0016:55 / 58:40•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=LdMTs93sekg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 26903, "s": 26890, "text": "GATE-CS-2008" }, { "code": null, "e": 26921, "s": 26903, "text": "GATE-GATE CS 2008" }, { "code": null, "e": 26926, "s": 26921, "text": "GATE" }, { "code": null, "e": 27024, "s": 26926, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27033, "s": 27024, "text": "Comments" }, { "code": null, "e": 27046, "s": 27033, "text": "Old Comments" }, { "code": null, "e": 27080, "s": 27046, "text": "GATE | GATE-IT-2004 | Question 71" }, { "code": null, "e": 27113, "s": 27080, "text": "GATE | GATE CS 2011 | Question 7" }, { "code": null, "e": 27155, "s": 27113, "text": "GATE | GATE-CS-2016 (Set 2) | Question 48" }, { "code": null, "e": 27189, "s": 27155, "text": "GATE | GATE CS 2010 | Question 24" }, { "code": null, "e": 27231, "s": 27189, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 27273, "s": 27231, "text": "GATE | GATE-CS-2016 (Set 1) | Question 65" }, { "code": null, "e": 27315, "s": 27273, "text": "GATE | GATE-CS-2014-(Set-3) | Question 38" }, { "code": null, "e": 27349, "s": 27315, "text": "GATE | GATE CS 2018 | Question 37" }, { "code": null, "e": 27383, "s": 27349, "text": "GATE | GATE-IT-2004 | Question 83" } ]
How to handle errors in middleware C# Asp.net Core?
Create a new folder named CustomExceptionMiddleware and a class ExceptionMiddleware.cs inside it. The first thing we need to do is to register our IloggerManager service and RequestDelegate through the dependency injection. The _next parameter of RequestDeleagate type is a function delegate that can process our HTTP requests. After the registration process, we need to create the InvokeAsync() method. RequestDelegate can’t process requests without it. The _next delegate should process the request and the Get action from our controller should generate a successful response. But if a request is unsuccessful (and it is, because we are forcing exception), our middleware will trigger the catch block and call the HandleExceptionAsync method. public class ExceptionMiddleware{ private readonly RequestDelegate _next; private readonly ILoggerManager _logger; public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){ _logger = logger; _next = next; } public async Task InvokeAsync(HttpContext httpContext){ try{ await _next(httpContext); } catch (Exception ex){ _logger.LogError($"Something went wrong: {ex}"); await HandleExceptionAsync(httpContext, ex); } } private Task HandleExceptionAsync(HttpContext context, Exception exception){ context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; return context.Response.WriteAsync(new ErrorDetails(){ StatusCode = context.Response.StatusCode, Message = "Internal Server Error from the custom middleware." }.ToString()); } } Modify our ExceptionMiddlewareExtensions class with another static method − public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder app){ app.UseMiddleware<ExceptionMiddleware>(); } use this method in the Configure method in the Startup class − app.ConfigureCustomExceptionMiddleware();
[ { "code": null, "e": 1160, "s": 1062, "text": "Create a new folder named CustomExceptionMiddleware and a class\nExceptionMiddleware.cs inside it." }, { "code": null, "e": 1286, "s": 1160, "text": "The first thing we need to do is to register our IloggerManager service and\nRequestDelegate through the dependency injection." }, { "code": null, "e": 1390, "s": 1286, "text": "The _next parameter of RequestDeleagate type is a function delegate that can process\nour HTTP requests." }, { "code": null, "e": 1517, "s": 1390, "text": "After the registration process, we need to create the InvokeAsync() method.\nRequestDelegate can’t process requests without it." }, { "code": null, "e": 1721, "s": 1517, "text": "The _next delegate should process the request and the Get action from our controller\nshould generate a successful response. But if a request is unsuccessful (and it is,\nbecause we are forcing exception)," }, { "code": null, "e": 1807, "s": 1721, "text": "our middleware will trigger the catch block and call the HandleExceptionAsync\nmethod." }, { "code": null, "e": 2747, "s": 1807, "text": "public class ExceptionMiddleware{\n private readonly RequestDelegate _next;\n private readonly ILoggerManager _logger;\n public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){\n _logger = logger;\n _next = next;\n }\n public async Task InvokeAsync(HttpContext httpContext){\n try{\n await _next(httpContext);\n }\n catch (Exception ex){\n _logger.LogError($\"Something went wrong: {ex}\");\n await HandleExceptionAsync(httpContext, ex);\n }\n }\n private Task HandleExceptionAsync(HttpContext context, Exception exception){\n context.Response.ContentType = \"application/json\";\n context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;\n return context.Response.WriteAsync(new ErrorDetails(){\n StatusCode = context.Response.StatusCode,\n Message = \"Internal Server Error from the custom middleware.\"\n }.ToString());\n }\n}" }, { "code": null, "e": 2823, "s": 2747, "text": "Modify our ExceptionMiddlewareExtensions class with another static method −" }, { "code": null, "e": 2955, "s": 2823, "text": "public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder\napp){\n app.UseMiddleware<ExceptionMiddleware>();\n}" }, { "code": null, "e": 3018, "s": 2955, "text": "use this method in the Configure method in the Startup class −" }, { "code": null, "e": 3060, "s": 3018, "text": "app.ConfigureCustomExceptionMiddleware();" } ]
How to create an unordered_set of user defined class or struct in C++? - GeeksforGeeks
22 Nov, 2021 The unordered_set internally implements a hash table to store elements. By default we can store only predefined type as int, string, float etc. If we want to store the element of user defined type as structure then compiler will show an error because before storing elements into unordered_set compiler performs some checking. And while comparing two user defined type compiler can not compare them hence it generate an error. So, in order to store a structure in a unordered_set, some comparison function need to be designed. Since unordered_set also store implements hash table to store elements we should also have to implement hash function to perform hashing related work. Below method explains its implementation. Implementation: We create a structure type and define a comparison function inside that structure that will used to compare two structure type objects. Since unordered_set internally implements hash function so we should have also implement the hash function for user defined type objects. Syntax To store user defined type elements unordered_set should follow following syntax unordered_set(elementType, MyHashType) us; // element type is user defined type and MyHashType is class implementing hash function Below code explains it. CPP // CPP implementation to use// user-defined data type in// structures#include <bits/stdc++.h>using namespace std; // Structure definitionstruct Test { int id; // This function is used by unordered_set to compare // elements of Test. bool operator==(const Test& t) const { return (this->id == t.id); }}; // class for hash functionclass MyHashFunction {public: // id is returned as hash function size_t operator()(const Test& t) const { return t.id; }}; // Driver methodint main(){ // put values in each // structure define below. Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // define a unordered_set having // structure as its elements. unordered_set<Test, MyHashFunction> us; // insert structure in unordered_set us.insert(t1); us.insert(t2); us.insert(t3); us.insert(t4); // printing the elements of unordered_set for (auto e : us) { cout << e.id << " "; } return 0;} 115 101 110 102 115 101 110 102 Below is another example where we use predefined hash functions to make overall hash function of our defined class. CPP // CPP program to demonstrate working of unordered_set// for user defined data types.#include <bits/stdc++.h>using namespace std; struct Person { string first, last; Person(string f, string l) { first = f; last = l; } bool operator==(const Person& p) const { return first == p.first && last == p.last; }}; class MyHashFunction {public: // We use predefined hash functions of strings // and define our hash function as XOR of the // hash values. size_t operator()(const Person& p) const { return (hash<string>()(p.first)) ^ (hash<string>()(p.last)); }}; // Driver codeint main(){ unordered_set<Person, MyHashFunction> us; Person p1("kartik", "kapoor"); Person p2("Ram", "Singh"); Person p3("Laxman", "Prasad"); us.insert(p1); us.insert(p2); us.insert(p3); for (auto e : us) { cout << "[" << e.first << ", " << e.last << "]\n"; } return 0;} [Laxman, Prasad] [kartik, kapoor] [Ram, Singh] as5853535 cpp-unordered_set Picked STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Operator Overloading in C++ Iterators in C++ STL Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ List in C++ Standard Template Library (STL) Inline Functions in C++ std::string class in C++ Destructors in C++
[ { "code": null, "e": 24018, "s": 23990, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25118, "s": 24018, "text": "The unordered_set internally implements a hash table to store elements. By default we can store only predefined type as int, string, float etc. If we want to store the element of user defined type as structure then compiler will show an error because before storing elements into unordered_set compiler performs some checking. And while comparing two user defined type compiler can not compare them hence it generate an error. So, in order to store a structure in a unordered_set, some comparison function need to be designed. Since unordered_set also store implements hash table to store elements we should also have to implement hash function to perform hashing related work. Below method explains its implementation. Implementation: We create a structure type and define a comparison function inside that structure that will used to compare two structure type objects. Since unordered_set internally implements hash function so we should have also implement the hash function for user defined type objects. Syntax To store user defined type elements unordered_set should follow following syntax " }, { "code": null, "e": 25249, "s": 25118, "text": "unordered_set(elementType, MyHashType) us;\n// element type is user defined type and MyHashType is class implementing hash function" }, { "code": null, "e": 25275, "s": 25249, "text": "Below code explains it. " }, { "code": null, "e": 25279, "s": 25275, "text": "CPP" }, { "code": "// CPP implementation to use// user-defined data type in// structures#include <bits/stdc++.h>using namespace std; // Structure definitionstruct Test { int id; // This function is used by unordered_set to compare // elements of Test. bool operator==(const Test& t) const { return (this->id == t.id); }}; // class for hash functionclass MyHashFunction {public: // id is returned as hash function size_t operator()(const Test& t) const { return t.id; }}; // Driver methodint main(){ // put values in each // structure define below. Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; // define a unordered_set having // structure as its elements. unordered_set<Test, MyHashFunction> us; // insert structure in unordered_set us.insert(t1); us.insert(t2); us.insert(t3); us.insert(t4); // printing the elements of unordered_set for (auto e : us) { cout << e.id << \" \"; } return 0;}", "e": 26275, "s": 25279, "text": null }, { "code": null, "e": 26291, "s": 26275, "text": "115 101 110 102" }, { "code": null, "e": 26309, "s": 26293, "text": "115 101 110 102" }, { "code": null, "e": 26428, "s": 26311, "text": "Below is another example where we use predefined hash functions to make overall hash function of our defined class. " }, { "code": null, "e": 26432, "s": 26428, "text": "CPP" }, { "code": "// CPP program to demonstrate working of unordered_set// for user defined data types.#include <bits/stdc++.h>using namespace std; struct Person { string first, last; Person(string f, string l) { first = f; last = l; } bool operator==(const Person& p) const { return first == p.first && last == p.last; }}; class MyHashFunction {public: // We use predefined hash functions of strings // and define our hash function as XOR of the // hash values. size_t operator()(const Person& p) const { return (hash<string>()(p.first)) ^ (hash<string>()(p.last)); }}; // Driver codeint main(){ unordered_set<Person, MyHashFunction> us; Person p1(\"kartik\", \"kapoor\"); Person p2(\"Ram\", \"Singh\"); Person p3(\"Laxman\", \"Prasad\"); us.insert(p1); us.insert(p2); us.insert(p3); for (auto e : us) { cout << \"[\" << e.first << \", \" << e.last << \"]\\n\"; } return 0;}", "e": 27393, "s": 26432, "text": null }, { "code": null, "e": 27440, "s": 27393, "text": "[Laxman, Prasad]\n[kartik, kapoor]\n[Ram, Singh]" }, { "code": null, "e": 27452, "s": 27442, "text": "as5853535" }, { "code": null, "e": 27470, "s": 27452, "text": "cpp-unordered_set" }, { "code": null, "e": 27477, "s": 27470, "text": "Picked" }, { "code": null, "e": 27481, "s": 27477, "text": "STL" }, { "code": null, "e": 27485, "s": 27481, "text": "C++" }, { "code": null, "e": 27489, "s": 27485, "text": "STL" }, { "code": null, "e": 27493, "s": 27489, "text": "CPP" }, { "code": null, "e": 27591, "s": 27493, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27600, "s": 27591, "text": "Comments" }, { "code": null, "e": 27613, "s": 27600, "text": "Old Comments" }, { "code": null, "e": 27641, "s": 27613, "text": "Operator Overloading in C++" }, { "code": null, "e": 27662, "s": 27641, "text": "Iterators in C++ STL" }, { "code": null, "e": 27695, "s": 27662, "text": "Friend class and function in C++" }, { "code": null, "e": 27715, "s": 27695, "text": "Polymorphism in C++" }, { "code": null, "e": 27739, "s": 27715, "text": "Sorting a vector in C++" }, { "code": null, "e": 27775, "s": 27739, "text": "Convert string to char array in C++" }, { "code": null, "e": 27819, "s": 27775, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 27843, "s": 27819, "text": "Inline Functions in C++" }, { "code": null, "e": 27868, "s": 27843, "text": "std::string class in C++" } ]
Scala Int round() method with example - GeeksforGeeks
30 Jan, 2020 The round() method is utilized to return the rounded value of the specified int value. This method is used to avoid accidental loss of precision from a detour through Float. Method Definition: def round: Int Return Type: It returns the rounded value of the specified int value. Example #1: // Scala program of Int round// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying round method val result = (5).round // Displays output println(result) } } 5 Example #2: // Scala program of Int round// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying round method val result = (5.8).round // Displays output println(result) } } 6 Scala Scala-Method Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Scala Map Type Casting in Scala Scala Lists Scala List contains() method with example Scala Tutorial – Learn Scala with Step By Step Guide Scala String substring() method with example Scala | Arrays How to get the first element of List in Scala Scala String replace() method with example Lambda Expression in Scala
[ { "code": null, "e": 25305, "s": 25277, "text": "\n30 Jan, 2020" }, { "code": null, "e": 25479, "s": 25305, "text": "The round() method is utilized to return the rounded value of the specified int value. This method is used to avoid accidental loss of precision from a detour through Float." }, { "code": null, "e": 25513, "s": 25479, "text": "Method Definition: def round: Int" }, { "code": null, "e": 25583, "s": 25513, "text": "Return Type: It returns the rounded value of the specified int value." }, { "code": null, "e": 25595, "s": 25583, "text": "Example #1:" }, { "code": "// Scala program of Int round// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying round method val result = (5).round // Displays output println(result) } } ", "e": 25897, "s": 25595, "text": null }, { "code": null, "e": 25900, "s": 25897, "text": "5\n" }, { "code": null, "e": 25912, "s": 25900, "text": "Example #2:" }, { "code": "// Scala program of Int round// method // Creating object object GfG { // Main method def main(args:Array[String]) { // Applying round method val result = (5.8).round // Displays output println(result) } } ", "e": 26215, "s": 25912, "text": null }, { "code": null, "e": 26218, "s": 26215, "text": "6\n" }, { "code": null, "e": 26224, "s": 26218, "text": "Scala" }, { "code": null, "e": 26237, "s": 26224, "text": "Scala-Method" }, { "code": null, "e": 26243, "s": 26237, "text": "Scala" }, { "code": null, "e": 26341, "s": 26243, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26351, "s": 26341, "text": "Scala Map" }, { "code": null, "e": 26373, "s": 26351, "text": "Type Casting in Scala" }, { "code": null, "e": 26385, "s": 26373, "text": "Scala Lists" }, { "code": null, "e": 26427, "s": 26385, "text": "Scala List contains() method with example" }, { "code": null, "e": 26480, "s": 26427, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 26525, "s": 26480, "text": "Scala String substring() method with example" }, { "code": null, "e": 26540, "s": 26525, "text": "Scala | Arrays" }, { "code": null, "e": 26586, "s": 26540, "text": "How to get the first element of List in Scala" }, { "code": null, "e": 26629, "s": 26586, "text": "Scala String replace() method with example" } ]
Document Type Definition - DTD - GeeksforGeeks
06 Nov, 2020 A Document Type Definition (DTD) describes the tree structure of a document and something about its data. It is a set of markup affirmations that actually define a type of document for the SGML family, like GML, SGML, HTML, XML. A DTD can be declared inside an XML document as inline or as an external recommendation. DTD determines how many times a node should appear, and how their child nodes are ordered. There are 2 data types, PCDATA and CDATA PCDATA is parsed character data. CDATA is character data, not usually parsed. Syntax: <!DOCTYPE element DTD identifier [ first declaration second declaration . . nth declaration ]> Example: DTD for the above tree is: XML document with an internal DTD: XML <?xml version="1.0"?><!DOCTYPE address [<!ELEMENT address (name, email, phone, birthday)><!ELEMENT name (first, last)><!ELEMENT first (#PCDATA)><!ELEMENT last (#PCDATA)><!ELEMENT email (#PCDATA)><!ELEMENT phone (#PCDATA)><!ELEMENT birthday (year, month, day)><!ELEMENT year (#PCDATA)><!ELEMENT month (#PCDATA)><!ELEMENT day (#PCDATA)>]> <address> <name> <first>Rohit</first> <last>Sharma</last> </name> <email>[email protected]</email> <phone>9876543210</phone> <birthday> <year>1987</year> <month>June</month> <day>23</day> </birthday></address> The DTD above is interpreted like this: !DOCTYPE address defines that the root element of this document is address. !ELEMENT address defines that the address element must contain four elements: “name, email, phone, birthday”. !ELEMENT name defines that the name element must contain two elements: “first, last”. !ELEMENT first defines the first element to be of type “#PCDATA”.!ELEMENT last defines the last element to be of type “#PCDATA”. !ELEMENT first defines the first element to be of type “#PCDATA”. !ELEMENT last defines the last element to be of type “#PCDATA”. !ELEMENT email defines the email element to be of type “#PCDATA”. !ELEMENT phone defines the phone element to be of type “#PCDATA”. !ELEMENT birthday defines that the birthday element must contain three elements “year, month, day”.!ELEMENT year defines the year element to be of type “#PCDATA”.!ELEMENT month defines the month element to be of type “#PCDATA”.!ELEMENT day defines the day element to be of type “#PCDATA”. !ELEMENT year defines the year element to be of type “#PCDATA”. !ELEMENT month defines the month element to be of type “#PCDATA”. !ELEMENT day defines the day element to be of type “#PCDATA”. XML document with an external DTD: XML <?xml version="1.0"?><!DOCTYPE address SYSTEM "address.dtd"><address> <name> <first>Rohit</first> <last>Sharma</last> </name> <email>[email protected]</email> <phone>9876543210</phone> <birthday> <year>1987</year> <month>June</month> <day>23</day> </birthday></address> address.dtd: <!ELEMENT address (name, email, phone, birthday)> <!ELEMENT name (first, last)><!ELEMENT first (#PCDATA)><!ELEMENT last (#PCDATA)> <!ELEMENT first (#PCDATA)> <!ELEMENT last (#PCDATA)> <!ELEMENT email (#PCDATA)> <!ELEMENT phone (#PCDATA)> <!ELEMENT birthday (year, month, day)><!ELEMENT year (#PCDATA)><!ELEMENT month (#PCDATA)><!ELEMENT day (#PCDATA)> <!ELEMENT year (#PCDATA)> <!ELEMENT month (#PCDATA)> <!ELEMENT day (#PCDATA)> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML and XML Web technologies-HTML and XML Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript Top 10 Angular Libraries For Web Developers Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to redirect to another page in ReactJS ? How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? Set the value of an input field in JavaScript
[ { "code": null, "e": 24860, "s": 24832, "text": "\n06 Nov, 2020" }, { "code": null, "e": 25090, "s": 24860, "text": "A Document Type Definition (DTD) describes the tree structure of a document and something about its data. It is a set of markup affirmations that actually define a type of document for the SGML family, like GML, SGML, HTML, XML. " }, { "code": null, "e": 25270, "s": 25090, "text": "A DTD can be declared inside an XML document as inline or as an external recommendation. DTD determines how many times a node should appear, and how their child nodes are ordered." }, { "code": null, "e": 25311, "s": 25270, "text": "There are 2 data types, PCDATA and CDATA" }, { "code": null, "e": 25344, "s": 25311, "text": "PCDATA is parsed character data." }, { "code": null, "e": 25389, "s": 25344, "text": "CDATA is character data, not usually parsed." }, { "code": null, "e": 25397, "s": 25389, "text": "Syntax:" }, { "code": null, "e": 25508, "s": 25397, "text": "<!DOCTYPE element DTD identifier\n[\n first declaration\n second declaration\n .\n .\n nth declaration\n]>\n" }, { "code": null, "e": 25517, "s": 25508, "text": "Example:" }, { "code": null, "e": 25544, "s": 25517, "text": "DTD for the above tree is:" }, { "code": null, "e": 25579, "s": 25544, "text": "XML document with an internal DTD:" }, { "code": null, "e": 25583, "s": 25579, "text": "XML" }, { "code": "<?xml version=\"1.0\"?><!DOCTYPE address [<!ELEMENT address (name, email, phone, birthday)><!ELEMENT name (first, last)><!ELEMENT first (#PCDATA)><!ELEMENT last (#PCDATA)><!ELEMENT email (#PCDATA)><!ELEMENT phone (#PCDATA)><!ELEMENT birthday (year, month, day)><!ELEMENT year (#PCDATA)><!ELEMENT month (#PCDATA)><!ELEMENT day (#PCDATA)>]> <address> <name> <first>Rohit</first> <last>Sharma</last> </name> <email>[email protected]</email> <phone>9876543210</phone> <birthday> <year>1987</year> <month>June</month> <day>23</day> </birthday></address>", "e": 26188, "s": 25583, "text": null }, { "code": null, "e": 26228, "s": 26188, "text": "The DTD above is interpreted like this:" }, { "code": null, "e": 26304, "s": 26228, "text": "!DOCTYPE address defines that the root element of this document is address." }, { "code": null, "e": 26414, "s": 26304, "text": "!ELEMENT address defines that the address element must contain four elements: “name, email, phone, birthday”." }, { "code": null, "e": 26629, "s": 26414, "text": "!ELEMENT name defines that the name element must contain two elements: “first, last”. !ELEMENT first defines the first element to be of type “#PCDATA”.!ELEMENT last defines the last element to be of type “#PCDATA”." }, { "code": null, "e": 26696, "s": 26629, "text": " !ELEMENT first defines the first element to be of type “#PCDATA”." }, { "code": null, "e": 26760, "s": 26696, "text": "!ELEMENT last defines the last element to be of type “#PCDATA”." }, { "code": null, "e": 26826, "s": 26760, "text": "!ELEMENT email defines the email element to be of type “#PCDATA”." }, { "code": null, "e": 26892, "s": 26826, "text": "!ELEMENT phone defines the phone element to be of type “#PCDATA”." }, { "code": null, "e": 27181, "s": 26892, "text": "!ELEMENT birthday defines that the birthday element must contain three elements “year, month, day”.!ELEMENT year defines the year element to be of type “#PCDATA”.!ELEMENT month defines the month element to be of type “#PCDATA”.!ELEMENT day defines the day element to be of type “#PCDATA”." }, { "code": null, "e": 27245, "s": 27181, "text": "!ELEMENT year defines the year element to be of type “#PCDATA”." }, { "code": null, "e": 27311, "s": 27245, "text": "!ELEMENT month defines the month element to be of type “#PCDATA”." }, { "code": null, "e": 27373, "s": 27311, "text": "!ELEMENT day defines the day element to be of type “#PCDATA”." }, { "code": null, "e": 27408, "s": 27373, "text": "XML document with an external DTD:" }, { "code": null, "e": 27412, "s": 27408, "text": "XML" }, { "code": "<?xml version=\"1.0\"?><!DOCTYPE address SYSTEM \"address.dtd\"><address> <name> <first>Rohit</first> <last>Sharma</last> </name> <email>[email protected]</email> <phone>9876543210</phone> <birthday> <year>1987</year> <month>June</month> <day>23</day> </birthday></address>", "e": 27739, "s": 27412, "text": null }, { "code": null, "e": 27752, "s": 27739, "text": "address.dtd:" }, { "code": null, "e": 27802, "s": 27752, "text": "<!ELEMENT address (name, email, phone, birthday)>" }, { "code": null, "e": 27883, "s": 27802, "text": "<!ELEMENT name (first, last)><!ELEMENT first (#PCDATA)><!ELEMENT last (#PCDATA)>" }, { "code": null, "e": 27910, "s": 27883, "text": "<!ELEMENT first (#PCDATA)>" }, { "code": null, "e": 27936, "s": 27910, "text": "<!ELEMENT last (#PCDATA)>" }, { "code": null, "e": 27963, "s": 27936, "text": "<!ELEMENT email (#PCDATA)>" }, { "code": null, "e": 27990, "s": 27963, "text": "<!ELEMENT phone (#PCDATA)>" }, { "code": null, "e": 28104, "s": 27990, "text": "<!ELEMENT birthday (year, month, day)><!ELEMENT year (#PCDATA)><!ELEMENT month (#PCDATA)><!ELEMENT day (#PCDATA)>" }, { "code": null, "e": 28130, "s": 28104, "text": "<!ELEMENT year (#PCDATA)>" }, { "code": null, "e": 28157, "s": 28130, "text": "<!ELEMENT month (#PCDATA)>" }, { "code": null, "e": 28182, "s": 28157, "text": "<!ELEMENT day (#PCDATA)>" }, { "code": null, "e": 28190, "s": 28182, "text": "Output:" }, { "code": null, "e": 28327, "s": 28190, "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": 28340, "s": 28327, "text": "HTML and XML" }, { "code": null, "e": 28370, "s": 28340, "text": "Web technologies-HTML and XML" }, { "code": null, "e": 28387, "s": 28370, "text": "Web Technologies" }, { "code": null, "e": 28485, "s": 28387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28494, "s": 28485, "text": "Comments" }, { "code": null, "e": 28507, "s": 28494, "text": "Old Comments" }, { "code": null, "e": 28549, "s": 28507, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 28592, "s": 28549, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28637, "s": 28592, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28681, "s": 28637, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 28742, "s": 28681, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28814, "s": 28742, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 28859, "s": 28814, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 28909, "s": 28859, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28954, "s": 28909, "text": "How to execute PHP code using command line ?" } ]
Flower Species Classifier. Build an image classifier to recognize... | by Silvio Mori Neto | Towards Data Science
• Artificial Intelligence • Deep Learning • Convolutional Neural Networks• Python • PyTorch • Numpy • Matplotlib • Jupyter Notebooks In this article, I give an overview of the project I developed that led me to be awarded a scholarship to the Deep Learning Nanodegree program at Udacity. I developed this project as the final test of the PyTorch Scholarship Challenge assessment held by Udacity and Facebook. In this two-month challenge, I had my very first contact with Artificial Intelligence development. In addition to watching the videos and completing the assessments in the classroom, I also joined a private Slack community. So, I could connect with my peers and coaches in the program, share my progress, get feedback, ask questions, and help other scholars to complete the challenge. Build a deep learning model that identifies 102 species of flowers from images. The final application receives an image provided by the user and predicts the likelihood of being one of those known species. The image dataset, found in this link, contains 7,370 photos of flowers taken in different angles and lightening. You can see a few examples below. I divided the images randomly into three sets: Training : 6552 images / 205 batchesValidation: 409 images / 18 batchesTesting : 409 images / 18 batches For this project, I opted for using image normalization and data augmentation for the training set. As the first step, I selected randomly one of the four transformations in each image, with the given probability of being chosen: • 16,67% — Horizontal flip• 16,67% — Vertical flip• 33,33% — Random rotation, in a range of 360 degrees• 33,33% — Keep the image untouched After that, I made a random crop in the images and resized them to 224x224 pixels. For the test and validation sets, I only resized the images and made a 224x224 pixels center crop on each. To detect the features in images, I used a pre-trained network, available in the package torchvision.models. Having being trained on the ImageNet dataset, those models can identify a myriad of features in images. However, the classifiers attached in their final part categorize images in classes other than the flower species contained in the dataset. Thus, aiming at the final goal, I chose the ResNet-152 model. I kept its pre-trained convolutional layers and replaced its classifier, building a new network to sort images into new categories. My brand new classifier was a fully-connected network containing a 2,048-nodes input layer, one 1,000-nodes hidden-layer, and one output layer to categorize the input data into 102 classes. Once I had built my model, it was time to train it! Having tested many optimizers, I chose to work with Adagrad. It is a quite powerful optimizer dropping the training loss very fast. Nevertheless, it is necessary to give some control to that potency. Otherwise, that strength might be converted into exploding gradients, not converging to an optimal solution. I did so by introducing a learning rate scheduler, which I detail better in the following section. I divided the network training process into three phases, as described below. Training phase 1: The focus here was training the classifier. As the convolutional layers had already been pre-trained, they were capable of recognizing a wide variety of features in images. So, I froze their parameters, disabling them to be updated. Thus, all the effort was in adjusting the weights of the classifier. To limit the Adagrad power, I introduced a scheduler to decrease the learning rate if the error function reached a plateau. The learning rate started at 0.01 and was diminished by 0.1 in plateaus. As soon as the learning rate went under 0.0001, this phase was interrupted. During this training phase, 39 epochs were performed, delivering an accuracy of 94.62% in the validation dataset. Epoch: 39: lr: 0.00010000 Training Loss: 0.412109Validation Loss: 0.232272 Validation accuracy: 94.62% Training phase 2: Since the classifier had already acknowledgment about what to do, it was time to fine-tune the convolutional layers’ weights! To do so, I unfroze all the network parameters, set up the learning rate at 0.0001, and trained the entire model for 20 epochs. At the end of this training phase, the validation accuracy was 96.58%. Epoch: 59: lr: 0.00010000 Training Loss: 0.201783Validation Loss: 0.141651 Validation accuracy: 96.58% Training phase 3: At this point, even though I had already obtained a strong result, I decided to push forward the limits of my network! I dropped the learning rate to 0.000001, only to make a few minor adjustments to the classifier weights, and run other 10 epochs of training. Then, the validation accuracy reached impressive 97.07%. Epoch: 69: lr: 0.00000100 Training Loss: 0.187415Validation Loss: 0.142964 Validation accuracy: 97.07% At this point, the network was accurate enough in recognizing the training and validation images, sorting them with superhuman accuracy. The final test for this network was looking at a completely unknown dataset to classify the images correctly. I could not picture a better result! The network performed the task with an astonishing accuracy of 99.27%, missing only 3 of 409 images! As the final result, this network receives an image as input and makes predictions about the five most probable species for that flower. One example of a real application for this project is a phone app that shows the name of the flower captured by the camera. You can see some examples of the output below. Notice that not only does the network predict the correct category but also it is very sure about that. All the code for this project can be found in my GitHub profile:
[ { "code": null, "e": 305, "s": 172, "text": "• Artificial Intelligence • Deep Learning • Convolutional Neural Networks• Python • PyTorch • Numpy • Matplotlib • Jupyter Notebooks" }, { "code": null, "e": 460, "s": 305, "text": "In this article, I give an overview of the project I developed that led me to be awarded a scholarship to the Deep Learning Nanodegree program at Udacity." }, { "code": null, "e": 581, "s": 460, "text": "I developed this project as the final test of the PyTorch Scholarship Challenge assessment held by Udacity and Facebook." }, { "code": null, "e": 966, "s": 581, "text": "In this two-month challenge, I had my very first contact with Artificial Intelligence development. In addition to watching the videos and completing the assessments in the classroom, I also joined a private Slack community. So, I could connect with my peers and coaches in the program, share my progress, get feedback, ask questions, and help other scholars to complete the challenge." }, { "code": null, "e": 1046, "s": 966, "text": "Build a deep learning model that identifies 102 species of flowers from images." }, { "code": null, "e": 1172, "s": 1046, "text": "The final application receives an image provided by the user and predicts the likelihood of being one of those known species." }, { "code": null, "e": 1286, "s": 1172, "text": "The image dataset, found in this link, contains 7,370 photos of flowers taken in different angles and lightening." }, { "code": null, "e": 1320, "s": 1286, "text": "You can see a few examples below." }, { "code": null, "e": 1367, "s": 1320, "text": "I divided the images randomly into three sets:" }, { "code": null, "e": 1488, "s": 1367, "text": "Training : 6552 images / 205 batchesValidation: 409 images / 18 batchesTesting : 409 images / 18 batches" }, { "code": null, "e": 1588, "s": 1488, "text": "For this project, I opted for using image normalization and data augmentation for the training set." }, { "code": null, "e": 1718, "s": 1588, "text": "As the first step, I selected randomly one of the four transformations in each image, with the given probability of being chosen:" }, { "code": null, "e": 1857, "s": 1718, "text": "• 16,67% — Horizontal flip• 16,67% — Vertical flip• 33,33% — Random rotation, in a range of 360 degrees• 33,33% — Keep the image untouched" }, { "code": null, "e": 1940, "s": 1857, "text": "After that, I made a random crop in the images and resized them to 224x224 pixels." }, { "code": null, "e": 2047, "s": 1940, "text": "For the test and validation sets, I only resized the images and made a 224x224 pixels center crop on each." }, { "code": null, "e": 2399, "s": 2047, "text": "To detect the features in images, I used a pre-trained network, available in the package torchvision.models. Having being trained on the ImageNet dataset, those models can identify a myriad of features in images. However, the classifiers attached in their final part categorize images in classes other than the flower species contained in the dataset." }, { "code": null, "e": 2593, "s": 2399, "text": "Thus, aiming at the final goal, I chose the ResNet-152 model. I kept its pre-trained convolutional layers and replaced its classifier, building a new network to sort images into new categories." }, { "code": null, "e": 2783, "s": 2593, "text": "My brand new classifier was a fully-connected network containing a 2,048-nodes input layer, one 1,000-nodes hidden-layer, and one output layer to categorize the input data into 102 classes." }, { "code": null, "e": 2835, "s": 2783, "text": "Once I had built my model, it was time to train it!" }, { "code": null, "e": 3243, "s": 2835, "text": "Having tested many optimizers, I chose to work with Adagrad. It is a quite powerful optimizer dropping the training loss very fast. Nevertheless, it is necessary to give some control to that potency. Otherwise, that strength might be converted into exploding gradients, not converging to an optimal solution. I did so by introducing a learning rate scheduler, which I detail better in the following section." }, { "code": null, "e": 3321, "s": 3243, "text": "I divided the network training process into three phases, as described below." }, { "code": null, "e": 3339, "s": 3321, "text": "Training phase 1:" }, { "code": null, "e": 3383, "s": 3339, "text": "The focus here was training the classifier." }, { "code": null, "e": 3641, "s": 3383, "text": "As the convolutional layers had already been pre-trained, they were capable of recognizing a wide variety of features in images. So, I froze their parameters, disabling them to be updated. Thus, all the effort was in adjusting the weights of the classifier." }, { "code": null, "e": 3914, "s": 3641, "text": "To limit the Adagrad power, I introduced a scheduler to decrease the learning rate if the error function reached a plateau. The learning rate started at 0.01 and was diminished by 0.1 in plateaus. As soon as the learning rate went under 0.0001, this phase was interrupted." }, { "code": null, "e": 4028, "s": 3914, "text": "During this training phase, 39 epochs were performed, delivering an accuracy of 94.62% in the validation dataset." }, { "code": null, "e": 4131, "s": 4028, "text": "Epoch: 39: lr: 0.00010000 Training Loss: 0.412109Validation Loss: 0.232272 Validation accuracy: 94.62%" }, { "code": null, "e": 4149, "s": 4131, "text": "Training phase 2:" }, { "code": null, "e": 4275, "s": 4149, "text": "Since the classifier had already acknowledgment about what to do, it was time to fine-tune the convolutional layers’ weights!" }, { "code": null, "e": 4403, "s": 4275, "text": "To do so, I unfroze all the network parameters, set up the learning rate at 0.0001, and trained the entire model for 20 epochs." }, { "code": null, "e": 4474, "s": 4403, "text": "At the end of this training phase, the validation accuracy was 96.58%." }, { "code": null, "e": 4577, "s": 4474, "text": "Epoch: 59: lr: 0.00010000 Training Loss: 0.201783Validation Loss: 0.141651 Validation accuracy: 96.58%" }, { "code": null, "e": 4595, "s": 4577, "text": "Training phase 3:" }, { "code": null, "e": 4714, "s": 4595, "text": "At this point, even though I had already obtained a strong result, I decided to push forward the limits of my network!" }, { "code": null, "e": 4856, "s": 4714, "text": "I dropped the learning rate to 0.000001, only to make a few minor adjustments to the classifier weights, and run other 10 epochs of training." }, { "code": null, "e": 4913, "s": 4856, "text": "Then, the validation accuracy reached impressive 97.07%." }, { "code": null, "e": 5016, "s": 4913, "text": "Epoch: 69: lr: 0.00000100 Training Loss: 0.187415Validation Loss: 0.142964 Validation accuracy: 97.07%" }, { "code": null, "e": 5153, "s": 5016, "text": "At this point, the network was accurate enough in recognizing the training and validation images, sorting them with superhuman accuracy." }, { "code": null, "e": 5263, "s": 5153, "text": "The final test for this network was looking at a completely unknown dataset to classify the images correctly." }, { "code": null, "e": 5401, "s": 5263, "text": "I could not picture a better result! The network performed the task with an astonishing accuracy of 99.27%, missing only 3 of 409 images!" }, { "code": null, "e": 5538, "s": 5401, "text": "As the final result, this network receives an image as input and makes predictions about the five most probable species for that flower." }, { "code": null, "e": 5662, "s": 5538, "text": "One example of a real application for this project is a phone app that shows the name of the flower captured by the camera." }, { "code": null, "e": 5709, "s": 5662, "text": "You can see some examples of the output below." }, { "code": null, "e": 5813, "s": 5709, "text": "Notice that not only does the network predict the correct category but also it is very sure about that." } ]
Building a memory based collaborative filtering recommender | by Àlex Escolà Nixon | Towards Data Science
In the last post Building a movie content based recommender using tf-idf I explained how to build a simple movie recommender based on the genres. In this post, we’ll be implementing a Memory-based collaborative filtering model, and go through the main differences both conceptually and in implementation between user and item-based methods. You’ll find all the code to reproduce the results in a jupyter notebook here. Collaborative filtering is the most common technique when it comes to recommender systems. As its name suggests, it is a technique that helps filter out items for a user in a collaborative way, that is, based on the preferences of similar users. Say Lizzy has just watched “Arrival” and “Blade Runner 2049", and now wants to be recommended some similar movies, because she loved these. The main idea behind collaborative filtering methods, is to find users who also liked these movies and recommend unseen movies based on their preferences. In this example, the model would likely find that other users who enjoyed these movies also liked “Interstellar”, which would possibly be a nice recommendation for Lizzy. While this is the main idea, there are many approaches to this problem and choosing the more suited one will depend on multiple factors, such as the size of the dataset we’re working with and its sparsity. As mentioned, there are many collaborative filtering (CF in short) methods, bellow are the main types we can find: Memory-based Memory-based methods use user rating historical data to compute the similarity between users or items. The idea behind these methods is to define a similarity measure between users or items, and find the most similar to recommend unseen items. Model-based Model-based CF uses machine learning algorithms to predict users’ rating of unrated items. There are many model-based CF algorithms, the most commonly used are matrix factorization models such as to applying a SVD to reconstruct the rating matrix, latent Dirichlet allocation or Markov decision process based models. Hybrid These aim to combine the memory-based and the model-based approaches. One of the main drawbacks of the above methods, is that you’ll find yourself having to choose between historical user rating data and user or item attributes. Hybrid methods enable us to leverage both, and hence tend to perform better in most cases. The most widely used methods nowadays are factorization machines. Let’s delve a little more into memory based methods now, since it is the method we’ll be implementing in this post. There are 2 main types of memory-based collaborative filtering algorithms: User-Based and Item-Based. While their difference is subtle, in practice they lead to very different approaches, so it is crucial to know which is the most convenient for each case. Let’s go through a quick overview of these methods: User-Based Here we find users that have seen/rated similar content, and use their preferences to recommend new items: A drawback is that there tends to be many more users than items, which leads to much bigger user similarity matrices (this might be clear in the following section) leading to performance and memory issues on larger datasets, which forces to rely on parallelisation techniques or other approaches altogether. Another common problem is that we’ll suffer from a cold-start: There may be no to little information on a new user’s preferences, hence nothing to compare with. Item-Based The idea is similar, but instead, starting from a given movie (or set of movies) we find similar movies based on other users’ preferences. Contrarily to user-based methods, item similarity matrices tend to be smaller, which will reduce the cost of finding neighbours in our similarity matrix. Also, since a single item is enough to recommend other similar items, this method will not suffer from the cold-start problem. A drawback of item-based methods is that they there tends to be a lower diversity in the recommendations as opposed to user-based CF. We’ll be using the same dataset as in the previous post, the MovieLens dataset, which contains rating data sets from the MovieLens web site. It contains on 1M anonymous ratings of approximately 4000 movies made by 6000 MovieLens users, released in 2/2003. We’ll be working with three .csv files: ratings, users, and movies. Please check the previous post for more details on the dataset. The first thing we’ll need to do, is to create the user-item matrix. This is essentially a pivoted table from the rating data, where the rows will be the users, the columns will be the movies and the dataframe is filled with the rating the user has given (if it exists , 0 otherwise): user_item_m = ratings.pivot('user_id','movie_id','rating').fillna(0)print(f'Shape: {user_item_m.shape}')> Shape: (29909, 5840) Which looks like (I’ve joined with the movies table so the titles can be seen here too): Next, we will define a similarity matrix. Along the lines of the previous post on Content based recommenders, see the section Similarity between vectors, we want to find a proximity measure between all users (or items) in the user-item matrix. A commonly used measure is the cosine similarity. As we also saw, this similarity measure owns its name to the fact that it equals to the cosine of the angle between the two vectors being compared, user (or item) similarity vectors of scores in this case. The lower the angle between two vectors, the higher the cosine will be, hence yielding a higher similarity factor. See the aforementioned section for more details on this. We can use sklearn's metrics.pairwise sub-module for pairwise distance or similarity metrics, in this case we’ll be using cosine_similarity . Note that the function, has the signature: sklearn.metrics.pairwise.cosine_similarity(X, Y=None, dense_output=True) Where Yis expected to be: Y: ndarray or sparse array, shape: (n_samples_Y, n_features). If None, the output will be the pairwise similarities between all samples in X. So by only specifying X this will generate a similarity matrix from the samples in X : from sklearn.metrics.pairwise import cosine_similarityX_user = cosine_similarity(user_item_m)print(X_user.shape)(6040, 6040)print(X_user)array([[1. , 0.063, 0.127, 0.116, 0.075, 0.15 , 0.035, 0.102], [0.063, 1. , 0.111, 0.145, 0.107, 0.105, 0.246, 0.161], [0.127, 0.111, 1. , 0.127, 0.066, 0.036, 0.185, 0.086], [0.116, 0.145, 0.127, 1. , 0.052, 0.016, 0.1 , 0.072], [0.075, 0.107, 0.066, 0.052, 1. , 0.052, 0.106, 0.18 ], [0.15 , 0.105, 0.036, 0.016, 0.052, 1. , 0.067, 0.085], [0.035, 0.246, 0.185, 0.1 , 0.106, 0.067, 1. , 0.202], [0.102, 0.161, 0.086, 0.072, 0.18 , 0.085, 0.202, 1. ], [0.174, 0.156, 0.1 , 0.092, 0.242, 0.078, 0.125, 0.217], [0.209, 0.162, 0.158, 0.096, 0.079, 0.124, 0.091, 0.109]]) This will generate a user similarity matrix, with shape (n_users, n_users). And since X is expected to be: X: ndarray or sparse array, shape: (n_samples_X, n_features) By transposing the user-item matrix, our samples will now be the columns of the user-item matrix, i.e. the movies. So if our original user-item matrix is of shape (n,m) , by finding the cosine similarities on the transposed matrix we’ll end up with a (m,m) matrix: X_item = cosine_similarity(user_item_m.T)X_item.shape(3706, 3706) Which will represent the item similarity matrix. Having created the similarity matrices, we can now define some logic to find similar users. In the case of a user-based recommendation we want to find users similar to a new user to who we want to recommend movies, and since we already have the similarity scores, we only have to search for the highest values in a given user row, and from there select the top k. Once we have the k closest users, we can find the highest rated movies that the user has not seen yet. Of course in this case it is simpler, since we already have computed the similarity matrix between all users. In a real scenario, we’d have to update the similarity matrix with the new user, and then find the most similar users. The algorithm for used-based CF can be summarised as: Compute the similarity between the new user with all other users (if not already done)Compute the mean rating of all movies of the k most similar usersRecommend the top n rated movies by other users unseen by the user Compute the similarity between the new user with all other users (if not already done) Compute the mean rating of all movies of the k most similar users Recommend the top n rated movies by other users unseen by the user Bellow is a function to implement a user-based CF recommender explained step by step: As mentioned earlier, the difference in implementation between user and item-based CF systems is quite small. For this reason it might be a good idea to wrap both methods in a class, which once instantiated we’ll then use to recommend movies or items to a given user: Before testing the recommender on some examples, it might be useful to define a function to see which are the preferences of a user to see if the recommendations make sense or not . Here I’m sorting the ratings given to the movies seen by a user and taking the first 10: Testing a recommender is actually tougher than it may seem. In the movielens dataset, a lot of the users will have seen a bit of everything, in the sense that they will probably have given a high rating to movies from multiple genres, not just their favourite. A useful way to test the model, is to find some specific examples of users with specific tastes, for instance, with a clear preference for one or two genres. What I have done is to find users which have already seen a couple of movies, but from very few genres, meaning that they clearly have a preference for them. The recommender is hence expected to suggest movies from the same genre. Let’s start with some user-based recommendations: Let’s try with a user which seems to have a preference for Drama: rec = CfRec(user_item_m, X_user, movies)because_user_liked(user_item_m, movies, ratings, 69) We can see that the movies that have been most highly rated by this user, are Drama movies. Let’s see what the recommender suggests: rec.recommend_user_based(69) The recommendations seem good! Hard to tell whether the user would completely agree with the specific movies, but the genre preferences of the user are clearly reflected in the recommendations. Let’s try with a fan of Horror movies now: because_user_liked(user_item_m, movies, ratings, 2155) rec.recommend_user_based(2155) “The Shining”, “Alien”... sounds like this user is missing out on these horror classics! Let’s try now with some item-based recommendations The first thing we’ll have to do is create another instance of the class, but using the item similarity matrix this time as a similarity matrix: rec = CfRec(user_item_m, X_item, movies) Here, as earlier discussed, the logic is to recommend movies based on some other movie. Let’s see what the recommender suggests for a user who likes the sci-fi classic Dune: rec.recommend_item_based(2021)>> Because you liked Dune (1984), we'd recommend you to watch: We can see that all recommended movies are from the same genre, and seem like good suggestions. If we liked Se7en, a Crime and Thriller movie, we’d be recommended to watch: rec.recommend_item_based(47)>> Because you liked (Se7en) (1995), we'd recommend you to watch: And finally, for a classic animation movie, Bambi: rec.recommend_item_based(2018)>> Because you liked Bambi (1942), we'd recommend you to watch: So in both cases, the implemented collaborative filtering models seem to provide good recommendations. There are many improvements that could be done. For instance, we could account for the fact that users can behave very differently when it comes to rating movies. Some users might rate very highly all movies, whereas other might be much more critical. This could be done by subtracting the average score from each user, we’d then have normalised score per user. I hope how ever, that this example has been illustrative in terms of how collaborative filtering methods work. I’d encourage you to take it as a starting point and perhaps tweak it a little or add some improvements. Thanks a lot for taking the time to read this post and I hope you enjoyed it :)
[ { "code": null, "e": 318, "s": 172, "text": "In the last post Building a movie content based recommender using tf-idf I explained how to build a simple movie recommender based on the genres." }, { "code": null, "e": 513, "s": 318, "text": "In this post, we’ll be implementing a Memory-based collaborative filtering model, and go through the main differences both conceptually and in implementation between user and item-based methods." }, { "code": null, "e": 591, "s": 513, "text": "You’ll find all the code to reproduce the results in a jupyter notebook here." }, { "code": null, "e": 837, "s": 591, "text": "Collaborative filtering is the most common technique when it comes to recommender systems. As its name suggests, it is a technique that helps filter out items for a user in a collaborative way, that is, based on the preferences of similar users." }, { "code": null, "e": 977, "s": 837, "text": "Say Lizzy has just watched “Arrival” and “Blade Runner 2049\", and now wants to be recommended some similar movies, because she loved these." }, { "code": null, "e": 1303, "s": 977, "text": "The main idea behind collaborative filtering methods, is to find users who also liked these movies and recommend unseen movies based on their preferences. In this example, the model would likely find that other users who enjoyed these movies also liked “Interstellar”, which would possibly be a nice recommendation for Lizzy." }, { "code": null, "e": 1509, "s": 1303, "text": "While this is the main idea, there are many approaches to this problem and choosing the more suited one will depend on multiple factors, such as the size of the dataset we’re working with and its sparsity." }, { "code": null, "e": 1624, "s": 1509, "text": "As mentioned, there are many collaborative filtering (CF in short) methods, bellow are the main types we can find:" }, { "code": null, "e": 1637, "s": 1624, "text": "Memory-based" }, { "code": null, "e": 1881, "s": 1637, "text": "Memory-based methods use user rating historical data to compute the similarity between users or items. The idea behind these methods is to define a similarity measure between users or items, and find the most similar to recommend unseen items." }, { "code": null, "e": 1893, "s": 1881, "text": "Model-based" }, { "code": null, "e": 2210, "s": 1893, "text": "Model-based CF uses machine learning algorithms to predict users’ rating of unrated items. There are many model-based CF algorithms, the most commonly used are matrix factorization models such as to applying a SVD to reconstruct the rating matrix, latent Dirichlet allocation or Markov decision process based models." }, { "code": null, "e": 2217, "s": 2210, "text": "Hybrid" }, { "code": null, "e": 2603, "s": 2217, "text": "These aim to combine the memory-based and the model-based approaches. One of the main drawbacks of the above methods, is that you’ll find yourself having to choose between historical user rating data and user or item attributes. Hybrid methods enable us to leverage both, and hence tend to perform better in most cases. The most widely used methods nowadays are factorization machines." }, { "code": null, "e": 2719, "s": 2603, "text": "Let’s delve a little more into memory based methods now, since it is the method we’ll be implementing in this post." }, { "code": null, "e": 3028, "s": 2719, "text": "There are 2 main types of memory-based collaborative filtering algorithms: User-Based and Item-Based. While their difference is subtle, in practice they lead to very different approaches, so it is crucial to know which is the most convenient for each case. Let’s go through a quick overview of these methods:" }, { "code": null, "e": 3039, "s": 3028, "text": "User-Based" }, { "code": null, "e": 3146, "s": 3039, "text": "Here we find users that have seen/rated similar content, and use their preferences to recommend new items:" }, { "code": null, "e": 3454, "s": 3146, "text": "A drawback is that there tends to be many more users than items, which leads to much bigger user similarity matrices (this might be clear in the following section) leading to performance and memory issues on larger datasets, which forces to rely on parallelisation techniques or other approaches altogether." }, { "code": null, "e": 3615, "s": 3454, "text": "Another common problem is that we’ll suffer from a cold-start: There may be no to little information on a new user’s preferences, hence nothing to compare with." }, { "code": null, "e": 3626, "s": 3615, "text": "Item-Based" }, { "code": null, "e": 3765, "s": 3626, "text": "The idea is similar, but instead, starting from a given movie (or set of movies) we find similar movies based on other users’ preferences." }, { "code": null, "e": 3919, "s": 3765, "text": "Contrarily to user-based methods, item similarity matrices tend to be smaller, which will reduce the cost of finding neighbours in our similarity matrix." }, { "code": null, "e": 4046, "s": 3919, "text": "Also, since a single item is enough to recommend other similar items, this method will not suffer from the cold-start problem." }, { "code": null, "e": 4180, "s": 4046, "text": "A drawback of item-based methods is that they there tends to be a lower diversity in the recommendations as opposed to user-based CF." }, { "code": null, "e": 4436, "s": 4180, "text": "We’ll be using the same dataset as in the previous post, the MovieLens dataset, which contains rating data sets from the MovieLens web site. It contains on 1M anonymous ratings of approximately 4000 movies made by 6000 MovieLens users, released in 2/2003." }, { "code": null, "e": 4568, "s": 4436, "text": "We’ll be working with three .csv files: ratings, users, and movies. Please check the previous post for more details on the dataset." }, { "code": null, "e": 4853, "s": 4568, "text": "The first thing we’ll need to do, is to create the user-item matrix. This is essentially a pivoted table from the rating data, where the rows will be the users, the columns will be the movies and the dataframe is filled with the rating the user has given (if it exists , 0 otherwise):" }, { "code": null, "e": 4980, "s": 4853, "text": "user_item_m = ratings.pivot('user_id','movie_id','rating').fillna(0)print(f'Shape: {user_item_m.shape}')> Shape: (29909, 5840)" }, { "code": null, "e": 5069, "s": 4980, "text": "Which looks like (I’ve joined with the movies table so the titles can be seen here too):" }, { "code": null, "e": 5363, "s": 5069, "text": "Next, we will define a similarity matrix. Along the lines of the previous post on Content based recommenders, see the section Similarity between vectors, we want to find a proximity measure between all users (or items) in the user-item matrix. A commonly used measure is the cosine similarity." }, { "code": null, "e": 5741, "s": 5363, "text": "As we also saw, this similarity measure owns its name to the fact that it equals to the cosine of the angle between the two vectors being compared, user (or item) similarity vectors of scores in this case. The lower the angle between two vectors, the higher the cosine will be, hence yielding a higher similarity factor. See the aforementioned section for more details on this." }, { "code": null, "e": 5883, "s": 5741, "text": "We can use sklearn's metrics.pairwise sub-module for pairwise distance or similarity metrics, in this case we’ll be using cosine_similarity ." }, { "code": null, "e": 5926, "s": 5883, "text": "Note that the function, has the signature:" }, { "code": null, "e": 5999, "s": 5926, "text": "sklearn.metrics.pairwise.cosine_similarity(X, Y=None, dense_output=True)" }, { "code": null, "e": 6025, "s": 5999, "text": "Where Yis expected to be:" }, { "code": null, "e": 6167, "s": 6025, "text": "Y: ndarray or sparse array, shape: (n_samples_Y, n_features). If None, the output will be the pairwise similarities between all samples in X." }, { "code": null, "e": 6254, "s": 6167, "text": "So by only specifying X this will generate a similarity matrix from the samples in X :" }, { "code": null, "e": 7033, "s": 6254, "text": "from sklearn.metrics.pairwise import cosine_similarityX_user = cosine_similarity(user_item_m)print(X_user.shape)(6040, 6040)print(X_user)array([[1. , 0.063, 0.127, 0.116, 0.075, 0.15 , 0.035, 0.102], [0.063, 1. , 0.111, 0.145, 0.107, 0.105, 0.246, 0.161], [0.127, 0.111, 1. , 0.127, 0.066, 0.036, 0.185, 0.086], [0.116, 0.145, 0.127, 1. , 0.052, 0.016, 0.1 , 0.072], [0.075, 0.107, 0.066, 0.052, 1. , 0.052, 0.106, 0.18 ], [0.15 , 0.105, 0.036, 0.016, 0.052, 1. , 0.067, 0.085], [0.035, 0.246, 0.185, 0.1 , 0.106, 0.067, 1. , 0.202], [0.102, 0.161, 0.086, 0.072, 0.18 , 0.085, 0.202, 1. ], [0.174, 0.156, 0.1 , 0.092, 0.242, 0.078, 0.125, 0.217], [0.209, 0.162, 0.158, 0.096, 0.079, 0.124, 0.091, 0.109]])" }, { "code": null, "e": 7109, "s": 7033, "text": "This will generate a user similarity matrix, with shape (n_users, n_users)." }, { "code": null, "e": 7140, "s": 7109, "text": "And since X is expected to be:" }, { "code": null, "e": 7201, "s": 7140, "text": "X: ndarray or sparse array, shape: (n_samples_X, n_features)" }, { "code": null, "e": 7466, "s": 7201, "text": "By transposing the user-item matrix, our samples will now be the columns of the user-item matrix, i.e. the movies. So if our original user-item matrix is of shape (n,m) , by finding the cosine similarities on the transposed matrix we’ll end up with a (m,m) matrix:" }, { "code": null, "e": 7532, "s": 7466, "text": "X_item = cosine_similarity(user_item_m.T)X_item.shape(3706, 3706)" }, { "code": null, "e": 7581, "s": 7532, "text": "Which will represent the item similarity matrix." }, { "code": null, "e": 8048, "s": 7581, "text": "Having created the similarity matrices, we can now define some logic to find similar users. In the case of a user-based recommendation we want to find users similar to a new user to who we want to recommend movies, and since we already have the similarity scores, we only have to search for the highest values in a given user row, and from there select the top k. Once we have the k closest users, we can find the highest rated movies that the user has not seen yet." }, { "code": null, "e": 8277, "s": 8048, "text": "Of course in this case it is simpler, since we already have computed the similarity matrix between all users. In a real scenario, we’d have to update the similarity matrix with the new user, and then find the most similar users." }, { "code": null, "e": 8331, "s": 8277, "text": "The algorithm for used-based CF can be summarised as:" }, { "code": null, "e": 8549, "s": 8331, "text": "Compute the similarity between the new user with all other users (if not already done)Compute the mean rating of all movies of the k most similar usersRecommend the top n rated movies by other users unseen by the user" }, { "code": null, "e": 8636, "s": 8549, "text": "Compute the similarity between the new user with all other users (if not already done)" }, { "code": null, "e": 8702, "s": 8636, "text": "Compute the mean rating of all movies of the k most similar users" }, { "code": null, "e": 8769, "s": 8702, "text": "Recommend the top n rated movies by other users unseen by the user" }, { "code": null, "e": 8855, "s": 8769, "text": "Bellow is a function to implement a user-based CF recommender explained step by step:" }, { "code": null, "e": 9123, "s": 8855, "text": "As mentioned earlier, the difference in implementation between user and item-based CF systems is quite small. For this reason it might be a good idea to wrap both methods in a class, which once instantiated we’ll then use to recommend movies or items to a given user:" }, { "code": null, "e": 9394, "s": 9123, "text": "Before testing the recommender on some examples, it might be useful to define a function to see which are the preferences of a user to see if the recommendations make sense or not . Here I’m sorting the ratings given to the movies seen by a user and taking the first 10:" }, { "code": null, "e": 9655, "s": 9394, "text": "Testing a recommender is actually tougher than it may seem. In the movielens dataset, a lot of the users will have seen a bit of everything, in the sense that they will probably have given a high rating to movies from multiple genres, not just their favourite." }, { "code": null, "e": 10044, "s": 9655, "text": "A useful way to test the model, is to find some specific examples of users with specific tastes, for instance, with a clear preference for one or two genres. What I have done is to find users which have already seen a couple of movies, but from very few genres, meaning that they clearly have a preference for them. The recommender is hence expected to suggest movies from the same genre." }, { "code": null, "e": 10094, "s": 10044, "text": "Let’s start with some user-based recommendations:" }, { "code": null, "e": 10160, "s": 10094, "text": "Let’s try with a user which seems to have a preference for Drama:" }, { "code": null, "e": 10253, "s": 10160, "text": "rec = CfRec(user_item_m, X_user, movies)because_user_liked(user_item_m, movies, ratings, 69)" }, { "code": null, "e": 10386, "s": 10253, "text": "We can see that the movies that have been most highly rated by this user, are Drama movies. Let’s see what the recommender suggests:" }, { "code": null, "e": 10415, "s": 10386, "text": "rec.recommend_user_based(69)" }, { "code": null, "e": 10609, "s": 10415, "text": "The recommendations seem good! Hard to tell whether the user would completely agree with the specific movies, but the genre preferences of the user are clearly reflected in the recommendations." }, { "code": null, "e": 10652, "s": 10609, "text": "Let’s try with a fan of Horror movies now:" }, { "code": null, "e": 10707, "s": 10652, "text": "because_user_liked(user_item_m, movies, ratings, 2155)" }, { "code": null, "e": 10738, "s": 10707, "text": "rec.recommend_user_based(2155)" }, { "code": null, "e": 10827, "s": 10738, "text": "“The Shining”, “Alien”... sounds like this user is missing out on these horror classics!" }, { "code": null, "e": 10878, "s": 10827, "text": "Let’s try now with some item-based recommendations" }, { "code": null, "e": 11023, "s": 10878, "text": "The first thing we’ll have to do is create another instance of the class, but using the item similarity matrix this time as a similarity matrix:" }, { "code": null, "e": 11064, "s": 11023, "text": "rec = CfRec(user_item_m, X_item, movies)" }, { "code": null, "e": 11238, "s": 11064, "text": "Here, as earlier discussed, the logic is to recommend movies based on some other movie. Let’s see what the recommender suggests for a user who likes the sci-fi classic Dune:" }, { "code": null, "e": 11331, "s": 11238, "text": "rec.recommend_item_based(2021)>> Because you liked Dune (1984), we'd recommend you to watch:" }, { "code": null, "e": 11427, "s": 11331, "text": "We can see that all recommended movies are from the same genre, and seem like good suggestions." }, { "code": null, "e": 11504, "s": 11427, "text": "If we liked Se7en, a Crime and Thriller movie, we’d be recommended to watch:" }, { "code": null, "e": 11598, "s": 11504, "text": "rec.recommend_item_based(47)>> Because you liked (Se7en) (1995), we'd recommend you to watch:" }, { "code": null, "e": 11649, "s": 11598, "text": "And finally, for a classic animation movie, Bambi:" }, { "code": null, "e": 11743, "s": 11649, "text": "rec.recommend_item_based(2018)>> Because you liked Bambi (1942), we'd recommend you to watch:" }, { "code": null, "e": 11846, "s": 11743, "text": "So in both cases, the implemented collaborative filtering models seem to provide good recommendations." }, { "code": null, "e": 12208, "s": 11846, "text": "There are many improvements that could be done. For instance, we could account for the fact that users can behave very differently when it comes to rating movies. Some users might rate very highly all movies, whereas other might be much more critical. This could be done by subtracting the average score from each user, we’d then have normalised score per user." }, { "code": null, "e": 12424, "s": 12208, "text": "I hope how ever, that this example has been illustrative in terms of how collaborative filtering methods work. I’d encourage you to take it as a starting point and perhaps tweak it a little or add some improvements." } ]
GATE | GATE-CS-2017 (Set 2) | Question 31 - GeeksforGeeks
10 Sep, 2021 Which of the following statements about the parser is/are correct? I. Canonical LR is more powerful than SLR. II. SLR is more powerful than LALR. III. SLR is more powerful than canonical LR. (A) I only(B) II only(C) III only(D) II and III onlyAnswer: (A)Explanation: LR parsers in term of power CLR > LALR > SLR > LR(0) Therefore, Option A is only correct option. YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch 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:001:02 / 52:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=Sn5eIxvrNBc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question GATE-CS-2017 (Set 2) GATE-GATE-CS-2017 (Set 2) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 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-2000 | Question 41 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 24612, "s": 24584, "text": "\n10 Sep, 2021" }, { "code": null, "e": 24679, "s": 24612, "text": "Which of the following statements about the parser is/are correct?" }, { "code": null, "e": 24804, "s": 24679, "text": "I. Canonical LR is more powerful than SLR.\nII. SLR is more powerful than LALR.\nIII. SLR is more powerful than canonical LR.\n" }, { "code": null, "e": 24908, "s": 24804, "text": "(A) I only(B) II only(C) III only(D) II and III onlyAnswer: (A)Explanation: LR parsers in term of power" }, { "code": null, "e": 24933, "s": 24908, "text": "CLR > LALR > SLR > LR(0)" }, { "code": null, "e": 24977, "s": 24933, "text": "Therefore, Option A is only correct option." }, { "code": null, "e": 25873, "s": 24977, "text": "YouTubeGeeksforGeeks GATE Computer Science16.3K subscribersGATE PYQ - Parsing and SDT (Continued) Part 3 with Joyojyoti AcharyaWatch 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:001:02 / 52:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=Sn5eIxvrNBc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question" }, { "code": null, "e": 25894, "s": 25873, "text": "GATE-CS-2017 (Set 2)" }, { "code": null, "e": 25920, "s": 25894, "text": "GATE-GATE-CS-2017 (Set 2)" }, { "code": null, "e": 25925, "s": 25920, "text": "GATE" }, { "code": null, "e": 26023, "s": 25925, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26057, "s": 26023, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26091, "s": 26057, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26124, "s": 26091, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26160, "s": 26124, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26194, "s": 26160, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26230, "s": 26194, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26264, "s": 26230, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26298, "s": 26264, "text": "GATE | GATE-CS-2009 | Question 38" }, { "code": null, "e": 26332, "s": 26298, "text": "GATE | GATE-CS-2000 | Question 41" } ]
Error Handling in OpenGL - GeeksforGeeks
18 May, 2021 Many of the features of the OpenGL API are very useful and powerful. But, it’s quite possible that OpenGL programs may contain errors. So, it becomes important to learn error handling in OpenGL programs. The OpenGL and GLU libraries have a simple method of recording errors. When an OpenGL program encounters an error in a call to a base library routine or a GLU routine, it records an error code internally, and the routine which caused the error is ignored. Although, OpenGL records only a single error code at any given time. OpenGL uses its own methods to detect errors. Once an error occurs, no other error code will be recorded until the program explicitly queries the OpenGL error state. Syntax: GLenum code;code = glGetError (); This function call returns the current error code and clears the internal error flag: If the returned value is equal to the GLNOERROR OpenGL symbolic constant, everything is fine. If there is any other return value, then it indicates that a problem has occurred. The base OpenGL library provides a definition for a number of symbolic constants which represent different error conditions. The GLU library also defines a number of error codes, but most of them have almost meaningless names such as GLUNURBSERROR1, GLUNURBSERROR2, and so on. The GLU library contains a function that returns a descriptive string for each of the GLU and GL errors. To use it, first retrieve the current error code and then pass it as a parameter to this function. The return value can be printed out using the C standard library functions like fprintf() function. Below is the code snippet to implement the above approach: C #include <stdio.h>GLenum code; const GLubyte* string;code = glGetError();string = gluErrorString(code);fprintf(stderr, "OpenGL error: %s\n", string); Explanation: The value returned by gluErrorString points to a string located inside the GLU library. Since it is not a dynamically allocated string, so it must not be explicitly deallocated by the program. Additionally, it mustn’t be modified by the program (therefore, the const modifier on the declaration of string). It is quite easy to encapsulate these function calls into a general error-reporting function in the program. The function given below will retrieve the current error code, print the descriptive error string, and return the code to the calling routine: C // C program for the above approach#include <stdio.h> GLenum errorCheck(){ GLenum code; const GLubyte* string; code = glGetError(); if (code != GL_NO_ERROR) { string = gluErrorString(code); fprintf(stderr, "OpenGL error: %s\n", string); } return code;} Explanation: By default, glGetError only prints error numbers, which isn’t easy to understand unless error codes have been memorized already. Thus, it often makes sense to write a small helper function to easily print out the error strings together with where the error check function was called: GLenum glCheckError_(const char *file, int line){ GLenum errorCode; while ((errorCode = glGetError()) != GL_NO_ERROR) { std::string error; switch (errorCode) { case GL_INVALID_ENUM: error = “INVALID_ENUM”; break; case GL_INVALID_VALUE: error = “INVALID_VALUE”; break; case GL_INVALID_OPERATION: error = “INVALID_OPERATION”; break; case GL_STACK_OVERFLOW: error = “STACK_OVERFLOW”; break; case GL_STACK_UNDERFLOW: error = “STACK_UNDERFLOW”; break; case GL_OUT_OF_MEMORY: error = “OUT_OF_MEMORY”; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = “INVALID_FRAMEBUFFER_OPERATION”; break; } std::cout << error << ” | ” << file << ” (” << line << “)” << std::endl; } return errorCode;}#define glCheckError() glCheckError_(__FILE__, __LINE__) It’s helpful to more precisely know which glCheckError call returned the error if any of these glCheckError calls are grouped in our database. glBindBuffer(GL_VERTEX_ARRAY, vbo);glCheckError(); Output Example: c-graphics OpenGL Articles C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity Docker - COPY Instruction Time complexities of different data structures Difference between Class and Object SQL | Date functions Arrays in C/C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() std::sort() in C++ STL Bitwise Operators in C/C++ Multidimensional Arrays in C / C++
[ { "code": null, "e": 25751, "s": 25723, "text": "\n18 May, 2021" }, { "code": null, "e": 26446, "s": 25751, "text": "Many of the features of the OpenGL API are very useful and powerful. But, it’s quite possible that OpenGL programs may contain errors. So, it becomes important to learn error handling in OpenGL programs. The OpenGL and GLU libraries have a simple method of recording errors. When an OpenGL program encounters an error in a call to a base library routine or a GLU routine, it records an error code internally, and the routine which caused the error is ignored. Although, OpenGL records only a single error code at any given time. OpenGL uses its own methods to detect errors. Once an error occurs, no other error code will be recorded until the program explicitly queries the OpenGL error state." }, { "code": null, "e": 26454, "s": 26446, "text": "Syntax:" }, { "code": null, "e": 26488, "s": 26454, "text": "GLenum code;code = glGetError ();" }, { "code": null, "e": 26574, "s": 26488, "text": "This function call returns the current error code and clears the internal error flag:" }, { "code": null, "e": 26668, "s": 26574, "text": "If the returned value is equal to the GLNOERROR OpenGL symbolic constant, everything is fine." }, { "code": null, "e": 26751, "s": 26668, "text": "If there is any other return value, then it indicates that a problem has occurred." }, { "code": null, "e": 27028, "s": 26751, "text": "The base OpenGL library provides a definition for a number of symbolic constants which represent different error conditions. The GLU library also defines a number of error codes, but most of them have almost meaningless names such as GLUNURBSERROR1, GLUNURBSERROR2, and so on." }, { "code": null, "e": 27332, "s": 27028, "text": "The GLU library contains a function that returns a descriptive string for each of the GLU and GL errors. To use it, first retrieve the current error code and then pass it as a parameter to this function. The return value can be printed out using the C standard library functions like fprintf() function." }, { "code": null, "e": 27391, "s": 27332, "text": "Below is the code snippet to implement the above approach:" }, { "code": null, "e": 27393, "s": 27391, "text": "C" }, { "code": "#include <stdio.h>GLenum code; const GLubyte* string;code = glGetError();string = gluErrorString(code);fprintf(stderr, \"OpenGL error: %s\\n\", string);", "e": 27544, "s": 27393, "text": null }, { "code": null, "e": 27973, "s": 27544, "text": "Explanation: The value returned by gluErrorString points to a string located inside the GLU library. Since it is not a dynamically allocated string, so it must not be explicitly deallocated by the program. Additionally, it mustn’t be modified by the program (therefore, the const modifier on the declaration of string). It is quite easy to encapsulate these function calls into a general error-reporting function in the program." }, { "code": null, "e": 28116, "s": 27973, "text": "The function given below will retrieve the current error code, print the descriptive error string, and return the code to the calling routine:" }, { "code": null, "e": 28118, "s": 28116, "text": "C" }, { "code": "// C program for the above approach#include <stdio.h> GLenum errorCheck(){ GLenum code; const GLubyte* string; code = glGetError(); if (code != GL_NO_ERROR) { string = gluErrorString(code); fprintf(stderr, \"OpenGL error: %s\\n\", string); } return code;}", "e": 28404, "s": 28118, "text": null }, { "code": null, "e": 28701, "s": 28404, "text": "Explanation: By default, glGetError only prints error numbers, which isn’t easy to understand unless error codes have been memorized already. Thus, it often makes sense to write a small helper function to easily print out the error strings together with where the error check function was called:" }, { "code": null, "e": 29660, "s": 28701, "text": "GLenum glCheckError_(const char *file, int line){ GLenum errorCode; while ((errorCode = glGetError()) != GL_NO_ERROR) { std::string error; switch (errorCode) { case GL_INVALID_ENUM: error = “INVALID_ENUM”; break; case GL_INVALID_VALUE: error = “INVALID_VALUE”; break; case GL_INVALID_OPERATION: error = “INVALID_OPERATION”; break; case GL_STACK_OVERFLOW: error = “STACK_OVERFLOW”; break; case GL_STACK_UNDERFLOW: error = “STACK_UNDERFLOW”; break; case GL_OUT_OF_MEMORY: error = “OUT_OF_MEMORY”; break; case GL_INVALID_FRAMEBUFFER_OPERATION: error = “INVALID_FRAMEBUFFER_OPERATION”; break; } std::cout << error << ” | ” << file << ” (” << line << “)” << std::endl; } return errorCode;}#define glCheckError() glCheckError_(__FILE__, __LINE__) " }, { "code": null, "e": 29803, "s": 29660, "text": "It’s helpful to more precisely know which glCheckError call returned the error if any of these glCheckError calls are grouped in our database." }, { "code": null, "e": 29854, "s": 29803, "text": "glBindBuffer(GL_VERTEX_ARRAY, vbo);glCheckError();" }, { "code": null, "e": 29870, "s": 29854, "text": "Output Example:" }, { "code": null, "e": 29881, "s": 29870, "text": "c-graphics" }, { "code": null, "e": 29888, "s": 29881, "text": "OpenGL" }, { "code": null, "e": 29897, "s": 29888, "text": "Articles" }, { "code": null, "e": 29908, "s": 29897, "text": "C Language" }, { "code": null, "e": 29919, "s": 29908, "text": "C Programs" }, { "code": null, "e": 30017, "s": 29919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30054, "s": 30017, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 30080, "s": 30054, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30127, "s": 30080, "text": "Time complexities of different data structures" }, { "code": null, "e": 30163, "s": 30127, "text": "Difference between Class and Object" }, { "code": null, "e": 30184, "s": 30163, "text": "SQL | Date functions" }, { "code": null, "e": 30200, "s": 30184, "text": "Arrays in C/C++" }, { "code": null, "e": 30278, "s": 30200, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 30301, "s": 30278, "text": "std::sort() in C++ STL" }, { "code": null, "e": 30328, "s": 30301, "text": "Bitwise Operators in C/C++" } ]
How to send data through wifi in android programmatically?
This example demonstrate about send data through wifi in android programmatically Need Server and Client Project Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" tools:context = ".MainActivity"> <TextView android:id = "@+id/tvIP" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" /> <TextView android:id = "@+id/tvPort" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_below = "@+id/tvIP" android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" /> <TextView android:id = "@+id/tvConnectionStatus" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_below = "@+id/tvPort" android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" /> <TextView android:id = "@+id/tvMessages" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_above = "@+id/etMessage" android:layout_below = "@+id/tvConnectionStatus" android:inputType = "textMultiLine" android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" /> <EditText android:id = "@+id/etMessage" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_above = "@+id/btnSend" android:hint = "Enter Message" android:inputType = "text" /> <Button android:id = "@+id/btnSend" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_alignParentBottom = "true" android:text = "SEND" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java package com.server.myapplication.server; import android.annotation.SuppressLint; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.ByteOrder; @SuppressLint("SetTextI18n") public class MainActivity extends AppCompatActivity { ServerSocket serverSocket; Thread Thread1 = null; TextView tvIP, tvPort; TextView tvMessages; EditText etMessage; Button btnSend; public static String SERVER_IP = ""; public static final int SERVER_PORT = 8080; String message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvIP = findViewById(R.id.tvIP); tvPort = findViewById(R.id.tvPort); tvMessages = findViewById(R.id.tvMessages); etMessage = findViewById(R.id.etMessage); btnSend = findViewById(R.id.btnSend); try { SERVER_IP = getLocalIpAddress(); } catch (UnknownHostException e) { e.printStackTrace(); } Thread1 = new Thread(new Thread1()); Thread1.start(); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { message = etMessage.getText().toString().trim(); if (!message.isEmpty()) { new Thread(new Thread3(message)).start(); } } }); } private String getLocalIpAddress() throws UnknownHostException { WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); assert wifiManager ! = null; WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipInt = wifiInfo.getIpAddress(); return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress(); } private PrintWriter output; private BufferedReader input; class Thread1 implements Runnable { @Override public void run() { Socket socket; try { serverSocket = new ServerSocket(SERVER_PORT); runOnUiThread(new Runnable() { @Override public void run() { tvMessages.setText("Not connected"); tvIP.setText("IP: " + SERVER_IP); tvPort.setText("Port: " + String.valueOf(SERVER_PORT)); } }); try { socket = serverSocket.accept(); output = new PrintWriter(socket.getOutputStream()); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); runOnUiThread(new Runnable() { @Override public void run() { tvMessages.setText("Connected\n"); } }); new Thread(new Thread2()).start(); } catch (IOException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } } private class Thread2 implements Runnable { @Override public void run() { while (true) { try { final String message = input.readLine(); if (message ! = null) { runOnUiThread(new Runnable() { @Override public void run() { tvMessages.append("client:" + message + "\n"); } }); } else { Thread1 = new Thread(new Thread1()); Thread1.start(); return; } } catch (IOException e) { e.printStackTrace(); } } } } class Thread3 implements Runnable { private String message; Thread3(String message) { this.message = message; } @Override public void run() { output.write(message); output.flush(); runOnUiThread(new Runnable() { @Override public void run() { tvMessages.append("server: " + message + "\n"); etMessage.setText(""); } }); } } } Step 4 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.example.myapplication"> <uses-permission android:name = "android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name = "android.permission.INTERNET"/> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = ".MainActivity" android:label = "Server"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "16dp" tools:context = ".MainActivity"> <EditText android:id = "@+id/etIP" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:hint = "IP-Address" android:inputType = "text" /> <EditText android:id = "@+id/etPort" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_below = "@+id/etIP" android:hint = "Port No" android:inputType = "number" /> <Button android:id = "@+id/btnConnect" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_below = "@+id/etPort" android:layout_gravity = "center" android:layout_marginTop = "16dp" android:text = "Connect To Server" /> <TextView android:id = "@+id/tvMessages" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_above = "@+id/etMessage" android:layout_below = "@+id/btnConnect" android:inputType = "textMultiLine" android:textAppearance = "@style/Base.TextAppearance.AppCompat.Medium" /> <EditText android:id = "@+id/etMessage" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_above = "@+id/btnSend" android:hint = "Enter Message" android:inputType = "text" /> <Button android:id = "@+id/btnSend" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_alignParentBottom = "true" android:text = "SEND" /> </RelativeLayout> Step 3 − Add the following code to res/layout/MainActivity.java. package com.client.myapplication.client; import android.annotation.SuppressLint; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; @SuppressLint("SetTextI18n") public class MainActivity extends AppCompatActivity { Thread Thread1 = null; EditText etIP, etPort; TextView tvMessages; EditText etMessage; Button btnSend; String SERVER_IP; int SERVER_PORT; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etIP = findViewById(R.id.etIP); etPort = findViewById(R.id.etPort); tvMessages = findViewById(R.id.tvMessages); etMessage = findViewById(R.id.etMessage); btnSend = findViewById(R.id.btnSend); Button btnConnect = findViewById(R.id.btnConnect); btnConnect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tvMessages.setText(""); SERVER_IP = etIP.getText().toString().trim(); SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim()); Thread1 = new Thread(new Thread1()); Thread1.start(); } }); btnSend.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String message = etMessage.getText().toString().trim(); if (!message.isEmpty()) { new Thread(new Thread3(message)).start(); } } }); } private PrintWriter output; private BufferedReader input; class Thread1 implements Runnable { @Override public void run() { Socket socket; try { socket = new Socket(SERVER_IP, SERVER_PORT); output = new PrintWriter(socket.getOutputStream()); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); runOnUiThread(new Runnable() { @Override public void run() { tvMessages.setText("Connected\n"); } }); new Thread(new Thread2()).start(); } catch (IOException e) { e.printStackTrace(); } } } class Thread2 implements Runnable { @Override public void run() { while (true) { try { final String message = input.readLine(); if (message ! = null) { runOnUiThread(new Runnable() { @Override public void run() { tvMessages.append("server: " + message + "\n"); } }); } else { Thread1 = new Thread(new Thread1()); Thread1.start(); return; } } catch (IOException e) { e.printStackTrace(); } } } } class Thread3 implements Runnable { private String message; Thread3(String message) { this.message = message; } @Override public void run() { output.write(message); output.flush(); runOnUiThread(new Runnable() { @Override public void run() { tvMessages.append("client: " + message + "\n"); etMessage.setText(""); } }); } } } Step 4 − Add the following code to androidManifest.xml <?xml version = "1.0" encoding = "utf-8"?> <manifest xmlns:android = "http://schemas.android.com/apk/res/android" package = "com.client.myapplication.client"> <uses-permission android:name = "android.permission.INTERNET" /> <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup = "true" android:icon = "@mipmap/ic_launcher" android:label = "@string/app_name" android:roundIcon = "@mipmap/ic_launcher_round" android:supportsRtl = "true" android:theme = "@style/AppTheme"> <activity android:name = "com.client.myapplication.client.MainActivity" android:label = "Client"> <intent-filter> <action android:name = "android.intent.action.MAIN" /> <category android:name = "android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your both server and client application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code
[ { "code": null, "e": 1144, "s": 1062, "text": "This example demonstrate about send data through wifi in android programmatically" }, { "code": null, "e": 1175, "s": 1144, "text": "Need Server and Client Project" }, { "code": null, "e": 1304, "s": 1175, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1369, "s": 1304, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3281, "s": 1369, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n tools:context = \".MainActivity\">\n <TextView\n android:id = \"@+id/tvIP\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <TextView\n android:id = \"@+id/tvPort\"\n android:layout_width = \"wrap_content\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/tvIP\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <TextView\n android:id = \"@+id/tvConnectionStatus\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/tvPort\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <TextView\n android:id = \"@+id/tvMessages\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/etMessage\"\n android:layout_below = \"@+id/tvConnectionStatus\"\n android:inputType = \"textMultiLine\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <EditText\n android:id = \"@+id/etMessage\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/btnSend\"\n android:hint = \"Enter Message\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/btnSend\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentBottom = \"true\"\n android:text = \"SEND\" />\n</RelativeLayout>" }, { "code": null, "e": 3338, "s": 3281, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 8089, "s": 3338, "text": "package com.server.myapplication.server;\n\nimport android.annotation.SuppressLint;\nimport android.net.wifi.WifiInfo;\nimport android.net.wifi.WifiManager;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.InetAddress;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.net.UnknownHostException;\nimport java.nio.ByteBuffer;\nimport java.nio.ByteOrder;\n\n@SuppressLint(\"SetTextI18n\")\npublic class MainActivity extends AppCompatActivity {\n ServerSocket serverSocket;\n Thread Thread1 = null;\n TextView tvIP, tvPort;\n TextView tvMessages;\n EditText etMessage;\n Button btnSend;\n public static String SERVER_IP = \"\";\n public static final int SERVER_PORT = 8080;\n String message;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n tvIP = findViewById(R.id.tvIP);\n tvPort = findViewById(R.id.tvPort);\n tvMessages = findViewById(R.id.tvMessages);\n etMessage = findViewById(R.id.etMessage);\n btnSend = findViewById(R.id.btnSend);\n try {\n SERVER_IP = getLocalIpAddress();\n } catch (UnknownHostException e) {\n e.printStackTrace();\n }\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n btnSend.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n message = etMessage.getText().toString().trim();\n if (!message.isEmpty()) {\n new Thread(new Thread3(message)).start();\n }\n }\n });\n }\n private String getLocalIpAddress() throws UnknownHostException {\n WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);\n assert wifiManager ! = null;\n WifiInfo wifiInfo = wifiManager.getConnectionInfo();\n int ipInt = wifiInfo.getIpAddress();\n return InetAddress.getByAddress(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(ipInt).array()).getHostAddress();\n }\n private PrintWriter output;\n private BufferedReader input;\n class Thread1 implements Runnable {\n @Override\n public void run() {\n Socket socket;\n try {\n serverSocket = new ServerSocket(SERVER_PORT);\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.setText(\"Not connected\");\n tvIP.setText(\"IP: \" + SERVER_IP);\n tvPort.setText(\"Port: \" + String.valueOf(SERVER_PORT));\n }\n });\n try {\n socket = serverSocket.accept();\n output = new PrintWriter(socket.getOutputStream());\n input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.setText(\"Connected\\n\");\n }\n });\n new Thread(new Thread2()).start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n private class Thread2 implements Runnable {\n @Override\n public void run() {\n while (true) {\n try {\n final String message = input.readLine();\n if (message ! = null) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"client:\" + message + \"\\n\");\n }\n });\n } else {\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n return;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n class Thread3 implements Runnable {\n private String message;\n Thread3(String message) {\n this.message = message;\n }\n @Override\n public void run() {\n output.write(message);\n output.flush();\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"server: \" + message + \"\\n\");\n etMessage.setText(\"\");\n }\n });\n }\n }\n}" }, { "code": null, "e": 8144, "s": 8089, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 9103, "s": 8144, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.example.myapplication\">\n <uses-permission android:name = \"android.permission.ACCESS_WIFI_STATE\" />\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_STATE\" />\n <uses-permission android:name = \"android.permission.INTERNET\"/>\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity android:name = \".MainActivity\" android:label = \"Server\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 9232, "s": 9103, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 9297, "s": 9232, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 11214, "s": 9297, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<RelativeLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n android:layout_margin = \"16dp\"\n tools:context = \".MainActivity\">\n <EditText\n android:id = \"@+id/etIP\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:hint = \"IP-Address\"\n android:inputType = \"text\" />\n <EditText\n android:id = \"@+id/etPort\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/etIP\"\n android:hint = \"Port No\"\n android:inputType = \"number\" />\n <Button\n android:id = \"@+id/btnConnect\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_below = \"@+id/etPort\"\n android:layout_gravity = \"center\"\n android:layout_marginTop = \"16dp\"\n android:text = \"Connect To Server\" />\n <TextView\n android:id = \"@+id/tvMessages\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/etMessage\"\n android:layout_below = \"@+id/btnConnect\"\n android:inputType = \"textMultiLine\"\n android:textAppearance = \"@style/Base.TextAppearance.AppCompat.Medium\" />\n <EditText\n android:id = \"@+id/etMessage\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_above = \"@+id/btnSend\"\n android:hint = \"Enter Message\"\n android:inputType = \"text\" />\n <Button\n android:id = \"@+id/btnSend\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"wrap_content\"\n android:layout_alignParentBottom = \"true\"\n android:text = \"SEND\" />\n</RelativeLayout>" }, { "code": null, "e": 11279, "s": 11214, "text": "Step 3 − Add the following code to res/layout/MainActivity.java." }, { "code": null, "e": 15023, "s": 11279, "text": "package com.client.myapplication.client;\n\nimport android.annotation.SuppressLint;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\nimport java.io.PrintWriter;\nimport java.net.Socket;\n\n@SuppressLint(\"SetTextI18n\")\npublic class MainActivity extends AppCompatActivity {\n Thread Thread1 = null;\n EditText etIP, etPort;\n TextView tvMessages;\n EditText etMessage;\n Button btnSend;\n String SERVER_IP;\n int SERVER_PORT;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n etIP = findViewById(R.id.etIP);\n etPort = findViewById(R.id.etPort);\n tvMessages = findViewById(R.id.tvMessages);\n etMessage = findViewById(R.id.etMessage);\n btnSend = findViewById(R.id.btnSend);\n Button btnConnect = findViewById(R.id.btnConnect);\n btnConnect.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n tvMessages.setText(\"\");\n SERVER_IP = etIP.getText().toString().trim();\n SERVER_PORT = Integer.parseInt(etPort.getText().toString().trim());\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n }\n });\n btnSend.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n String message = etMessage.getText().toString().trim();\n if (!message.isEmpty()) {\n new Thread(new Thread3(message)).start();\n }\n }\n });\n }\n private PrintWriter output;\n private BufferedReader input;\n class Thread1 implements Runnable {\n @Override\n public void run() {\n Socket socket;\n try {\n socket = new Socket(SERVER_IP, SERVER_PORT);\n output = new PrintWriter(socket.getOutputStream());\n input = new BufferedReader(new InputStreamReader(socket.getInputStream()));\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.setText(\"Connected\\n\");\n }\n });\n new Thread(new Thread2()).start();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n class Thread2 implements Runnable {\n @Override\n public void run() {\n while (true) {\n try {\n final String message = input.readLine();\n if (message ! = null) {\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"server: \" + message + \"\\n\");\n }\n });\n } else {\n Thread1 = new Thread(new Thread1());\n Thread1.start();\n return;\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n }\n }\n class Thread3 implements Runnable {\n private String message;\n Thread3(String message) {\n this.message = message;\n }\n @Override\n public void run() {\n output.write(message);\n output.flush();\n runOnUiThread(new Runnable() {\n @Override\n public void run() {\n tvMessages.append(\"client: \" + message + \"\\n\");\n etMessage.setText(\"\");\n }\n });\n }\n }\n}" }, { "code": null, "e": 15078, "s": 15023, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 16016, "s": 15078, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<manifest xmlns:android = \"http://schemas.android.com/apk/res/android\"\n package = \"com.client.myapplication.client\">\n <uses-permission android:name = \"android.permission.INTERNET\" />\n <uses-permission android:name = \"android.permission.ACCESS_NETWORK_STATE\" />\n <application\n android:allowBackup = \"true\"\n android:icon = \"@mipmap/ic_launcher\"\n android:label = \"@string/app_name\"\n android:roundIcon = \"@mipmap/ic_launcher_round\"\n android:supportsRtl = \"true\"\n android:theme = \"@style/AppTheme\">\n <activity\n android:name = \"com.client.myapplication.client.MainActivity\"\n android:label = \"Client\">\n <intent-filter>\n <action android:name = \"android.intent.action.MAIN\" />\n <category android:name = \"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 16388, "s": 16016, "text": "Let's try to run your both server and client application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 16428, "s": 16388, "text": "Click here to download the project code" } ]
Replace all 0's with 5 | Practice | GeeksforGeeks
Given a number N. The task is to complete the function convertFive() which replace all zeros in the number with 5 and returns the number. Input: The first line of input contains an integer T, denoting the number of testcases. Then T testcases follow. Each testcase contains a single integer N denoting the number. Output: The function will return integer where all zero's are converted to 5. User Task: Since this is a functional problem you don't have to worry about input, you just have to complete the function convertFive(). Constraints: 1 <= T <= 103 1 <= N <= 104 Example: Input 2 1004 121 Output 1554 121 Explanation: Testcase 1: At index 1 and 2 there is 0 so we replace it with 5. Testcase 2: There is no ,0 so output will remain same. 0 heyankit22 minutes ago simple solution in python def convertFive(self,n): new_str = str(n) return int(new_str.replace("0","5")) 0 yashvardhanyadav82 days ago int convertFive(int n) { int num=0,i=0; while (n!=0){ if (n%10==0){ num = num + 5*pow(10,i); n = n/10; i++; } else{ num = num + (n%10)*pow(10,i); n = n/10; i++; } } return num; } 0 sanskarnaredi0075 days ago public static int convertFive(int n){ //add code here. String str = Integer.toString(n); String str1 = str.replace("0","5"); n = Integer.parseInt(str1); return n; } 0 sanskarnaredi007 This comment was deleted. 0 vishalsinghrajput1 week ago def convertFive(self,n): ss= str(n) ss2=[] ss3="" for i in range(len(ss)): if ss[i]=='0': ss2.insert(i,'5') else: ss2.insert(i,ss[i]) for i in range(len(ss2)): ss3+=ss2[i] return int(ss3) 0 ritikraaj771 week ago Without using String just MATH class Solution{ public static int convertFive(int n){ //add code here. int r = 0,s= 0; int c = 0,d = 0; int t = n; while(n>0){ r=n%10; if(r==0){ if(c!=0){ s=s+10*c*5; c=c*10; } else if(c==0){ s=s+5; c=c+1; } } else if(r!=0){ if(c!=0){ s=s+r*10*c; c=c*10; } else if(c==0){ s=s+r; c=c+1; } } n=n/10; } return s; } } 0 tarunyarram98 This comment was deleted. 0 monsotal3 weeks ago JAVA class Solution{public static int convertFive(int n){ String number = String.valueOf(n); String newnumber = ""; for(int i=0 ; i< number.length() ; i++){ // check if current index equal to ASCII value of the number 0(48). if(number.charAt(i) == 48){ newnumber += "5"; } else{ newnumber += number.charAt(i); } } int parsednumber = Integer.parseInt(newnumber); return parsednumber; } 0 prateekkasaudhan1233 weeks ago // java solutions class Solution{public static int convertFive(int n){ String s = Integer.toString(n); String newS = ""; for(int i=0; i<s.length(); i++){ if(s.charAt(i)=='0') newS += '5'; else newS += s.charAt(i); } int ans = Integer.parseInt(newS); return ans; }} 0 aravindmn75833 weeks ago simple solution in c++_____ by converting from int to string after that if char is “0” replace with “5” return string to int____ int conversion(int n){ string s =to_string(n); for(int i=0; i<s.length(); i++){ if(s[i]=='0'){ s[i]='5'; } } return n = stoi(s); } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 376, "s": 238, "text": "Given a number N. The task is to complete the function convertFive() which replace all zeros in the number with 5 and returns the number." }, { "code": null, "e": 552, "s": 376, "text": "Input:\nThe first line of input contains an integer T, denoting the number of testcases. Then T testcases follow. Each testcase contains a single integer N denoting the number." }, { "code": null, "e": 630, "s": 552, "text": "Output:\nThe function will return integer where all zero's are converted to 5." }, { "code": null, "e": 767, "s": 630, "text": "User Task:\nSince this is a functional problem you don't have to worry about input, you just have to complete the function convertFive()." }, { "code": null, "e": 808, "s": 767, "text": "Constraints:\n1 <= T <= 103\n1 <= N <= 104" }, { "code": null, "e": 834, "s": 808, "text": "Example:\nInput\n2\n1004\n121" }, { "code": null, "e": 850, "s": 834, "text": "Output\n1554\n121" }, { "code": null, "e": 984, "s": 850, "text": "Explanation:\nTestcase 1: At index 1 and 2 there is 0 so we replace it with 5.\nTestcase 2: There is no ,0 so output will remain same." }, { "code": null, "e": 986, "s": 984, "text": "0" }, { "code": null, "e": 1009, "s": 986, "text": "heyankit22 minutes ago" }, { "code": null, "e": 1035, "s": 1009, "text": "simple solution in python" }, { "code": null, "e": 1126, "s": 1035, "text": "def convertFive(self,n): new_str = str(n) return int(new_str.replace(\"0\",\"5\"))" }, { "code": null, "e": 1128, "s": 1126, "text": "0" }, { "code": null, "e": 1156, "s": 1128, "text": "yashvardhanyadav82 days ago" }, { "code": null, "e": 1487, "s": 1156, "text": "int convertFive(int n) { int num=0,i=0; while (n!=0){ if (n%10==0){ num = num + 5*pow(10,i); n = n/10; i++; } else{ num = num + (n%10)*pow(10,i); n = n/10; i++; } } return num; }" }, { "code": null, "e": 1489, "s": 1487, "text": "0" }, { "code": null, "e": 1516, "s": 1489, "text": "sanskarnaredi0075 days ago" }, { "code": null, "e": 1705, "s": 1516, "text": "public static int convertFive(int n){ //add code here. String str = Integer.toString(n); String str1 = str.replace(\"0\",\"5\"); n = Integer.parseInt(str1); return n; }" }, { "code": null, "e": 1707, "s": 1705, "text": "0" }, { "code": null, "e": 1724, "s": 1707, "text": "sanskarnaredi007" }, { "code": null, "e": 1750, "s": 1724, "text": "This comment was deleted." }, { "code": null, "e": 1752, "s": 1750, "text": "0" }, { "code": null, "e": 1780, "s": 1752, "text": "vishalsinghrajput1 week ago" }, { "code": null, "e": 2098, "s": 1780, "text": "def convertFive(self,n):\n ss= str(n)\n ss2=[]\n ss3=\"\"\n for i in range(len(ss)):\n if ss[i]=='0':\n ss2.insert(i,'5')\n \n else:\n ss2.insert(i,ss[i])\n for i in range(len(ss2)):\n ss3+=ss2[i]\n return int(ss3)" }, { "code": null, "e": 2100, "s": 2098, "text": "0" }, { "code": null, "e": 2122, "s": 2100, "text": "ritikraaj771 week ago" }, { "code": null, "e": 2153, "s": 2122, "text": "Without using String just MATH" }, { "code": null, "e": 2752, "s": 2153, "text": "class Solution{\n\tpublic static int convertFive(int n){\n //add code here.\n int r = 0,s= 0;\n int c = 0,d = 0;\n int t = n;\n while(n>0){\n r=n%10;\n if(r==0){\n if(c!=0){\n s=s+10*c*5;\n c=c*10;\n }\n else if(c==0){\n s=s+5;\n c=c+1;\n }\n }\n else if(r!=0){\n if(c!=0){\n s=s+r*10*c;\n c=c*10;\n }\n else if(c==0){\n s=s+r;\n c=c+1;\n }\n }\n n=n/10;\n }\n return s;\n }\n}" }, { "code": null, "e": 2754, "s": 2752, "text": "0" }, { "code": null, "e": 2768, "s": 2754, "text": "tarunyarram98" }, { "code": null, "e": 2794, "s": 2768, "text": "This comment was deleted." }, { "code": null, "e": 2796, "s": 2794, "text": "0" }, { "code": null, "e": 2816, "s": 2796, "text": "monsotal3 weeks ago" }, { "code": null, "e": 2821, "s": 2816, "text": "JAVA" }, { "code": null, "e": 3320, "s": 2823, "text": "class Solution{public static int convertFive(int n){ String number = String.valueOf(n); String newnumber = \"\"; for(int i=0 ; i< number.length() ; i++){ // check if current index equal to ASCII value of the number 0(48). if(number.charAt(i) == 48){ newnumber += \"5\"; } else{ newnumber += number.charAt(i); } } int parsednumber = Integer.parseInt(newnumber); return parsednumber; } " }, { "code": null, "e": 3322, "s": 3320, "text": "0" }, { "code": null, "e": 3353, "s": 3322, "text": "prateekkasaudhan1233 weeks ago" }, { "code": null, "e": 3372, "s": 3353, "text": "// java solutions" }, { "code": null, "e": 3665, "s": 3372, "text": "class Solution{public static int convertFive(int n){ String s = Integer.toString(n); String newS = \"\"; for(int i=0; i<s.length(); i++){ if(s.charAt(i)=='0') newS += '5'; else newS += s.charAt(i); } int ans = Integer.parseInt(newS); return ans; }}" }, { "code": null, "e": 3667, "s": 3665, "text": "0" }, { "code": null, "e": 3692, "s": 3667, "text": "aravindmn75833 weeks ago" }, { "code": null, "e": 3720, "s": 3692, "text": "simple solution in c++_____" }, { "code": null, "e": 3822, "s": 3720, "text": "by converting from int to string after that if char is “0” replace with “5” return string to int____" }, { "code": null, "e": 3966, "s": 3822, "text": "int conversion(int n){\n\tstring s =to_string(n);\n\tfor(int i=0; i<s.length(); i++){\n\t\tif(s[i]=='0'){\n\t\t\ts[i]='5';\n\t\t}\n\t}\n\treturn n = stoi(s);\n}\n\n" }, { "code": null, "e": 4120, "s": 3974, "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": 4156, "s": 4120, "text": " Login to access your submissions. " }, { "code": null, "e": 4166, "s": 4156, "text": "\nProblem\n" }, { "code": null, "e": 4176, "s": 4166, "text": "\nContest\n" }, { "code": null, "e": 4239, "s": 4176, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 4387, "s": 4239, "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": 4595, "s": 4387, "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": 4701, "s": 4595, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Kotlin infix function notation - GeeksforGeeks
20 Apr, 2022 In this article, we will learn infix notation used in Kotlin functions. In Kotlin, a functions marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot. There are two types of infix function notation in Kotlin- Standard library infix function notationUser defined infix function notation Standard library infix function notation User defined infix function notation When we call operators like and, or , shr, shl etc then compiler looks for the function and calls the desired one. There is a number of standard library infix notations functions but we will discuss here some of them. Let’s discuss some of infix notations one by one.1. Kotlin program using bitwise and operator – Kotlin fun main(args: Array<String>) { var a = 15 var b = 12 var c = 11 // call using dot and parenthesis var result1 =(a > b).and(a > c) println("Boolean result1 = $result1") // call using infix notation var result2 =(a > b) and (a > c) println("Boolean result1 = $result2")} Output: Boolean result1 = true Boolean result1 = true Explanation: Here, we have called the a.and(b) function using infix (a and b). Both produce the same result in the standard output.2. Kotlin program of using signed shift right(shr) operator – Kotlin fun main(args: Array<String>) { var a = 8 // // call using infix notation var result1 = a shr 2 println("Signed shift right by 2 bit: $result1") // call using dot and parenthesis var result2 = a.shr(1) println("Signed shift right by 1 bit: $result2")} Output: Signed shift right by 2 bit: 2 Signed shift right by 1 bit: 4 Explanation: In the above program, we have used signed shift operator. First, performed the operation using the infix notation then performed using dot and parenthesis. If we signed shift the value by 2 bits then 23=8 becomes 2(3-2=1)=2. 3. Kotlin program of using increment and decrement operators – Kotlin fun main(args: Array<String>) { var a = 8 var b = 4 println(++a) // call using infix notation println(a.inc()) // call using dot and parenthesis println(--b) // call using infix notation println(b.dec()) // call using dot and parenthesis} Output: 9 10 3 2 Explanation: Here, we have used increment and decrement operators using infix notations. ++a represents a(8) + 1 so it prints 9 a.inc() also represents a(9) + 1 so it prints 10 –b represents b(4) – 1 = 3 b.dec() also represents b(3)- 1 = 2 We can create own function with infix notation if the function satisfy the following requirements: It must be member function or extension function It must accepts a single parameter The parameter must not accept variable number of arguments and must have no default value It must be marked with infix keyword Kotlin program of creating square function with infix notation – Kotlin class math { // user defined infix member function infix fun square(n : Int): Int{ val num = n * n return num }}fun main(args: Array<String>) { val m = math() // call using infix notation val result = m square 3 print("The square of a number is: "+result)} Output: The square of a number is: 9 Explanation: In the above program, we have created own infix notation function (m square 3). 1. First of all, we defined the infix the infix notation function within a class math because it must be member function. 2. infix keyword used to mark the function. 3. It contains only one parameter and having no default value and function return type is also Integer. square(n : Int):Int Then, we create an object for the class math() and called the function using infix notation- m square 3 It calculate the square of the number and returns value 9Kotlin program to check the data type of variable with infix notation – Kotlin class check{ // user defined infix member function infix fun dataType(x: Any):Any{ var i = when(x){ is String -> "String" is Int -> "Integer" is Double -> "Double" else -> "invalid" } return i }}fun main(args: Array<String>){ var chk = check() // call using infix notation var result = chk dataType 3.3 println(result)} Output: Double Explanation: We have created an infix notation function to find the datatype of variable. The datatype has been passed as an argument in infix call- chk dataType 3.3 when checks data type for the passing parameter and returns the desired value. Here, it returns Double to the standard output. Precedence matters at the time of execution of an instruction. Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator.The following expressions are equivalent: 2 shr 1 + 2 and 2 shr (1 + 2) 1 until n * 2 and 0 until (n * 2) xs union ys as Set<*> and xs union (ys as Set<*>) On the other hand, infix function call have higher precedence than the boolean operators && and ||, is- and in-checks, and some other operators. The following expressions are equivalent as well: a xor b || c and a xor (b || c) a in b xor c and a in (b xor c) ManasChhabra2 rajeev0719singh ayushpandey3july surinderdawra388 Kotlin Functions Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Retrofit with Kotlin Coroutine in Android How to Get Current Location in Android? ImageView in Android with Example How to Build a Weather App in Android? Android SQLite Database in Kotlin Suspend Function In Kotlin Coroutines ScrollView in Android Kotlin Coroutines on Android Singleton Class in Kotlin Notifications in Android with Example
[ { "code": null, "e": 25763, "s": 25735, "text": "\n20 Apr, 2022" }, { "code": null, "e": 26033, "s": 25763, "text": "In this article, we will learn infix notation used in Kotlin functions. In Kotlin, a functions marked with infix keyword can also be called using infix notation means calling without using parenthesis and dot. There are two types of infix function notation in Kotlin- " }, { "code": null, "e": 26110, "s": 26033, "text": "Standard library infix function notationUser defined infix function notation" }, { "code": null, "e": 26151, "s": 26110, "text": "Standard library infix function notation" }, { "code": null, "e": 26188, "s": 26151, "text": "User defined infix function notation" }, { "code": null, "e": 26506, "s": 26190, "text": "When we call operators like and, or , shr, shl etc then compiler looks for the function and calls the desired one. There is a number of standard library infix notations functions but we will discuss here some of them. Let’s discuss some of infix notations one by one.1. Kotlin program using bitwise and operator – " }, { "code": null, "e": 26513, "s": 26506, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { var a = 15 var b = 12 var c = 11 // call using dot and parenthesis var result1 =(a > b).and(a > c) println(\"Boolean result1 = $result1\") // call using infix notation var result2 =(a > b) and (a > c) println(\"Boolean result1 = $result2\")}", "e": 26829, "s": 26513, "text": null }, { "code": null, "e": 26839, "s": 26829, "text": "Output: " }, { "code": null, "e": 26885, "s": 26839, "text": "Boolean result1 = true\nBoolean result1 = true" }, { "code": null, "e": 27080, "s": 26885, "text": "Explanation: Here, we have called the a.and(b) function using infix (a and b). Both produce the same result in the standard output.2. Kotlin program of using signed shift right(shr) operator – " }, { "code": null, "e": 27087, "s": 27080, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { var a = 8 // // call using infix notation var result1 = a shr 2 println(\"Signed shift right by 2 bit: $result1\") // call using dot and parenthesis var result2 = a.shr(1) println(\"Signed shift right by 1 bit: $result2\")}", "e": 27361, "s": 27087, "text": null }, { "code": null, "e": 27371, "s": 27361, "text": "Output: " }, { "code": null, "e": 27433, "s": 27371, "text": "Signed shift right by 2 bit: 2\nSigned shift right by 1 bit: 4" }, { "code": null, "e": 27736, "s": 27433, "text": "Explanation: In the above program, we have used signed shift operator. First, performed the operation using the infix notation then performed using dot and parenthesis. If we signed shift the value by 2 bits then 23=8 becomes 2(3-2=1)=2. 3. Kotlin program of using increment and decrement operators – " }, { "code": null, "e": 27743, "s": 27736, "text": "Kotlin" }, { "code": "fun main(args: Array<String>) { var a = 8 var b = 4 println(++a) // call using infix notation println(a.inc()) // call using dot and parenthesis println(--b) // call using infix notation println(b.dec()) // call using dot and parenthesis}", "e": 28016, "s": 27743, "text": null }, { "code": null, "e": 28026, "s": 28016, "text": "Output: " }, { "code": null, "e": 28035, "s": 28026, "text": "9\n10\n3\n2" }, { "code": null, "e": 28276, "s": 28035, "text": "Explanation: Here, we have used increment and decrement operators using infix notations. ++a represents a(8) + 1 so it prints 9 a.inc() also represents a(9) + 1 so it prints 10 –b represents b(4) – 1 = 3 b.dec() also represents b(3)- 1 = 2 " }, { "code": null, "e": 28377, "s": 28276, "text": "We can create own function with infix notation if the function satisfy the following requirements: " }, { "code": null, "e": 28426, "s": 28377, "text": "It must be member function or extension function" }, { "code": null, "e": 28461, "s": 28426, "text": "It must accepts a single parameter" }, { "code": null, "e": 28551, "s": 28461, "text": "The parameter must not accept variable number of arguments and must have no default value" }, { "code": null, "e": 28588, "s": 28551, "text": "It must be marked with infix keyword" }, { "code": null, "e": 28655, "s": 28588, "text": "Kotlin program of creating square function with infix notation – " }, { "code": null, "e": 28662, "s": 28655, "text": "Kotlin" }, { "code": "class math { // user defined infix member function infix fun square(n : Int): Int{ val num = n * n return num }}fun main(args: Array<String>) { val m = math() // call using infix notation val result = m square 3 print(\"The square of a number is: \"+result)}", "e": 28953, "s": 28662, "text": null }, { "code": null, "e": 28963, "s": 28953, "text": "Output: " }, { "code": null, "e": 28992, "s": 28963, "text": "The square of a number is: 9" }, { "code": null, "e": 29357, "s": 28992, "text": "Explanation: In the above program, we have created own infix notation function (m square 3). 1. First of all, we defined the infix the infix notation function within a class math because it must be member function. 2. infix keyword used to mark the function. 3. It contains only one parameter and having no default value and function return type is also Integer. " }, { "code": null, "e": 29377, "s": 29357, "text": "square(n : Int):Int" }, { "code": null, "e": 29472, "s": 29377, "text": "Then, we create an object for the class math() and called the function using infix notation- " }, { "code": null, "e": 29483, "s": 29472, "text": "m square 3" }, { "code": null, "e": 29614, "s": 29483, "text": "It calculate the square of the number and returns value 9Kotlin program to check the data type of variable with infix notation – " }, { "code": null, "e": 29621, "s": 29614, "text": "Kotlin" }, { "code": "class check{ // user defined infix member function infix fun dataType(x: Any):Any{ var i = when(x){ is String -> \"String\" is Int -> \"Integer\" is Double -> \"Double\" else -> \"invalid\" } return i }}fun main(args: Array<String>){ var chk = check() // call using infix notation var result = chk dataType 3.3 println(result)}", "e": 30023, "s": 29621, "text": null }, { "code": null, "e": 30033, "s": 30023, "text": "Output: " }, { "code": null, "e": 30040, "s": 30033, "text": "Double" }, { "code": null, "e": 30191, "s": 30040, "text": "Explanation: We have created an infix notation function to find the datatype of variable. The datatype has been passed as an argument in infix call- " }, { "code": null, "e": 30208, "s": 30191, "text": "chk dataType 3.3" }, { "code": null, "e": 30337, "s": 30208, "text": "when checks data type for the passing parameter and returns the desired value. Here, it returns Double to the standard output. " }, { "code": null, "e": 30555, "s": 30337, "text": "Precedence matters at the time of execution of an instruction. Infix function calls have lower precedence than the arithmetic operators, type casts, and the rangeTo operator.The following expressions are equivalent: " }, { "code": null, "e": 30669, "s": 30555, "text": "2 shr 1 + 2 and 2 shr (1 + 2)\n1 until n * 2 and 0 until (n * 2)\nxs union ys as Set<*> and xs union (ys as Set<*>)" }, { "code": null, "e": 30866, "s": 30669, "text": "On the other hand, infix function call have higher precedence than the boolean operators && and ||, is- and in-checks, and some other operators. The following expressions are equivalent as well: " }, { "code": null, "e": 30930, "s": 30866, "text": "a xor b || c and a xor (b || c)\na in b xor c and a in (b xor c)" }, { "code": null, "e": 30946, "s": 30932, "text": "ManasChhabra2" }, { "code": null, "e": 30962, "s": 30946, "text": "rajeev0719singh" }, { "code": null, "e": 30979, "s": 30962, "text": "ayushpandey3july" }, { "code": null, "e": 30996, "s": 30979, "text": "surinderdawra388" }, { "code": null, "e": 31013, "s": 30996, "text": "Kotlin Functions" }, { "code": null, "e": 31020, "s": 31013, "text": "Kotlin" }, { "code": null, "e": 31118, "s": 31020, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31160, "s": 31118, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31200, "s": 31160, "text": "How to Get Current Location in Android?" }, { "code": null, "e": 31234, "s": 31200, "text": "ImageView in Android with Example" }, { "code": null, "e": 31273, "s": 31234, "text": "How to Build a Weather App in Android?" }, { "code": null, "e": 31307, "s": 31273, "text": "Android SQLite Database in Kotlin" }, { "code": null, "e": 31345, "s": 31307, "text": "Suspend Function In Kotlin Coroutines" }, { "code": null, "e": 31367, "s": 31345, "text": "ScrollView in Android" }, { "code": null, "e": 31396, "s": 31367, "text": "Kotlin Coroutines on Android" }, { "code": null, "e": 31422, "s": 31396, "text": "Singleton Class in Kotlin" } ]
Python | Find groups of strictly increasing numbers in a list - GeeksforGeeks
08 Mar, 2019 Given a list of integers, write a Python program to find groups of strictly increasing numbers. Examples: Input : [1, 2, 3, 5, 6] Output : [[1, 2, 3], [5, 6]] Input : [8, 9, 10, 7, 8, 1, 2, 3] Output : [[8, 9, 10], [7, 8], [1, 2, 3]] Approach #1 : Pythonic naive This is a naive approach which uses an extra input list space. It makes use of a for loop and in every iteration, it checks if the next element increments from previous by 1. If yes, append it to the current sublist, otherwise, create another sublist. # Python3 program to Find groups # of strictly increasing numbers within def groupSequence(lst): res = [[lst[0]]] for i in range(1, len(lst)): if lst[i-1]+1 == lst[i]: res[-1].append(lst[i]) else: res.append([lst[i]]) return res # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(groupSequence(l)) [[8, 9, 10], [7, 8], [1, 2, 3]] Approach #2 : Alternate naive This is an alternative to the above mentioned naive approach. This method is quite simple and straight. It constructs a start_bound list and an end_bound list, which contains the position of starting and ending sequence of increasing integers. Thus simply return the bounds using for loops. # Python3 program to Find groups # of strictly increasing numbers within def groupSequence(l): start_bound = [i for i in range(len(l)-1) if (l == 0 or l[i] != l[i-1]+1) and l[i + 1] == l[i]+1] end_bound = [i for i in range(1, len(l)) if l[i] == l[i-1]+1 and (i == len(l)-1 or l[i + 1] != l[i]+1)] return [l[start_bound[i]:end_bound[i]+1] for i in range(len(start_bound))] # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(list(groupSequence(l))) [[8, 9, 10], [7, 8], [1, 2, 3]] Approach #3 : Using iterable and yieldThis approach uses another list ‘res’ and an iterable ‘it’. A variable ‘prev’ is used for keeping the record of previous integer and start is used for getting the starting position of the increasing sequence. Using a loop, in every iteration, we check if start element is a successor of prev or not. If yes, we append it to res, otherwise, we simply yield the res + [prev] as list element. # Python3 program to Find groups # of strictly increasing numbers within def groupSequence(x): it = iter(x) prev, res = next(it), [] while prev is not None: start = next(it, None) if prev + 1 == start: res.append(prev) elif res: yield list(res + [prev]) res = [] prev = start # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(list(groupSequence(l))) [[8, 9, 10], [7, 8], [1, 2, 3]] Approach #4 : Using itertoolsPython itertools provides operations like cycle and groupby which are used in this method. First we form another list ‘temp_list‘ using cycle. Cycle generates an infinitely repeating series of values. Then we group the temp_list accordingly using groupby operation and finally yield the desired output. # Python3 program to Find groups # of strictly increasing numbers within from itertools import groupby, cycle def groupSequence(l): temp_list = cycle(l) next(temp_list) groups = groupby(l, key = lambda j: j + 1 == next(temp_list)) for k, v in groups: if k: yield tuple(v) + (next((next(groups)[1])), ) # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(list(groupSequence(l))) [(8, 9, 10), (7, 8), (1, 2, 3)] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25439, "s": 25411, "text": "\n08 Mar, 2019" }, { "code": null, "e": 25535, "s": 25439, "text": "Given a list of integers, write a Python program to find groups of strictly increasing numbers." }, { "code": null, "e": 25545, "s": 25535, "text": "Examples:" }, { "code": null, "e": 25675, "s": 25545, "text": "Input : [1, 2, 3, 5, 6]\nOutput : [[1, 2, 3], [5, 6]]\n\nInput : [8, 9, 10, 7, 8, 1, 2, 3]\nOutput : [[8, 9, 10], [7, 8], [1, 2, 3]]\n" }, { "code": null, "e": 25704, "s": 25675, "text": "Approach #1 : Pythonic naive" }, { "code": null, "e": 25956, "s": 25704, "text": "This is a naive approach which uses an extra input list space. It makes use of a for loop and in every iteration, it checks if the next element increments from previous by 1. If yes, append it to the current sublist, otherwise, create another sublist." }, { "code": "# Python3 program to Find groups # of strictly increasing numbers within def groupSequence(lst): res = [[lst[0]]] for i in range(1, len(lst)): if lst[i-1]+1 == lst[i]: res[-1].append(lst[i]) else: res.append([lst[i]]) return res # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(groupSequence(l))", "e": 26311, "s": 25956, "text": null }, { "code": null, "e": 26344, "s": 26311, "text": "[[8, 9, 10], [7, 8], [1, 2, 3]]\n" }, { "code": null, "e": 26375, "s": 26344, "text": " Approach #2 : Alternate naive" }, { "code": null, "e": 26666, "s": 26375, "text": "This is an alternative to the above mentioned naive approach. This method is quite simple and straight. It constructs a start_bound list and an end_bound list, which contains the position of starting and ending sequence of increasing integers. Thus simply return the bounds using for loops." }, { "code": "# Python3 program to Find groups # of strictly increasing numbers within def groupSequence(l): start_bound = [i for i in range(len(l)-1) if (l == 0 or l[i] != l[i-1]+1) and l[i + 1] == l[i]+1] end_bound = [i for i in range(1, len(l)) if l[i] == l[i-1]+1 and (i == len(l)-1 or l[i + 1] != l[i]+1)] return [l[start_bound[i]:end_bound[i]+1] for i in range(len(start_bound))] # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(list(groupSequence(l)))", "e": 27165, "s": 26666, "text": null }, { "code": null, "e": 27198, "s": 27165, "text": "[[8, 9, 10], [7, 8], [1, 2, 3]]\n" }, { "code": null, "e": 27627, "s": 27198, "text": " Approach #3 : Using iterable and yieldThis approach uses another list ‘res’ and an iterable ‘it’. A variable ‘prev’ is used for keeping the record of previous integer and start is used for getting the starting position of the increasing sequence. Using a loop, in every iteration, we check if start element is a successor of prev or not. If yes, we append it to res, otherwise, we simply yield the res + [prev] as list element." }, { "code": "# Python3 program to Find groups # of strictly increasing numbers within def groupSequence(x): it = iter(x) prev, res = next(it), [] while prev is not None: start = next(it, None) if prev + 1 == start: res.append(prev) elif res: yield list(res + [prev]) res = [] prev = start # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(list(groupSequence(l)))", "e": 28060, "s": 27627, "text": null }, { "code": null, "e": 28093, "s": 28060, "text": "[[8, 9, 10], [7, 8], [1, 2, 3]]\n" }, { "code": null, "e": 28426, "s": 28093, "text": " Approach #4 : Using itertoolsPython itertools provides operations like cycle and groupby which are used in this method. First we form another list ‘temp_list‘ using cycle. Cycle generates an infinitely repeating series of values. Then we group the temp_list accordingly using groupby operation and finally yield the desired output." }, { "code": "# Python3 program to Find groups # of strictly increasing numbers within from itertools import groupby, cycle def groupSequence(l): temp_list = cycle(l) next(temp_list) groups = groupby(l, key = lambda j: j + 1 == next(temp_list)) for k, v in groups: if k: yield tuple(v) + (next((next(groups)[1])), ) # Driver program l = [8, 9, 10, 7, 8, 1, 2, 3]print(list(groupSequence(l)))", "e": 28844, "s": 28426, "text": null }, { "code": null, "e": 28877, "s": 28844, "text": "[(8, 9, 10), (7, 8), (1, 2, 3)]\n" }, { "code": null, "e": 28898, "s": 28877, "text": "Python list-programs" }, { "code": null, "e": 28905, "s": 28898, "text": "Python" }, { "code": null, "e": 28921, "s": 28905, "text": "Python Programs" }, { "code": null, "e": 29019, "s": 28921, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29054, "s": 29019, "text": "Read a file line by line in Python" }, { "code": null, "e": 29086, "s": 29054, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29108, "s": 29086, "text": "Enumerate() in Python" }, { "code": null, "e": 29150, "s": 29108, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29180, "s": 29150, "text": "Iterate over a list in Python" }, { "code": null, "e": 29223, "s": 29180, "text": "Python program to convert a list to string" }, { "code": null, "e": 29245, "s": 29223, "text": "Defaultdict in Python" }, { "code": null, "e": 29284, "s": 29245, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 29330, "s": 29284, "text": "Python | Split string into list of characters" } ]
Trigger a keypress/keydown/keyup event in JS/jQuery - GeeksforGeeks
03 Aug, 2021 In this article, we are going to discuss 2 methods of logging key-presses in web technologies using vanilla JavaScript as well as Jquery. We will also discuss the events related to key-presses in JavaScript. Firstly we have to create a structure so let’s make an HTML and CSS layout first. HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box.The events related to keypresses are as follows : keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc. keyup: This event is triggered when a key is released. <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> h1 { color: green; } .display { border: 2px solid black; height: 100px; width: 400px; text-align: center; } .input { display: flex; flex-direction: column; font-size: 0px; } button { border: none; margin: 2px; width: 80px; height: 3vw; float: right; background-color: green; color: white; } button:hover { background-color: rgb(5, 94, 12); } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class="display"><h3></h3></div> <div class="input"> <button>emit event</button> </div> </body></html> Output: We shall achieve to trigger a keypress/keydown/keyup event in JS/jQuery using 2 methods: Using Vanilla JavaScript: We will use the native dispatchEvent in order to create keyboard events as follows.We add an event listener to the button to trigger a series of events that will show ‘Hey Geek’ in the display division that we created. for this we have used dispatchEvent(new KeyboardEvent(...)). The KeyboardEvent is a constructor that takes an event and an object of event properties as parameters.window.addEventListener('load', ()=>{ document.querySelector('button').addEventListener('click', ()=>{ document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'H'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'y'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': ' '})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'G'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'k'})); });});document.addEventListener('keypress', (event)=>{ document.querySelector('h1').innerHTML += event.key;}); We add an event listener to the button to trigger a series of events that will show ‘Hey Geek’ in the display division that we created. for this we have used dispatchEvent(new KeyboardEvent(...)). The KeyboardEvent is a constructor that takes an event and an object of event properties as parameters. window.addEventListener('load', ()=>{ document.querySelector('button').addEventListener('click', ()=>{ document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'H'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'y'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': ' '})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'G'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'k'})); });});document.addEventListener('keypress', (event)=>{ document.querySelector('h1').innerHTML += event.key;}); Using jQuery: We first create an event e and assign the key property to it as shown in the above code. Using Jquery.trigger(e) we emit the event and handle it the same way we did in approach 1. However, instead of using innerHTML we use Jquery’s .append() method.$(document).ready(()=>{ $('button').on('click', ()=>{ let e = $.Event('keypress'); e.key = 'H'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'y'; $(document).trigger(e); e.key = ' '; $(document).trigger(e); e.key = 'G'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'k'; $(document).trigger(e); }) }); $(document).on('keypress', (event)=>{ $('h1').append(event.key); }) $(document).ready(()=>{ $('button').on('click', ()=>{ let e = $.Event('keypress'); e.key = 'H'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'y'; $(document).trigger(e); e.key = ' '; $(document).trigger(e); e.key = 'G'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'k'; $(document).trigger(e); }) }); $(document).on('keypress', (event)=>{ $('h1').append(event.key); }) Final solution: We will simply use the approach 1 in this code, you can use any of them is as follows: <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <script src="https://code.jquery.com/jquery-3.5.0.slim.js" integrity="sha256-sCexhaKpAfuqulKjtSY7V9H7QT0TCN90H+Y5NlmqOUE=" crossorigin="anonymous"> </script> <style> h1 { color: green; } .display { border: 2px solid black; height: 100px; width: 400px; text-align: center; } .input { display: flex; flex-direction: column; font-size: 0px; } button { border: none; margin: 2px; width: 80px; height: 3vw; float: right; background-color: green; color: white; } button:hover { background-color: rgb(5, 94, 12); } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class="display"><h3></h3></div> <div class="input"> <button>emit event</button> </div> <script type="text/javascript"> window.addEventListener("load", () => { document.querySelector("button").addEventListener("click", () => { document.dispatchEvent(new KeyboardEvent("keypress", { key: "H" })); document.dispatchEvent(new KeyboardEvent("keypress", { key: "e" })); document.dispatchEvent(new KeyboardEvent("keypress", { key: "y" })); document.dispatchEvent(new KeyboardEvent("keypress", { key: " " })); document.dispatchEvent(new KeyboardEvent("keypress", { key: "G" })); document.dispatchEvent(new KeyboardEvent("keypress", { key: "e" })); document.dispatchEvent(new KeyboardEvent("keypress", { key: "e" })); document.dispatchEvent(new KeyboardEvent("keypress", { key: "k" })); }); }); document.addEventListener("keypress", (event) => { document.querySelector("h3").innerHTML += event.key; }); </script> </body></html> Output: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Events Picked CSS HTML JavaScript JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? How to apply style to parent if it has child with CSS? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction)
[ { "code": null, "e": 26602, "s": 26574, "text": "\n03 Aug, 2021" }, { "code": null, "e": 26892, "s": 26602, "text": "In this article, we are going to discuss 2 methods of logging key-presses in web technologies using vanilla JavaScript as well as Jquery. We will also discuss the events related to key-presses in JavaScript. Firstly we have to create a structure so let’s make an HTML and CSS layout first." }, { "code": null, "e": 27064, "s": 26892, "text": "HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box.The events related to keypresses are as follows :" }, { "code": null, "e": 27125, "s": 27064, "text": "keydown: This event is triggered when a key is pressed down." }, { "code": null, "e": 27258, "s": 27125, "text": "keypress: This event is triggered when a key is pressed. This event fails to recognise keys such as tab, shift, ctrl, backspace etc." }, { "code": null, "e": 27313, "s": 27258, "text": "keyup: This event is triggered when a key is released." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <style> h1 { color: green; } .display { border: 2px solid black; height: 100px; width: 400px; text-align: center; } .input { display: flex; flex-direction: column; font-size: 0px; } button { border: none; margin: 2px; width: 80px; height: 3vw; float: right; background-color: green; color: white; } button:hover { background-color: rgb(5, 94, 12); } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class=\"display\"><h3></h3></div> <div class=\"input\"> <button>emit event</button> </div> </body></html>", "e": 28324, "s": 27313, "text": null }, { "code": null, "e": 28332, "s": 28324, "text": "Output:" }, { "code": null, "e": 28421, "s": 28332, "text": "We shall achieve to trigger a keypress/keydown/keyup event in JS/jQuery using 2 methods:" }, { "code": null, "e": 29661, "s": 28421, "text": "Using Vanilla JavaScript: We will use the native dispatchEvent in order to create keyboard events as follows.We add an event listener to the button to trigger a series of events that will show ‘Hey Geek’ in the display division that we created. for this we have used dispatchEvent(new KeyboardEvent(...)). The KeyboardEvent is a constructor that takes an event and an object of event properties as parameters.window.addEventListener('load', ()=>{ document.querySelector('button').addEventListener('click', ()=>{ document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'H'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'y'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': ' '})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'G'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'k'})); });});document.addEventListener('keypress', (event)=>{ document.querySelector('h1').innerHTML += event.key;});" }, { "code": null, "e": 29962, "s": 29661, "text": "We add an event listener to the button to trigger a series of events that will show ‘Hey Geek’ in the display division that we created. for this we have used dispatchEvent(new KeyboardEvent(...)). The KeyboardEvent is a constructor that takes an event and an object of event properties as parameters." }, { "code": "window.addEventListener('load', ()=>{ document.querySelector('button').addEventListener('click', ()=>{ document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'H'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'y'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': ' '})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'G'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'e'})); document.dispatchEvent(new KeyboardEvent('keypress', {'key': 'k'})); });});document.addEventListener('keypress', (event)=>{ document.querySelector('h1').innerHTML += event.key;});", "e": 30793, "s": 29962, "text": null }, { "code": null, "e": 31726, "s": 30793, "text": "Using jQuery: We first create an event e and assign the key property to it as shown in the above code. Using Jquery.trigger(e) we emit the event and handle it the same way we did in approach 1. However, instead of using innerHTML we use Jquery’s .append() method.$(document).ready(()=>{ $('button').on('click', ()=>{ let e = $.Event('keypress'); e.key = 'H'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'y'; $(document).trigger(e); e.key = ' '; $(document).trigger(e); e.key = 'G'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'k'; $(document).trigger(e); }) }); $(document).on('keypress', (event)=>{ $('h1').append(event.key); })" }, { "code": "$(document).ready(()=>{ $('button').on('click', ()=>{ let e = $.Event('keypress'); e.key = 'H'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'y'; $(document).trigger(e); e.key = ' '; $(document).trigger(e); e.key = 'G'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'e'; $(document).trigger(e); e.key = 'k'; $(document).trigger(e); }) }); $(document).on('keypress', (event)=>{ $('h1').append(event.key); })", "e": 32396, "s": 31726, "text": null }, { "code": null, "e": 32499, "s": 32396, "text": "Final solution: We will simply use the approach 1 in this code, you can use any of them is as follows:" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Document</title> <script src=\"https://code.jquery.com/jquery-3.5.0.slim.js\" integrity=\"sha256-sCexhaKpAfuqulKjtSY7V9H7QT0TCN90H+Y5NlmqOUE=\" crossorigin=\"anonymous\"> </script> <style> h1 { color: green; } .display { border: 2px solid black; height: 100px; width: 400px; text-align: center; } .input { display: flex; flex-direction: column; font-size: 0px; } button { border: none; margin: 2px; width: 80px; height: 3vw; float: right; background-color: green; color: white; } button:hover { background-color: rgb(5, 94, 12); } </style> </head> <body> <h1>GeeksforGeeks</h1> <div class=\"display\"><h3></h3></div> <div class=\"input\"> <button>emit event</button> </div> <script type=\"text/javascript\"> window.addEventListener(\"load\", () => { document.querySelector(\"button\").addEventListener(\"click\", () => { document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"H\" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"e\" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"y\" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \" \" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"G\" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"e\" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"e\" })); document.dispatchEvent(new KeyboardEvent(\"keypress\", { key: \"k\" })); }); }); document.addEventListener(\"keypress\", (event) => { document.querySelector(\"h3\").innerHTML += event.key; }); </script> </body></html>", "e": 34789, "s": 32499, "text": null }, { "code": null, "e": 34797, "s": 34789, "text": "Output:" }, { "code": null, "e": 35065, "s": 34797, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 35079, "s": 35065, "text": "jQuery-Events" }, { "code": null, "e": 35086, "s": 35079, "text": "Picked" }, { "code": null, "e": 35090, "s": 35086, "text": "CSS" }, { "code": null, "e": 35095, "s": 35090, "text": "HTML" }, { "code": null, "e": 35106, "s": 35095, "text": "JavaScript" }, { "code": null, "e": 35113, "s": 35106, "text": "JQuery" }, { "code": null, "e": 35130, "s": 35113, "text": "Web Technologies" }, { "code": null, "e": 35157, "s": 35130, "text": "Web technologies Questions" }, { "code": null, "e": 35162, "s": 35157, "text": "HTML" }, { "code": null, "e": 35260, "s": 35162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35308, "s": 35260, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35363, "s": 35308, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 35400, "s": 35363, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 35464, "s": 35400, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 35503, "s": 35464, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 35551, "s": 35503, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 35611, "s": 35551, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 35664, "s": 35611, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 35725, "s": 35664, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Get Application Version using Python - GeeksforGeeks
02 Feb, 2021 Software versioning maybe thanks to reasoning the distinctive states of pc software package because it is developed and discharged. The version symbol is typically a word, a number, or both. For instance, version 1.0 is often accustomed to denote the initial unharness of a program. In this article, we will see how to get an application version number using Python. Method 1: Here will use the win32api module. Python extensions for Microsoft Windows Provide access to a lot of the Win32 API, the flexibility to make and use COM objects, and therefore the Pythonwin atmosphere. Before getting started, we need to install the Module pip install pywin32 Here we will use these methods: GetFileVersionInfo: This method is used for retrieving the version information for a given file GetFileVersionInfo(File Path, SubBlock, **attr) LOWORD: An interface to the win32api LOWORD macro. Value is of integer datatype LOWORD(val) HIWORD: An interface to the win32api HIWORD macro. Value is of integer datatype HIWORD(val) Approach: First we will parse file information using GetFileVersionInfo() method. File information is in the form of a dictionary, we will fetch two information, one is msfileversion and another one is lsfileversion Below is the implementation: Python3 # Import Modulefrom win32api import * def get_version_number(file_path): File_information = GetFileVersionInfo(file_path, "\\") ms_file_version = File_information['FileVersionMS'] ls_file_version = File_information['FileVersionLS'] return [str(HIWORD(ms_file_version)), str(LOWORD(ms_file_version)), str(HIWORD(ls_file_version)), str(LOWORD(ls_file_version))] file_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe' version = ".".join(get_version_number(file_path)) print(version) Output: 88.0.4324.104 Method 2: Using win32com Here will use the win32com module. Before getting started we need to install the Module pip install pypiwin32 Approach: We will create an information parser that will parse the required information using Dispatch() method. Then we will fetch the file version using the GetFileVersion() method. Below is the implementation: Python3 # Import Modulefrom win32com.client import * def get_version_number(file_path): information_parser = Dispatch("Scripting.FileSystemObject") version = information_parser.GetFileVersion(file_path) return version file_path = r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe'version = get_version_number(file_path) print(version) Output: 88.0.4324.104 python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Feb, 2021" }, { "code": null, "e": 25904, "s": 25537, "text": "Software versioning maybe thanks to reasoning the distinctive states of pc software package because it is developed and discharged. The version symbol is typically a word, a number, or both. For instance, version 1.0 is often accustomed to denote the initial unharness of a program. In this article, we will see how to get an application version number using Python." }, { "code": null, "e": 25949, "s": 25904, "text": "Method 1: Here will use the win32api module." }, { "code": null, "e": 26116, "s": 25949, "text": "Python extensions for Microsoft Windows Provide access to a lot of the Win32 API, the flexibility to make and use COM objects, and therefore the Pythonwin atmosphere." }, { "code": null, "e": 26170, "s": 26116, "text": "Before getting started, we need to install the Module" }, { "code": null, "e": 26190, "s": 26170, "text": "pip install pywin32" }, { "code": null, "e": 26222, "s": 26190, "text": "Here we will use these methods:" }, { "code": null, "e": 26318, "s": 26222, "text": "GetFileVersionInfo: This method is used for retrieving the version information for a given file" }, { "code": null, "e": 26366, "s": 26318, "text": "GetFileVersionInfo(File Path, SubBlock, **attr)" }, { "code": null, "e": 26446, "s": 26366, "text": "LOWORD: An interface to the win32api LOWORD macro. Value is of integer datatype" }, { "code": null, "e": 26458, "s": 26446, "text": "LOWORD(val)" }, { "code": null, "e": 26538, "s": 26458, "text": "HIWORD: An interface to the win32api HIWORD macro. Value is of integer datatype" }, { "code": null, "e": 26550, "s": 26538, "text": "HIWORD(val)" }, { "code": null, "e": 26560, "s": 26550, "text": "Approach:" }, { "code": null, "e": 26632, "s": 26560, "text": "First we will parse file information using GetFileVersionInfo() method." }, { "code": null, "e": 26766, "s": 26632, "text": "File information is in the form of a dictionary, we will fetch two information, one is msfileversion and another one is lsfileversion" }, { "code": null, "e": 26795, "s": 26766, "text": "Below is the implementation:" }, { "code": null, "e": 26803, "s": 26795, "text": "Python3" }, { "code": "# Import Modulefrom win32api import * def get_version_number(file_path): File_information = GetFileVersionInfo(file_path, \"\\\\\") ms_file_version = File_information['FileVersionMS'] ls_file_version = File_information['FileVersionLS'] return [str(HIWORD(ms_file_version)), str(LOWORD(ms_file_version)), str(HIWORD(ls_file_version)), str(LOWORD(ls_file_version))] file_path = r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe' version = \".\".join(get_version_number(file_path)) print(version)", "e": 27336, "s": 26803, "text": null }, { "code": null, "e": 27344, "s": 27336, "text": "Output:" }, { "code": null, "e": 27358, "s": 27344, "text": "88.0.4324.104" }, { "code": null, "e": 27383, "s": 27358, "text": "Method 2: Using win32com" }, { "code": null, "e": 27471, "s": 27383, "text": "Here will use the win32com module. Before getting started we need to install the Module" }, { "code": null, "e": 27493, "s": 27471, "text": "pip install pypiwin32" }, { "code": null, "e": 27503, "s": 27493, "text": "Approach:" }, { "code": null, "e": 27606, "s": 27503, "text": "We will create an information parser that will parse the required information using Dispatch() method." }, { "code": null, "e": 27677, "s": 27606, "text": "Then we will fetch the file version using the GetFileVersion() method." }, { "code": null, "e": 27706, "s": 27677, "text": "Below is the implementation:" }, { "code": null, "e": 27714, "s": 27706, "text": "Python3" }, { "code": "# Import Modulefrom win32com.client import * def get_version_number(file_path): information_parser = Dispatch(\"Scripting.FileSystemObject\") version = information_parser.GetFileVersion(file_path) return version file_path = r'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'version = get_version_number(file_path) print(version)", "e": 28067, "s": 27714, "text": null }, { "code": null, "e": 28075, "s": 28067, "text": "Output:" }, { "code": null, "e": 28089, "s": 28075, "text": "88.0.4324.104" }, { "code": null, "e": 28104, "s": 28089, "text": "python-utility" }, { "code": null, "e": 28111, "s": 28104, "text": "Python" }, { "code": null, "e": 28209, "s": 28111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28241, "s": 28209, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28283, "s": 28241, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28325, "s": 28283, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28352, "s": 28325, "text": "Python Classes and Objects" }, { "code": null, "e": 28408, "s": 28352, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28447, "s": 28408, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28469, "s": 28447, "text": "Defaultdict in Python" }, { "code": null, "e": 28500, "s": 28469, "text": "Python | os.path.join() method" }, { "code": null, "e": 28529, "s": 28500, "text": "Create a directory in Python" } ]
Find the nearest power of 2 for every array element - GeeksforGeeks
07 Apr, 2021 Given an array arr[] of size N, the task is to print the nearest power of 2 for each array element. Note: If there happens to be two nearest powers of 2, consider the larger one. Examples: Input: arr[] = {5, 2, 7, 12} Output: 4 2 8 16 Explanation: The nearest power of arr[0] ( = 5) is 4. The nearest power of arr[1] ( = 2) is 2. The nearest power of arr[2] ( = 7) is 8. The nearest power of arr[3] ( = 12) are 8 and 16. Print 16, as it is the largest. Input: arr[] = {31, 13, 64} Output: 32 16 64 Approach: Follow the steps below to solve the problem: Traverse the array from left to right. For every array element, find the nearest powers of 2 greater and smaller than it, i.e. calculate pow(2, log2(arr[i])) and pow(2, log2(arr[i]) + 1). Calculate difference of these two values from the current array element and print the nearest as specified in the problem statement. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find nearest power of two// for every element in the given arrayvoid nearestPowerOfTwo(int arr[], int N){ // Traverse the array for (int i = 0; i < N; i++) { // Calculate log of the // current array element int lg = log2(arr[i]); int a = pow(2, lg); int b = pow(2, lg + 1); // Find the nearest if ((arr[i] - a) < (b - arr[i])) cout << a << " "; else cout << b << " "; }} // Driver Codeint main(){ int arr[] = { 5, 2, 7, 12 }; int N = sizeof(arr) / sizeof(arr[0]); nearestPowerOfTwo(arr, N); return 0;} // Java program to implement the above approachimport java.io.*; class GFG { // Function to find the nearest power of two // for every element of the given array static void nearestPowerOfTwo(int[] arr, int N) { // Traverse the array for (int i = 0; i < N; i++) { // Calculate log of the // current array element int lg = (int)(Math.log(arr[i]) / Math.log(2)); int a = (int)(Math.pow(2, lg)); int b = (int)(Math.pow(2, lg + 1)); // Find the nearest if ((arr[i] - a) < (b - arr[i])) System.out.print(a + " "); else System.out.print(b + " "); } } // Driver Code public static void main(String[] args) { int[] arr = { 5, 2, 7, 12 }; int N = arr.length; nearestPowerOfTwo(arr, N); }} # Python program to implement the above approachimport math # Function to find the nearest power# of two for every array elementdef nearestPowerOfTwo(arr, N): # Traverse the array for i in range(N): # Calculate log of current array element lg = (int)(math.log2(arr[i])) a = (int)(math.pow(2, lg)) b = (int)(math.pow(2, lg + 1)) # Find the nearest if ((arr[i] - a) < (b - arr[i])): print(a, end = " ") else: print(b, end = " ") # Driver Codearr = [5, 2, 7, 12]N = len(arr)nearestPowerOfTwo(arr, N) // C# program to implement the above approachusing System; class GFG { // Function to find nearest power of two // for every array element static void nearestPowerOfTwo(int[] arr, int N) { // Traverse the array for (int i = 0; i < N; i++) { // Calculate log of the // current array element int lg = (int)(Math.Log(arr[i]) / Math.Log(2)); int a = (int)(Math.Pow(2, lg)); int b = (int)(Math.Pow(2, lg + 1)); // Find the nearest if ((arr[i] - a) < (b - arr[i])) Console.Write(a + " "); else Console.Write(b + " "); } } // Driver Code public static void Main(String[] args) { int[] arr = { 5, 2, 7, 12 }; int N = arr.Length; nearestPowerOfTwo(arr, N); }} <script> // JavaScript program to implement// the above approach // Function to find the nearest power of two // for every element of the given array function nearestPowerOfTwo(arr , N) { // Traverse the array for (i = 0; i < N; i++) { // Calculate log of the // current array element var lg = parseInt( (Math.log(arr[i]) / Math.log(2))); var a = parseInt( (Math.pow(2, lg))); var b = parseInt( (Math.pow(2, lg + 1))); // Find the nearest if ((arr[i] - a) < (b - arr[i])) document.write(a + " "); else document.write(b + " "); } } // Driver Code var arr = [ 5, 2, 7, 12 ]; var N = arr.length; nearestPowerOfTwo(arr, N); // This code is contributed by todaysgaurav </script> 4 2 8 16 Time Complexity: O(N) Auxiliary Space: O(1) todaysgaurav maths-log maths-power Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Count pairs with given sum Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Program for Fibonacci numbers Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 26041, "s": 26013, "text": "\n07 Apr, 2021" }, { "code": null, "e": 26220, "s": 26041, "text": "Given an array arr[] of size N, the task is to print the nearest power of 2 for each array element. Note: If there happens to be two nearest powers of 2, consider the larger one." }, { "code": null, "e": 26230, "s": 26220, "text": "Examples:" }, { "code": null, "e": 26494, "s": 26230, "text": "Input: arr[] = {5, 2, 7, 12} Output: 4 2 8 16 Explanation: The nearest power of arr[0] ( = 5) is 4. The nearest power of arr[1] ( = 2) is 2. The nearest power of arr[2] ( = 7) is 8. The nearest power of arr[3] ( = 12) are 8 and 16. Print 16, as it is the largest." }, { "code": null, "e": 26539, "s": 26494, "text": "Input: arr[] = {31, 13, 64} Output: 32 16 64" }, { "code": null, "e": 26594, "s": 26539, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 26633, "s": 26594, "text": "Traverse the array from left to right." }, { "code": null, "e": 26782, "s": 26633, "text": "For every array element, find the nearest powers of 2 greater and smaller than it, i.e. calculate pow(2, log2(arr[i])) and pow(2, log2(arr[i]) + 1)." }, { "code": null, "e": 26915, "s": 26782, "text": "Calculate difference of these two values from the current array element and print the nearest as specified in the problem statement." }, { "code": null, "e": 26966, "s": 26915, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26970, "s": 26966, "text": "C++" }, { "code": null, "e": 26975, "s": 26970, "text": "Java" }, { "code": null, "e": 26983, "s": 26975, "text": "Python3" }, { "code": null, "e": 26986, "s": 26983, "text": "C#" }, { "code": null, "e": 26997, "s": 26986, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find nearest power of two// for every element in the given arrayvoid nearestPowerOfTwo(int arr[], int N){ // Traverse the array for (int i = 0; i < N; i++) { // Calculate log of the // current array element int lg = log2(arr[i]); int a = pow(2, lg); int b = pow(2, lg + 1); // Find the nearest if ((arr[i] - a) < (b - arr[i])) cout << a << \" \"; else cout << b << \" \"; }} // Driver Codeint main(){ int arr[] = { 5, 2, 7, 12 }; int N = sizeof(arr) / sizeof(arr[0]); nearestPowerOfTwo(arr, N); return 0;}", "e": 27709, "s": 26997, "text": null }, { "code": "// Java program to implement the above approachimport java.io.*; class GFG { // Function to find the nearest power of two // for every element of the given array static void nearestPowerOfTwo(int[] arr, int N) { // Traverse the array for (int i = 0; i < N; i++) { // Calculate log of the // current array element int lg = (int)(Math.log(arr[i]) / Math.log(2)); int a = (int)(Math.pow(2, lg)); int b = (int)(Math.pow(2, lg + 1)); // Find the nearest if ((arr[i] - a) < (b - arr[i])) System.out.print(a + \" \"); else System.out.print(b + \" \"); } } // Driver Code public static void main(String[] args) { int[] arr = { 5, 2, 7, 12 }; int N = arr.length; nearestPowerOfTwo(arr, N); }}", "e": 28608, "s": 27709, "text": null }, { "code": "# Python program to implement the above approachimport math # Function to find the nearest power# of two for every array elementdef nearestPowerOfTwo(arr, N): # Traverse the array for i in range(N): # Calculate log of current array element lg = (int)(math.log2(arr[i])) a = (int)(math.pow(2, lg)) b = (int)(math.pow(2, lg + 1)) # Find the nearest if ((arr[i] - a) < (b - arr[i])): print(a, end = \" \") else: print(b, end = \" \") # Driver Codearr = [5, 2, 7, 12]N = len(arr)nearestPowerOfTwo(arr, N)", "e": 29187, "s": 28608, "text": null }, { "code": "// C# program to implement the above approachusing System; class GFG { // Function to find nearest power of two // for every array element static void nearestPowerOfTwo(int[] arr, int N) { // Traverse the array for (int i = 0; i < N; i++) { // Calculate log of the // current array element int lg = (int)(Math.Log(arr[i]) / Math.Log(2)); int a = (int)(Math.Pow(2, lg)); int b = (int)(Math.Pow(2, lg + 1)); // Find the nearest if ((arr[i] - a) < (b - arr[i])) Console.Write(a + \" \"); else Console.Write(b + \" \"); } } // Driver Code public static void Main(String[] args) { int[] arr = { 5, 2, 7, 12 }; int N = arr.Length; nearestPowerOfTwo(arr, N); }}", "e": 30057, "s": 29187, "text": null }, { "code": "<script> // JavaScript program to implement// the above approach // Function to find the nearest power of two // for every element of the given array function nearestPowerOfTwo(arr , N) { // Traverse the array for (i = 0; i < N; i++) { // Calculate log of the // current array element var lg = parseInt( (Math.log(arr[i]) / Math.log(2))); var a = parseInt( (Math.pow(2, lg))); var b = parseInt( (Math.pow(2, lg + 1))); // Find the nearest if ((arr[i] - a) < (b - arr[i])) document.write(a + \" \"); else document.write(b + \" \"); } } // Driver Code var arr = [ 5, 2, 7, 12 ]; var N = arr.length; nearestPowerOfTwo(arr, N); // This code is contributed by todaysgaurav </script>", "e": 30916, "s": 30057, "text": null }, { "code": null, "e": 30925, "s": 30916, "text": "4 2 8 16" }, { "code": null, "e": 30973, "s": 30929, "text": "Time Complexity: O(N) Auxiliary Space: O(1)" }, { "code": null, "e": 30988, "s": 30975, "text": "todaysgaurav" }, { "code": null, "e": 30998, "s": 30988, "text": "maths-log" }, { "code": null, "e": 31010, "s": 30998, "text": "maths-power" }, { "code": null, "e": 31017, "s": 31010, "text": "Arrays" }, { "code": null, "e": 31030, "s": 31017, "text": "Mathematical" }, { "code": null, "e": 31037, "s": 31030, "text": "Arrays" }, { "code": null, "e": 31050, "s": 31037, "text": "Mathematical" }, { "code": null, "e": 31148, "s": 31050, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31179, "s": 31148, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 31206, "s": 31179, "text": "Count pairs with given sum" }, { "code": null, "e": 31231, "s": 31206, "text": "Window Sliding Technique" }, { "code": null, "e": 31269, "s": 31231, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 31290, "s": 31269, "text": "Next Greater Element" }, { "code": null, "e": 31320, "s": 31290, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31380, "s": 31320, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31423, "s": 31380, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 31438, "s": 31423, "text": "C++ Data Types" } ]
C++ Program to Implement Set in STL
Set is abstract data type in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, but it is possible to remove and add the modified value of that element. Functions used here: st.size() = Returns the size of set. st.insert() = It is used to insert elements to the set. st.erase() = To delete the element from the set. st.find() = Returns an iterator to the search element in the set if found, else returns the iterator to end. st.begin() = Returns an iterator to the first element in the set. st.end() = Returns an iterator to the last element in the set. #include <iostream> #include <set> #include <string> #include <cstdlib> using namespace std; int main() { set<int> st; set<int>::iterator it; int c, i; while (1) { cout<<"1.Size of the Set"<<endl; cout<<"2.Insert Element into the Set"<<endl; cout<<"3.Delete Element of the Set"<<endl; cout<<"4.Find Element in a Set"<<endl; cout<<"5.Display the set: "<<endl; cout<<"6.Exit"<<endl; cout<<"Enter your Choice: "; cin>>c; switch(c) { case 1: cout<<"Size of the Set: "; cout<<st.size()<<endl; break; case 2: cout<<"Enter value to be inserted: "; cin>>i; st.insert(i); break; case 3: cout<<"Enter the element to be deleted: "; cin>>i; st.erase(i); break; case 4: cout<<"Enter the element to be found: "; cin>>i; it = st.find(i); if (it != st.end()) cout<<"Element "<<*it<<" found in the set" <<endl; else cout<<"No Element Found"<<endl; break; case 5: cout<<"Displaying Set by Iterator: "; for (it = st.begin(); it != st.end(); it++) { cout << (*it)<<" "; } cout<<endl; break; case 6: exit(1); break; default: cout<<"Wrong Choice"<<endl; } } return 0; } 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 1 Size of the Set: 0 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 2 Enter value to be inserted: 1 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 2 Enter value to be inserted: 7 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 2 Enter value to be inserted: 6 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 2 Enter value to be inserted: 4 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 3 Enter the element to be deleted: 1 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 4 Enter the element to be found: 7 Element 7 found in the set 1.Size of the Set 2.Insert Element into the Set 3.Delete Element of the Set 4.Find Element in a Set 5.Display the set: 6.Exit Enter your Choice: 6 Exit code: 1
[ { "code": null, "e": 1322, "s": 1062, "text": "Set is abstract data type in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, but it is possible to remove and add the modified value of that element." }, { "code": null, "e": 1741, "s": 1322, "text": "Functions used here:\n st.size() = Returns the size of set.\n st.insert() = It is used to insert elements to the set.\n st.erase() = To delete the element from the set.\n st.find() = Returns an iterator to the search element in the set if found, else returns the iterator to\n end. st.begin() = Returns an iterator to the first element in the set.\n st.end() = Returns an iterator to the last element in the set." }, { "code": null, "e": 3254, "s": 1741, "text": "#include <iostream>\n#include <set>\n#include <string>\n#include <cstdlib>\nusing namespace std;\nint main() {\n set<int> st;\n set<int>::iterator it;\n int c, i;\n while (1) {\n cout<<\"1.Size of the Set\"<<endl;\n cout<<\"2.Insert Element into the Set\"<<endl;\n cout<<\"3.Delete Element of the Set\"<<endl;\n cout<<\"4.Find Element in a Set\"<<endl;\n cout<<\"5.Display the set: \"<<endl;\n cout<<\"6.Exit\"<<endl;\n cout<<\"Enter your Choice: \";\n cin>>c;\n switch(c) {\n case 1:\n cout<<\"Size of the Set: \";\n cout<<st.size()<<endl;\n break;\n case 2:\n cout<<\"Enter value to be inserted: \";\n cin>>i;\n st.insert(i);\n break;\n case 3:\n cout<<\"Enter the element to be deleted: \";\n cin>>i;\n st.erase(i);\n break;\n case 4:\n cout<<\"Enter the element to be found: \";\n cin>>i;\n it = st.find(i);\n if (it != st.end())\n cout<<\"Element \"<<*it<<\" found in the set\" <<endl;\n else\n cout<<\"No Element Found\"<<endl;\n break;\n case 5:\n cout<<\"Displaying Set by Iterator: \";\n for (it = st.begin(); it != st.end(); it++) {\n cout << (*it)<<\" \";\n }\n cout<<endl;\n break;\n case 6:\n exit(1);\n break;\n default:\n cout<<\"Wrong Choice\"<<endl;\n }\n }\nreturn 0;\n}" }, { "code": null, "e": 4685, "s": 3254, "text": "1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\nEnter your Choice: 1\nSize of the Set: 0\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\n\nEnter your Choice: 2\nEnter value to be inserted: 1\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 7\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 6\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\nEnter your Choice: 2\nEnter value to be inserted: 4\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\nEnter your Choice: 3\nEnter the element to be deleted: 1\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\n\nEnter your Choice: 4\nEnter the element to be found: 7\nElement 7 found in the set\n1.Size of the Set\n2.Insert Element into the Set\n3.Delete Element of the Set\n4.Find Element in a Set\n5.Display the set:\n6.Exit\nEnter your Choice: 6\nExit code: 1" } ]
Merge K sorted linked lists | Practice | GeeksforGeeks
Given K sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a single sorted linked list. Example 1: Input: K = 4 value = {{1,2,3},{4 5},{5 6},{7,8}} Output: 1 2 3 4 5 5 6 7 8 Explanation: The test case has 4 sorted linked list of size 3, 2, 2, 2 1st list 1 -> 2-> 3 2nd list 4->5 3rd list 5->6 4th list 7->8 The merged list will be 1->2->3->4->5->5->6->7->8. Example 2: Input: K = 3 value = {{1,3},{4,5,6},{8}} Output: 1 3 4 5 6 8 Explanation: The test case has 3 sorted linked list of size 2, 3, 1. 1st list 1 -> 3 2nd list 4 -> 5 -> 6 3rd list 8 The merged list will be 1->3->4->5->6->8. Your Task: The task is to complete the function mergeKList() which merges the K given lists into a sorted one. The printing is done automatically by the driver code. Expected Time Complexity: O(nk Logk) Expected Auxiliary Space: O(k) Note: n is the maximum size of all the k link list Constraints 1 <= K <= 103 0 somain1005in 11 hours JAVA 3.74/5.7 Node mergeKList(Node[]arr,int K) { //Add your code here. if(arr.length==1) return arr[0]; Node x=arr[0]; Node y=arr[0]; int count=0; for(int i=0;i<K-1;i++) { int j=0; x=arr[i]; y=arr[i]; while(y!=null) { count++; y=y.next; } while(x.next!=null) x=x.next; x.next=arr[i+1]; } y=arr[K-1]; while(y!=null) { count++; y=y.next; } Node head=arr[0]; Node curr=head; int j=0; int[] array=new int[count]; while(curr!=null) { array[j++]=curr.data; curr=curr.next; } Arrays.sort(array); curr=head; int s=0; while(curr!=null) { curr.data=array[s++]; curr=curr.next; } return head; } +1 shahabuddinbravo40in 7 hours class Solution{ public: //Function to merge K sorted linked list. Node * mergeKLists(Node *arr[], int K) { // vector<int>v; // for(int i=0;i<K;i++){ // while(arr[i]!=NULL) // { // v.push_back(arr[i]->data); // arr[i]=arr[i]->next; // } // } // sort(v.begin(),v.end()); // Node *list=new Node(-1),*head=list; // for(int i=0;i<v.size();i++){ // Node *new_node=new Node(v[i]); // list->next=new_node; // list=list->next; // } // head=head->next; // return head; priority_queue< pair<int,Node*>,vector<pair<int,Node*>>,greater<pair<int,Node*>> >minH; for(int i=0;i<K;i++) { minH.push({arr[i]->data,arr[i]}); } Node *list=new Node(-1),*head=list; while(!minH.empty()) { pair<int,Node*> p=minH.top(); Node *new_node=new Node(p.first); list->next=new_node; list=list->next; minH.pop(); if(p.second->next!=NULL){ p.second=p.second->next; minH.push({p.second->data,p.second}); } } head=head->next; return head; }}; 0 sidharthsitesh2in 4 minutes Easy Python Solution array=[] for i in arr: while i: array.append(i.data) i=i.next array.sort() head=Node(None) curr=head for i in array: curr.next=Node(i) curr=curr.next return head.next 0 abhijeet1940322 hours ago The idea behind this approach is two first merge 2 linked lists and then keep on adding other remaining linked lists to make it one big linked list. Code in C++ // Function to merge 2 linked lists Node *merge(Node *a,Node *b) { if(a==NULL) return b; if(b==NULL) return a; Node *head ; Node *tail ; if(a->data<=b->data) { head = tail = a; a = a->next; } else { head = tail = b; b = b->next; } while(a!=NULL && b!=NULL) { if(a->data<=b->data) { tail->next = a; tail = tail->next; a = a->next; } else { tail ->next = b; tail = tail->next; b = b->next; } } if(a!=NULL) tail->next = a; else tail->next = b; return head; } //Function to merge K sorted linked list. Node * mergeKLists(Node *arr[], int k) { Node *first = arr[0]; for(int i=1;i<k;i++) { Node *second = arr[i]; first = merge(first,second); } return first; } 0 santoshkumar15novmth4 days ago class compare{ public: bool operator() (Node* a, Node* b) { return a->data > b->data; }};class Solution{ public: //Function to merge K sorted linked list. Node * mergeKLists(Node *lists[], int k) { priority_queue<Node*,vector<Node*> ,compare> q; Node* dummy = new Node(-1); Node* tail = dummy; for(int i=0; i<k; i++) { if(lists[i]!=NULL) { q.push(lists[i]); } } while(q.size()) { Node* temp=q.top(); tail->next = temp; tail = temp; q.pop(); if(temp->next!=NULL) q.push(temp->next); } return dummy->next; }}; 0 shreyassakariya20021 week ago //Time : O(nk Logk) //Space: O(k) Node * mergeKLists(Node *arr[], int k) { priority_queue<pair<int,Node*>,vector<pair<int,Node*>>,greater<pair<int,Node*>>> pq; for(int i=0;i<k;i++) pq.push({arr[i]->data , arr[i]}); Node *ans=new Node(-1); Node *curr = ans; while(!pq.empty()) { Node *temp=pq.top().second; pq.pop(); curr->next = new Node(temp->data); curr=curr->next; temp=temp->next; if(temp) pq.push({temp->data,temp}); } return ans->next; } 0 rishu This comment was deleted. 0 rishu1 week ago class Solution { //Function to merge K sorted linked list. Node mergeKList(Node[]arr,int K) { //Add your code here. int i=0; if(arr.length==1){ return arr[0]; } Node head = merge(arr[0],arr[1],i+1,arr,K); return head; } static Node merge(Node a, Node b, int i, Node[]arr,int K){ Node temp1 = a; Node temp2 = b; if(i<K-1){ Node X = merge(arr[i], arr[i+1], i+1,arr, K ); temp2=X; } Node dummy = new Node(-1); Node tail=dummy; while(temp1!=null && temp2!=null){ if(temp1.data<=temp2.data){ tail.next=temp1; tail=tail.next; temp1=temp1.next; } else{ tail.next=temp2; tail=tail.next; temp2=temp2.next; } } if(temp1!=null){ tail.next=temp1; } if(temp2!=null){ tail.next=temp2; } return dummy.next; } } 0 rishu This comment was deleted. 0 amarrajsmart1972 weeks ago Node * mergeKLists(Node *arr[], int K) { // Your code here vector<int> v; int i=0; int count=1; while(count<=K) { if(!arr[i]) { count++; i++; } else { v.push_back(arr[i]->data); arr[i]=arr[i]->next; } } sort(v.begin(),v.end()); Node*head=new Node(-1); Node* it=head; i=0; while(i<v.size()) { it->next=new Node(v[i++]); it=it->next; } head=head->next; return head; } We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 388, "s": 238, "text": "Given K sorted linked lists of different sizes. The task is to merge them in such a way that after merging they will be a single sorted linked list. " }, { "code": null, "e": 399, "s": 388, "text": "Example 1:" }, { "code": null, "e": 690, "s": 399, "text": "Input:\nK = 4\nvalue = {{1,2,3},{4 5},{5 6},{7,8}}\nOutput: 1 2 3 4 5 5 6 7 8\nExplanation:\nThe test case has 4 sorted linked \nlist of size 3, 2, 2, 2\n1st list 1 -> 2-> 3\n2nd list 4->5\n3rd list 5->6\n4th list 7->8\nThe merged list will be\n1->2->3->4->5->5->6->7->8.\n" }, { "code": null, "e": 701, "s": 690, "text": "Example 2:" }, { "code": null, "e": 922, "s": 701, "text": "Input:\nK = 3\nvalue = {{1,3},{4,5,6},{8}}\nOutput: 1 3 4 5 6 8\nExplanation:\nThe test case has 3 sorted linked\nlist of size 2, 3, 1.\n1st list 1 -> 3\n2nd list 4 -> 5 -> 6\n3rd list 8\nThe merged list will be\n1->3->4->5->6->8.\n" }, { "code": null, "e": 1088, "s": 922, "text": "Your Task:\nThe task is to complete the function mergeKList() which merges the K given lists into a sorted one. The printing is done automatically by the driver code." }, { "code": null, "e": 1207, "s": 1088, "text": "Expected Time Complexity: O(nk Logk)\nExpected Auxiliary Space: O(k)\nNote: n is the maximum size of all the k link list" }, { "code": null, "e": 1233, "s": 1207, "text": "Constraints\n1 <= K <= 103" }, { "code": null, "e": 1237, "s": 1235, "text": "0" }, { "code": null, "e": 1259, "s": 1237, "text": "somain1005in 11 hours" }, { "code": null, "e": 1274, "s": 1259, "text": "JAVA 3.74/5.7" }, { "code": null, "e": 1708, "s": 1276, "text": " Node mergeKList(Node[]arr,int K) { //Add your code here. if(arr.length==1) return arr[0]; Node x=arr[0]; Node y=arr[0]; int count=0; for(int i=0;i<K-1;i++) { int j=0; x=arr[i]; y=arr[i]; while(y!=null) { count++; y=y.next; } while(x.next!=null) x=x.next;" }, { "code": null, "e": 2228, "s": 1708, "text": " x.next=arr[i+1]; } y=arr[K-1]; while(y!=null) { count++; y=y.next; } Node head=arr[0]; Node curr=head; int j=0; int[] array=new int[count]; while(curr!=null) { array[j++]=curr.data; curr=curr.next; } Arrays.sort(array); curr=head; int s=0; while(curr!=null) { curr.data=array[s++]; curr=curr.next; } return head; }" }, { "code": null, "e": 2231, "s": 2228, "text": "+1" }, { "code": null, "e": 2260, "s": 2231, "text": "shahabuddinbravo40in 7 hours" }, { "code": null, "e": 3636, "s": 2260, "text": "class Solution{ public: //Function to merge K sorted linked list. Node * mergeKLists(Node *arr[], int K) { // vector<int>v; // for(int i=0;i<K;i++){ // while(arr[i]!=NULL) // { // v.push_back(arr[i]->data); // arr[i]=arr[i]->next; // } // } // sort(v.begin(),v.end()); // Node *list=new Node(-1),*head=list; // for(int i=0;i<v.size();i++){ // Node *new_node=new Node(v[i]); // list->next=new_node; // list=list->next; // } // head=head->next; // return head; priority_queue< pair<int,Node*>,vector<pair<int,Node*>>,greater<pair<int,Node*>> >minH; for(int i=0;i<K;i++) { minH.push({arr[i]->data,arr[i]}); } Node *list=new Node(-1),*head=list; while(!minH.empty()) { pair<int,Node*> p=minH.top(); Node *new_node=new Node(p.first); list->next=new_node; list=list->next; minH.pop(); if(p.second->next!=NULL){ p.second=p.second->next; minH.push({p.second->data,p.second}); } } head=head->next; return head; }}; " }, { "code": null, "e": 3638, "s": 3636, "text": "0" }, { "code": null, "e": 3666, "s": 3638, "text": "sidharthsitesh2in 4 minutes" }, { "code": null, "e": 3687, "s": 3666, "text": "Easy Python Solution" }, { "code": null, "e": 3965, "s": 3689, "text": " array=[] for i in arr: while i: array.append(i.data) i=i.next array.sort() head=Node(None) curr=head for i in array: curr.next=Node(i) curr=curr.next return head.next" }, { "code": null, "e": 3967, "s": 3965, "text": "0" }, { "code": null, "e": 3993, "s": 3967, "text": "abhijeet1940322 hours ago" }, { "code": null, "e": 4142, "s": 3993, "text": "The idea behind this approach is two first merge 2 linked lists and then keep on adding other remaining linked lists to make it one big linked list." }, { "code": null, "e": 4156, "s": 4144, "text": "Code in C++" }, { "code": null, "e": 5201, "s": 4158, "text": "// Function to merge 2 linked lists Node *merge(Node *a,Node *b) { if(a==NULL) return b; if(b==NULL) return a; Node *head ; Node *tail ; if(a->data<=b->data) { head = tail = a; a = a->next; } else { head = tail = b; b = b->next; } while(a!=NULL && b!=NULL) { if(a->data<=b->data) { tail->next = a; tail = tail->next; a = a->next; } else { tail ->next = b; tail = tail->next; b = b->next; } } if(a!=NULL) tail->next = a; else tail->next = b; return head; } //Function to merge K sorted linked list. Node * mergeKLists(Node *arr[], int k) { Node *first = arr[0]; for(int i=1;i<k;i++) { Node *second = arr[i]; first = merge(first,second); } return first; }" }, { "code": null, "e": 5203, "s": 5201, "text": "0" }, { "code": null, "e": 5234, "s": 5203, "text": "santoshkumar15novmth4 days ago" }, { "code": null, "e": 5936, "s": 5234, "text": "class compare{ public: bool operator() (Node* a, Node* b) { return a->data > b->data; }};class Solution{ public: //Function to merge K sorted linked list. Node * mergeKLists(Node *lists[], int k) { priority_queue<Node*,vector<Node*> ,compare> q; Node* dummy = new Node(-1); Node* tail = dummy; for(int i=0; i<k; i++) { if(lists[i]!=NULL) { q.push(lists[i]); } } while(q.size()) { Node* temp=q.top(); tail->next = temp; tail = temp; q.pop(); if(temp->next!=NULL) q.push(temp->next); } return dummy->next; }};" }, { "code": null, "e": 5938, "s": 5936, "text": "0" }, { "code": null, "e": 5968, "s": 5938, "text": "shreyassakariya20021 week ago" }, { "code": null, "e": 6638, "s": 5968, "text": "//Time : O(nk Logk)\n//Space: O(k)\n\nNode * mergeKLists(Node *arr[], int k)\n {\n priority_queue<pair<int,Node*>,vector<pair<int,Node*>>,greater<pair<int,Node*>>> pq;\n \n for(int i=0;i<k;i++)\n pq.push({arr[i]->data , arr[i]});\n \n Node *ans=new Node(-1);\n Node *curr = ans;\n \n while(!pq.empty())\n {\n Node *temp=pq.top().second;\n pq.pop();\n \n curr->next = new Node(temp->data);\n curr=curr->next;\n \n temp=temp->next;\n if(temp)\n pq.push({temp->data,temp});\n }\n return ans->next;\n }" }, { "code": null, "e": 6640, "s": 6638, "text": "0" }, { "code": null, "e": 6646, "s": 6640, "text": "rishu" }, { "code": null, "e": 6672, "s": 6646, "text": "This comment was deleted." }, { "code": null, "e": 6674, "s": 6672, "text": "0" }, { "code": null, "e": 6690, "s": 6674, "text": "rishu1 week ago" }, { "code": null, "e": 7752, "s": 6690, "text": "class Solution\n{\n //Function to merge K sorted linked list.\n Node mergeKList(Node[]arr,int K)\n {\n //Add your code here.\n int i=0;\n if(arr.length==1){\n return arr[0];\n }\n Node head = merge(arr[0],arr[1],i+1,arr,K);\n return head;\n \n }\n static Node merge(Node a, Node b, int i, Node[]arr,int K){\n Node temp1 = a;\n Node temp2 = b;\n if(i<K-1){\n Node X = merge(arr[i], arr[i+1], i+1,arr, K );\n temp2=X;\n }\n Node dummy = new Node(-1);\n Node tail=dummy;\n while(temp1!=null && temp2!=null){\n if(temp1.data<=temp2.data){\n tail.next=temp1;\n tail=tail.next;\n temp1=temp1.next;\n }\n else{\n tail.next=temp2;\n tail=tail.next;\n temp2=temp2.next;\n } \n \n }\n if(temp1!=null){\n tail.next=temp1;\n }\n if(temp2!=null){\n tail.next=temp2;\n }\n return dummy.next;\n }\n}" }, { "code": null, "e": 7754, "s": 7752, "text": "0" }, { "code": null, "e": 7760, "s": 7754, "text": "rishu" }, { "code": null, "e": 7786, "s": 7760, "text": "This comment was deleted." }, { "code": null, "e": 7788, "s": 7786, "text": "0" }, { "code": null, "e": 7815, "s": 7788, "text": "amarrajsmart1972 weeks ago" }, { "code": null, "e": 8512, "s": 7815, "text": "Node * mergeKLists(Node *arr[], int K) { // Your code here vector<int> v; int i=0; int count=1; while(count<=K) { if(!arr[i]) { count++; i++; } else { v.push_back(arr[i]->data); arr[i]=arr[i]->next; } } sort(v.begin(),v.end()); Node*head=new Node(-1); Node* it=head; i=0; while(i<v.size()) { it->next=new Node(v[i++]); it=it->next; } head=head->next; return head; }" }, { "code": null, "e": 8658, "s": 8512, "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": 8694, "s": 8658, "text": " Login to access your submissions. " }, { "code": null, "e": 8704, "s": 8694, "text": "\nProblem\n" }, { "code": null, "e": 8714, "s": 8704, "text": "\nContest\n" }, { "code": null, "e": 8777, "s": 8714, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8925, "s": 8777, "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": 9133, "s": 8925, "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": 9239, "s": 9133, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
AngularJS | angular.isDate() Function - GeeksforGeeks
12 Apr, 2019 The angular.isDate() function in AngularJS is used to determine the value of date is valid or not. It returns true if the reference is a date else false. Syntax: angular.isDate( value ) Parameters: This function accepts single parameter value which stores the date object. Return Value: It returns true if the value passed is date else return false. Example: This example uses angular.isDate() function to determine the value of date is valid or not. <!DOCTYPE html><html> <head> <title>angular.isDate() function</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"> </script></head> <body ng-app="app" style="text-align:center"> <h1 style="color:green">GeeksforGeeks</h1> <h2>angular.isDate()</h2> <div ng-controller="geek"> <b>Date:</b> {{ date }} <br><br> isDate: {{isDate}} </div> <!-- Script to uses angular.isDate() function --> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.date = new Date; $scope.isDate = angular.isDate($scope.date) }]); </script></body> </html> Output: AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular File Upload Top 10 Angular Libraries For Web Developers Angular | keyup event Auth Guards in Angular 9/10/11 What is AOT and JIT Compiler in Angular ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28271, "s": 28243, "text": "\n12 Apr, 2019" }, { "code": null, "e": 28425, "s": 28271, "text": "The angular.isDate() function in AngularJS is used to determine the value of date is valid or not. It returns true if the reference is a date else false." }, { "code": null, "e": 28433, "s": 28425, "text": "Syntax:" }, { "code": null, "e": 28457, "s": 28433, "text": "angular.isDate( value )" }, { "code": null, "e": 28544, "s": 28457, "text": "Parameters: This function accepts single parameter value which stores the date object." }, { "code": null, "e": 28621, "s": 28544, "text": "Return Value: It returns true if the value passed is date else return false." }, { "code": null, "e": 28722, "s": 28621, "text": "Example: This example uses angular.isDate() function to determine the value of date is valid or not." }, { "code": "<!DOCTYPE html><html> <head> <title>angular.isDate() function</title> <script src=\"//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js\"> </script></head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green\">GeeksforGeeks</h1> <h2>angular.isDate()</h2> <div ng-controller=\"geek\"> <b>Date:</b> {{ date }} <br><br> isDate: {{isDate}} </div> <!-- Script to uses angular.isDate() function --> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.date = new Date; $scope.isDate = angular.isDate($scope.date) }]); </script></body> </html> ", "e": 29469, "s": 28722, "text": null }, { "code": null, "e": 29477, "s": 29469, "text": "Output:" }, { "code": null, "e": 29487, "s": 29477, "text": "AngularJS" }, { "code": null, "e": 29504, "s": 29487, "text": "Web Technologies" }, { "code": null, "e": 29602, "s": 29504, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29622, "s": 29602, "text": "Angular File Upload" }, { "code": null, "e": 29666, "s": 29622, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29688, "s": 29666, "text": "Angular | keyup event" }, { "code": null, "e": 29719, "s": 29688, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29761, "s": 29719, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 29803, "s": 29761, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 29836, "s": 29803, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29879, "s": 29836, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29941, "s": 29879, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
How to disable right click using jQuery?
To disable right click on a page, use the jQuery bind() method. You can try to run the following code to learn how to disable right click: Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $(document).bind("contextmenu",function(e){ return false; }); }); </script> </head> <body> <p>Right click is disabled on this page.</p> </body> </html>
[ { "code": null, "e": 1126, "s": 1062, "text": "To disable right click on a page, use the jQuery bind() method." }, { "code": null, "e": 1201, "s": 1126, "text": "You can try to run the following code to learn how to disable right click:" }, { "code": null, "e": 1211, "s": 1201, "text": "Live Demo" }, { "code": null, "e": 1535, "s": 1211, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(document).bind(\"contextmenu\",function(e){\n return false;\n });\n});\n</script>\n</head>\n<body>\n\n<p>Right click is disabled on this page.</p>\n\n</body>\n</html>" } ]
Unidirectional Channel in Golang - GeeksforGeeks
18 May, 2020 As we know that a channel is a medium of communication between concurrently running goroutines so that they can send and receive data to each other. By default a channel is bidirectional but you can create a unidirectional channel also. A channel that can only receive data or a channel that can only send data is the unidirectional channel. The unidirectional channel can also create with the help of make() function as shown below: // Only to receive data c1:= make(<- chan bool) // Only to send data c2:= make(chan<-bool Example 1: // Go program to illustrate the concept// of the unidirectional channelpackage main import "fmt" // Main functionfunc main() { // Only for receiving mychanl1 := make(<-chan string) // Only for sending mychanl2 := make(chan<- string) // Display the types of channels fmt.Printf("%T", mychanl1) fmt.Printf("\n%T", mychanl2)} Output: <-chan string chan<- string In Go language, you are allowed to convert a bidirectional channel into the unidirectional channel, or in other words, you can convert a bidirectional channel into a receive-only or send-only channel, but vice versa is not possible. As shown in the below program: Example: // Go program to illustrate how to convert// bidirectional channel into the// unidirectional channelpackage main import "fmt" func sending(s chan<- string) { s <- "GeeksforGeeks"} func main() { // Creating a bidirectional channel mychanl := make(chan string) // Here, sending() function convert // the bidirectional channel // into send only channel go sending(mychanl) // Here, the channel is sent // only inside the goroutine // outside the goroutine the // channel is bidirectional // So, it print GeeksforGeeks fmt.Println(<-mychanl)} Output: GeeksforGeeks Use of Unidirectional Channel: The unidirectional channel is used to provide the type-safety of the program so, that the program gives less error. Or you can also use a unidirectional channel when you want to create a channel that can only send or receive data. amit bhaira Golang Golang-Concurrency Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Replace() Function in Golang With Examples strings.Contains Function in Golang with Examples Time Formatting in Golang fmt.Sprintf() Function in Golang With Examples Golang Maps How to convert a string in lower case in Golang? Different Ways to Find the Type of Variable in Golang Inheritance in GoLang
[ { "code": null, "e": 24515, "s": 24487, "text": "\n18 May, 2020" }, { "code": null, "e": 24949, "s": 24515, "text": "As we know that a channel is a medium of communication between concurrently running goroutines so that they can send and receive data to each other. By default a channel is bidirectional but you can create a unidirectional channel also. A channel that can only receive data or a channel that can only send data is the unidirectional channel. The unidirectional channel can also create with the help of make() function as shown below:" }, { "code": null, "e": 25041, "s": 24949, "text": "// Only to receive data\nc1:= make(<- chan bool)\n\n// Only to send data\nc2:= make(chan<-bool\n" }, { "code": null, "e": 25052, "s": 25041, "text": "Example 1:" }, { "code": "// Go program to illustrate the concept// of the unidirectional channelpackage main import \"fmt\" // Main functionfunc main() { // Only for receiving mychanl1 := make(<-chan string) // Only for sending mychanl2 := make(chan<- string) // Display the types of channels fmt.Printf(\"%T\", mychanl1) fmt.Printf(\"\\n%T\", mychanl2)}", "e": 25404, "s": 25052, "text": null }, { "code": null, "e": 25412, "s": 25404, "text": "Output:" }, { "code": null, "e": 25441, "s": 25412, "text": "<-chan string\nchan<- string\n" }, { "code": null, "e": 25705, "s": 25441, "text": "In Go language, you are allowed to convert a bidirectional channel into the unidirectional channel, or in other words, you can convert a bidirectional channel into a receive-only or send-only channel, but vice versa is not possible. As shown in the below program:" }, { "code": null, "e": 25714, "s": 25705, "text": "Example:" }, { "code": "// Go program to illustrate how to convert// bidirectional channel into the// unidirectional channelpackage main import \"fmt\" func sending(s chan<- string) { s <- \"GeeksforGeeks\"} func main() { // Creating a bidirectional channel mychanl := make(chan string) // Here, sending() function convert // the bidirectional channel // into send only channel go sending(mychanl) // Here, the channel is sent // only inside the goroutine // outside the goroutine the // channel is bidirectional // So, it print GeeksforGeeks fmt.Println(<-mychanl)}", "e": 26303, "s": 25714, "text": null }, { "code": null, "e": 26311, "s": 26303, "text": "Output:" }, { "code": null, "e": 26325, "s": 26311, "text": "GeeksforGeeks" }, { "code": null, "e": 26587, "s": 26325, "text": "Use of Unidirectional Channel: The unidirectional channel is used to provide the type-safety of the program so, that the program gives less error. Or you can also use a unidirectional channel when you want to create a channel that can only send or receive data." }, { "code": null, "e": 26599, "s": 26587, "text": "amit bhaira" }, { "code": null, "e": 26606, "s": 26599, "text": "Golang" }, { "code": null, "e": 26625, "s": 26606, "text": "Golang-Concurrency" }, { "code": null, "e": 26637, "s": 26625, "text": "Go Language" }, { "code": null, "e": 26735, "s": 26637, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26744, "s": 26735, "text": "Comments" }, { "code": null, "e": 26757, "s": 26744, "text": "Old Comments" }, { "code": null, "e": 26809, "s": 26757, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 26855, "s": 26809, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 26906, "s": 26855, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 26956, "s": 26906, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 26982, "s": 26956, "text": "Time Formatting in Golang" }, { "code": null, "e": 27029, "s": 26982, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 27041, "s": 27029, "text": "Golang Maps" }, { "code": null, "e": 27090, "s": 27041, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 27144, "s": 27090, "text": "Different Ways to Find the Type of Variable in Golang" } ]
Print All Link Name Using Selenium In Python - GeeksforGeeks
12 Nov, 2020 Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Requirements: You need to install chromedriver and set path. Click here to download. Note: For more information follows this link. Step-by-step Approach: Import required modules Taking any URL. using By.TAG_NAME find web link on a webpage. then use a loop for print link name. Implementation: Python3 #import modulefrom selenium import webdriverfrom selenium.webdriver.common.by import By driver = webdriver.Chrome() # urldriver.get('https://www.youtube.com/') # find web linkslink = driver.find_elements(By.TAG_NAME, 'a') # print name of all linksfor i in link: print(i.text) Output: Python-selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n12 Nov, 2020" }, { "code": null, "e": 25811, "s": 25537, "text": "Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python." }, { "code": null, "e": 25825, "s": 25811, "text": "Requirements:" }, { "code": null, "e": 25896, "s": 25825, "text": "You need to install chromedriver and set path. Click here to download." }, { "code": null, "e": 25942, "s": 25896, "text": "Note: For more information follows this link." }, { "code": null, "e": 25965, "s": 25942, "text": "Step-by-step Approach:" }, { "code": null, "e": 25989, "s": 25965, "text": "Import required modules" }, { "code": null, "e": 26005, "s": 25989, "text": "Taking any URL." }, { "code": null, "e": 26051, "s": 26005, "text": "using By.TAG_NAME find web link on a webpage." }, { "code": null, "e": 26088, "s": 26051, "text": "then use a loop for print link name." }, { "code": null, "e": 26104, "s": 26088, "text": "Implementation:" }, { "code": null, "e": 26112, "s": 26104, "text": "Python3" }, { "code": "#import modulefrom selenium import webdriverfrom selenium.webdriver.common.by import By driver = webdriver.Chrome() # urldriver.get('https://www.youtube.com/') # find web linkslink = driver.find_elements(By.TAG_NAME, 'a') # print name of all linksfor i in link: print(i.text)", "e": 26397, "s": 26112, "text": null }, { "code": null, "e": 26405, "s": 26397, "text": "Output:" }, { "code": null, "e": 26421, "s": 26405, "text": "Python-selenium" }, { "code": null, "e": 26428, "s": 26421, "text": "Python" }, { "code": null, "e": 26526, "s": 26428, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26558, "s": 26526, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26600, "s": 26558, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26642, "s": 26600, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26669, "s": 26642, "text": "Python Classes and Objects" }, { "code": null, "e": 26725, "s": 26669, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26747, "s": 26725, "text": "Defaultdict in Python" }, { "code": null, "e": 26786, "s": 26747, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26817, "s": 26786, "text": "Python | os.path.join() method" }, { "code": null, "e": 26846, "s": 26817, "text": "Create a directory in Python" } ]
Solidity - Arrays - GeeksforGeeks
11 May, 2022 Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index. In Solidity, an array can be of fixed size or dynamic size. Arrays have a continuous memory location, where the lowest index corresponds to the first element while the highest represents the last To declare an array in Solidity, the data type of the elements and the number of elements should be specified. The size of the array must be a positive integer and data type should be a valid Solidity type Syntax: <data type> <array name>[size] = <initialization> The size of the array should be predefined. The total number of elements should not exceed the size of the array. If the size of the array is not specified then the array of enough size is created which is enough to hold the initialization. Example: In the below example, the contract Types are created to demonstrate how to declare and initialize fixed-size arrays. Solidity // Solidity program to demonstrate // creating a fixed-size array pragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring state variables // of type array uint[6] data1; // Defining function to add // values to an array function array_example() public returns ( int[5] memory, uint[6] memory){ int[5] memory data = [int(50), -63, 77, -28, 90]; data1 = [uint(10), 20, 30, 40, 50, 60]; return (data, data1); } } Output : The size of the array is not predefined when it is declared. As the elements are added the size of array changes and at the runtime, the size of the array will be determined. Example: In the below example, the contract Types are created to demonstrate how to create and initialize dynamic arrays. Solidity // Solidity program to demonstrate // creating a dynamic arraypragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring state variable // of type array. One is fixed-size // and the other is dynamic array uint[] data = [10, 20, 30, 40, 50]; int[] data1; // Defining function to // assign values to dynamic array function dynamic_array() public returns( uint[] memory, int[] memory){ data1 = [int(-60), 70, -80, 90, -100, -120, 140]; return (data, data1); } } Output : 1. Accessing Array Elements: The elements of the array are accessed by using the index. If you want to access ith element then you have to access (i-1)th index. Example: In the below example, the contract Types first initializes an array[data] and then retrieves the value at specific index 2. Solidity // Solidity program to demonstrate// accessing elements of an arraypragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring an array uint[6] data; // Defining function to // assign values to array function array_example( ) public payable returns (uint[6] memory){ data = [uint(10), 20, 30, 40, 50, 60]; return data; } // Defining function to access // values from the array // from a specific index function array_element( ) public payable returns (uint){ uint x = data[2]; return x; } } Output : 2. Length of Array: Length of the array is used to check the number of elements present in an array. The size of the memory array is fixed when they are declared, while in case the dynamic array is defined at runtime so for manipulation length is required. Example: In the below example, the contract Types first initializes an array[data] and then the length of the array is calculated. Solidity // Solidity program to demonstrate // how to find length of an arraypragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring an array uint[6] data; // Defining a function to // assign values to an array function array_example( ) public payable returns (uint[6] memory){ data = [uint(10), 20, 30, 40, 50, 60]; return data; } // Defining a function to // find the length of the array function array_length( ) public returns(uint) { uint x = data.length; return x; } } Output : 3. Push: Push is used when a new element is to be added in a dynamic array. The new element is always added at the last position of the array. Example: In the below example, the contract Types first initializes an array[data], and then more values are pushed into the array. Solidity // Solidity program to demonstrate // Push operationpragma solidity ^0.5.0; // Creating a contract contract Types { // Defining the array uint[] data = [10, 20, 30, 40, 50]; // Defining the function to push // values to the array function array_push( ) public returns(uint[] memory){ data.push(60); data.push(70); data.push(80); return data; } } Output : 4. Pop: Pop is used when the last element of the array is to be removed in any dynamic array. Example: In the below example, the contract Types first initializes an array[data], and then values are removed from the array using the pop function. Solidity // Solidity program to demonstrate// Pop operationpragma solidity ^0.5.0; // Creating a contractcontract Types { // Defining an array uint[] data = [10, 20, 30, 40, 50]; // Defining a function to // pop values from the array function array_pop( ) public returns(uint[] memory){ data.pop(); return data; } } Output : Solidity-Arrays Blockchain Solidity Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Storage vs Memory in Solidity Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network How to Become a Blockchain Developer? How to connect ReactJS with MetaMask ? Proof of Work (PoW) Consensus Storage vs Memory in Solidity Solidity - Inheritance Mathematical Operations in Solidity How to Install Solidity in Windows? Dynamic Arrays and its Operations in Solidity
[ { "code": null, "e": 25741, "s": 25713, "text": "\n11 May, 2022" }, { "code": null, "e": 26289, "s": 25741, "text": "Arrays are data structures that store the fixed collection of elements of the same data types in which each and every element has a specific location called index. Instead of creating numerous individual variables of the same type, we just declare one array of the required size and store the elements in the array and can be accessed using the index. In Solidity, an array can be of fixed size or dynamic size. Arrays have a continuous memory location, where the lowest index corresponds to the first element while the highest represents the last" }, { "code": null, "e": 26495, "s": 26289, "text": "To declare an array in Solidity, the data type of the elements and the number of elements should be specified. The size of the array must be a positive integer and data type should be a valid Solidity type" }, { "code": null, "e": 26503, "s": 26495, "text": "Syntax:" }, { "code": null, "e": 26554, "s": 26503, "text": "<data type> <array name>[size] = <initialization>\n" }, { "code": null, "e": 26795, "s": 26554, "text": "The size of the array should be predefined. The total number of elements should not exceed the size of the array. If the size of the array is not specified then the array of enough size is created which is enough to hold the initialization." }, { "code": null, "e": 26921, "s": 26795, "text": "Example: In the below example, the contract Types are created to demonstrate how to declare and initialize fixed-size arrays." }, { "code": null, "e": 26930, "s": 26921, "text": "Solidity" }, { "code": "// Solidity program to demonstrate // creating a fixed-size array pragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring state variables // of type array uint[6] data1; // Defining function to add // values to an array function array_example() public returns ( int[5] memory, uint[6] memory){ int[5] memory data = [int(50), -63, 77, -28, 90]; data1 = [uint(10), 20, 30, 40, 50, 60]; return (data, data1); } }", "e": 27470, "s": 26930, "text": null }, { "code": null, "e": 27480, "s": 27470, "text": "Output : " }, { "code": null, "e": 27655, "s": 27480, "text": "The size of the array is not predefined when it is declared. As the elements are added the size of array changes and at the runtime, the size of the array will be determined." }, { "code": null, "e": 27778, "s": 27655, "text": "Example: In the below example, the contract Types are created to demonstrate how to create and initialize dynamic arrays. " }, { "code": null, "e": 27787, "s": 27778, "text": "Solidity" }, { "code": "// Solidity program to demonstrate // creating a dynamic arraypragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring state variable // of type array. One is fixed-size // and the other is dynamic array uint[] data = [10, 20, 30, 40, 50]; int[] data1; // Defining function to // assign values to dynamic array function dynamic_array() public returns( uint[] memory, int[] memory){ data1 = [int(-60), 70, -80, 90, -100, -120, 140]; return (data, data1); } }", "e": 28356, "s": 27787, "text": null }, { "code": null, "e": 28366, "s": 28356, "text": "Output : " }, { "code": null, "e": 28527, "s": 28366, "text": "1. Accessing Array Elements: The elements of the array are accessed by using the index. If you want to access ith element then you have to access (i-1)th index." }, { "code": null, "e": 28660, "s": 28527, "text": "Example: In the below example, the contract Types first initializes an array[data] and then retrieves the value at specific index 2." }, { "code": null, "e": 28669, "s": 28660, "text": "Solidity" }, { "code": "// Solidity program to demonstrate// accessing elements of an arraypragma solidity ^0.5.0; // Creating a contract contract Types { // Declaring an array uint[6] data; // Defining function to // assign values to array function array_example( ) public payable returns (uint[6] memory){ data = [uint(10), 20, 30, 40, 50, 60]; return data; } // Defining function to access // values from the array // from a specific index function array_element( ) public payable returns (uint){ uint x = data[2]; return x; } }", "e": 29288, "s": 28669, "text": null }, { "code": null, "e": 29298, "s": 29288, "text": "Output : " }, { "code": null, "e": 29555, "s": 29298, "text": "2. Length of Array: Length of the array is used to check the number of elements present in an array. The size of the memory array is fixed when they are declared, while in case the dynamic array is defined at runtime so for manipulation length is required." }, { "code": null, "e": 29686, "s": 29555, "text": "Example: In the below example, the contract Types first initializes an array[data] and then the length of the array is calculated." }, { "code": null, "e": 29695, "s": 29686, "text": "Solidity" }, { "code": "// Solidity program to demonstrate // how to find length of an arraypragma solidity ^0.5.0; // Creating a contractcontract Types { // Declaring an array uint[6] data; // Defining a function to // assign values to an array function array_example( ) public payable returns (uint[6] memory){ data = [uint(10), 20, 30, 40, 50, 60]; return data; } // Defining a function to // find the length of the array function array_length( ) public returns(uint) { uint x = data.length; return x; } }", "e": 30268, "s": 29695, "text": null }, { "code": null, "e": 30278, "s": 30268, "text": "Output : " }, { "code": null, "e": 30421, "s": 30278, "text": "3. Push: Push is used when a new element is to be added in a dynamic array. The new element is always added at the last position of the array." }, { "code": null, "e": 30553, "s": 30421, "text": "Example: In the below example, the contract Types first initializes an array[data], and then more values are pushed into the array." }, { "code": null, "e": 30562, "s": 30553, "text": "Solidity" }, { "code": "// Solidity program to demonstrate // Push operationpragma solidity ^0.5.0; // Creating a contract contract Types { // Defining the array uint[] data = [10, 20, 30, 40, 50]; // Defining the function to push // values to the array function array_push( ) public returns(uint[] memory){ data.push(60); data.push(70); data.push(80); return data; } }", "e": 30988, "s": 30562, "text": null }, { "code": null, "e": 30999, "s": 30988, "text": "Output : " }, { "code": null, "e": 31093, "s": 30999, "text": "4. Pop: Pop is used when the last element of the array is to be removed in any dynamic array." }, { "code": null, "e": 31244, "s": 31093, "text": "Example: In the below example, the contract Types first initializes an array[data], and then values are removed from the array using the pop function." }, { "code": null, "e": 31253, "s": 31244, "text": "Solidity" }, { "code": "// Solidity program to demonstrate// Pop operationpragma solidity ^0.5.0; // Creating a contractcontract Types { // Defining an array uint[] data = [10, 20, 30, 40, 50]; // Defining a function to // pop values from the array function array_pop( ) public returns(uint[] memory){ data.pop(); return data; } }", "e": 31621, "s": 31253, "text": null }, { "code": null, "e": 31631, "s": 31621, "text": "Output : " }, { "code": null, "e": 31647, "s": 31631, "text": "Solidity-Arrays" }, { "code": null, "e": 31658, "s": 31647, "text": "Blockchain" }, { "code": null, "e": 31667, "s": 31658, "text": "Solidity" }, { "code": null, "e": 31765, "s": 31667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31795, "s": 31765, "text": "Storage vs Memory in Solidity" }, { "code": null, "e": 31867, "s": 31795, "text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network" }, { "code": null, "e": 31905, "s": 31867, "text": "How to Become a Blockchain Developer?" }, { "code": null, "e": 31944, "s": 31905, "text": "How to connect ReactJS with MetaMask ?" }, { "code": null, "e": 31974, "s": 31944, "text": "Proof of Work (PoW) Consensus" }, { "code": null, "e": 32004, "s": 31974, "text": "Storage vs Memory in Solidity" }, { "code": null, "e": 32027, "s": 32004, "text": "Solidity - Inheritance" }, { "code": null, "e": 32063, "s": 32027, "text": "Mathematical Operations in Solidity" }, { "code": null, "e": 32099, "s": 32063, "text": "How to Install Solidity in Windows?" } ]
How to Get the Size of a Table in MySQL using Python? - GeeksforGeeks
26 Dec, 2020 Prerequisite: Python: MySQL Create Table In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. Approach: Import module. Make a connection request with the database. Create an object for the database cursor. Execute the following MySQL query: SELECT table_name AS `Table`, round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM information_schema.TABLES WHERE table_schema = ‘DataBase_name’ AND table_name = ‘Table_name’; Example 1: In this example we are using this database table with the following query; Below is the implementation: Python3 # Import required moduleimport mysql.connector # Establish connection# to MySQL databasemydb = mysql.connector.connect( host="localhost", user="root", password="root123", database="geeks") # Create cursor objectmycursor = mydb.cursor() # Execute queryquery = "SELECT table_name AS `Table`, \ round(((data_length + index_length) \ / 1024 / 1024), 2) `Size in MB` \ FROM information_schema.TABLES \ WHERE table_schema = 'Geeks' AND \ table_name = 'Persons';" mycursor.execute(query) # Display size of each tablemyresult = mycursor.fetchall() for item in myresult: print(item[0], "Size in MB: ", item[-1]) Output: Example 2: In this example, we are going to get all table sizes in a database. Below is the implementation: Python3 # Import required moduleimport mysql.connector # Establish connection# to MySQL databasemydb = mysql.connector.connect( host="localhost", user="root", password="root123", database="geeks") # Create cursor objectmycursor = mydb.cursor() # Execute queryquery = "SELECT TABLE_NAME AS `Table`, \ ROUND(((DATA_LENGTH + INDEX_LENGTH) \ / 1024 / 1024),2) AS `Size (MB)` \ FROM information_schema.TABLES WHERE \ TABLE_SCHEMA = 'Geeks' ORDER BY \ (DATA_LENGTH + INDEX_LENGTH) DESC;" mycursor.execute(query) # Display size of each tablemyresult = mycursor.fetchall() for item in myresult: print(item[0], "Size in MB: ", item[-1]) Output: Picked Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n26 Dec, 2020" }, { "code": null, "e": 25578, "s": 25537, "text": "Prerequisite: Python: MySQL Create Table" }, { "code": null, "e": 25913, "s": 25578, "text": "In this article, we are going to see how to get the size of a table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database. " }, { "code": null, "e": 25923, "s": 25913, "text": "Approach:" }, { "code": null, "e": 25938, "s": 25923, "text": "Import module." }, { "code": null, "e": 25983, "s": 25938, "text": "Make a connection request with the database." }, { "code": null, "e": 26025, "s": 25983, "text": "Create an object for the database cursor." }, { "code": null, "e": 26060, "s": 26025, "text": "Execute the following MySQL query:" }, { "code": null, "e": 26259, "s": 26060, "text": "SELECT table_name AS `Table`, round(((data_length + index_length) / 1024 / 1024), 2) `Size in MB` FROM information_schema.TABLES WHERE table_schema = ‘DataBase_name’ AND table_name = ‘Table_name’;" }, { "code": null, "e": 26270, "s": 26259, "text": "Example 1:" }, { "code": null, "e": 26345, "s": 26270, "text": "In this example we are using this database table with the following query;" }, { "code": null, "e": 26374, "s": 26345, "text": "Below is the implementation:" }, { "code": null, "e": 26382, "s": 26374, "text": "Python3" }, { "code": "# Import required moduleimport mysql.connector # Establish connection# to MySQL databasemydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"root123\", database=\"geeks\") # Create cursor objectmycursor = mydb.cursor() # Execute queryquery = \"SELECT table_name AS `Table`, \\ round(((data_length + index_length) \\ / 1024 / 1024), 2) `Size in MB` \\ FROM information_schema.TABLES \\ WHERE table_schema = 'Geeks' AND \\ table_name = 'Persons';\" mycursor.execute(query) # Display size of each tablemyresult = mycursor.fetchall() for item in myresult: print(item[0], \"Size in MB: \", item[-1])", "e": 27042, "s": 26382, "text": null }, { "code": null, "e": 27050, "s": 27042, "text": "Output:" }, { "code": null, "e": 27061, "s": 27050, "text": "Example 2:" }, { "code": null, "e": 27129, "s": 27061, "text": "In this example, we are going to get all table sizes in a database." }, { "code": null, "e": 27158, "s": 27129, "text": "Below is the implementation:" }, { "code": null, "e": 27166, "s": 27158, "text": "Python3" }, { "code": "# Import required moduleimport mysql.connector # Establish connection# to MySQL databasemydb = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"root123\", database=\"geeks\") # Create cursor objectmycursor = mydb.cursor() # Execute queryquery = \"SELECT TABLE_NAME AS `Table`, \\ ROUND(((DATA_LENGTH + INDEX_LENGTH) \\ / 1024 / 1024),2) AS `Size (MB)` \\ FROM information_schema.TABLES WHERE \\ TABLE_SCHEMA = 'Geeks' ORDER BY \\ (DATA_LENGTH + INDEX_LENGTH) DESC;\" mycursor.execute(query) # Display size of each tablemyresult = mycursor.fetchall() for item in myresult: print(item[0], \"Size in MB: \", item[-1])", "e": 27848, "s": 27166, "text": null }, { "code": null, "e": 27856, "s": 27848, "text": "Output:" }, { "code": null, "e": 27863, "s": 27856, "text": "Picked" }, { "code": null, "e": 27876, "s": 27863, "text": "Python-mySQL" }, { "code": null, "e": 27883, "s": 27876, "text": "Python" }, { "code": null, "e": 27981, "s": 27883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28013, "s": 27981, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28055, "s": 28013, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28097, "s": 28055, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28124, "s": 28097, "text": "Python Classes and Objects" }, { "code": null, "e": 28180, "s": 28124, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28219, "s": 28180, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28241, "s": 28219, "text": "Defaultdict in Python" }, { "code": null, "e": 28272, "s": 28241, "text": "Python | os.path.join() method" }, { "code": null, "e": 28301, "s": 28272, "text": "Create a directory in Python" } ]
CSS | radial-gradient() Function - GeeksforGeeks
30 Jul, 2021 The radial-gradient() function is an inbuilt function in CSS which is used to set a radial gradient as the background image. It starts at a single point and emanates outward. By default, the first color starts at the center position of the element and then fade to the end color towards the edge of the element. Fade happens at an equal rate until specified.Syntax: background-image: radial-gradient( shape size at position, start-color, ..., last-color ); Parameters: This function accepts many parameters which are listed below: shape: This parameter is used to define the shape of gradient. It has two possible value circle or ellipse. The default shape value is ellipse. size: This parameter is used to define the size of gradient. The possible value are: farthest-corner (default), closest-side, closest-corner, farthest-side. position: This parameter is used to define the position of gradient. The default value is center. start-color, ..., last-color: This parameter is used to hold the color value followed by its optional stop position. Below example illustrates the radial-gradient() function in CSS:Program 1: html <!DOCTYPE html><html> <head> <title>CSS Gradients</title> <style> #main { height: 250px; width: 600px; background-color: white; background-image: radial-gradient(#090, #fff, #2a4f32); } .gfg { text-align:center; font-size:40px; font-weight:bold; padding-top:80px; } .geeks { font-size:17px; text-align:center; } </style> </head> <body> <div id="main"> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> </div> </body></html> Output: Program 2: html <!DOCTYPE html><html> <head> <title>CSS Gradients</title> <style> #main { height: 400px; width: 600px; background-color: white; background-image: radial-gradient(circle, green, white, blue); } .gfg { text-align:center; font-size:40px; font-weight:bold; padding-top:155px; } .geeks { font-size:17px; text-align:center; } </style> </head> <body> <div id="main"> <div class = "gfg">GeeksforGeeks</div> <div class = "geeks">A computer science portal for geeks</div> </div> </body></html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ysachin2314 CSS-Functions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 24155, "s": 24127, "text": "\n30 Jul, 2021" }, { "code": null, "e": 24523, "s": 24155, "text": "The radial-gradient() function is an inbuilt function in CSS which is used to set a radial gradient as the background image. It starts at a single point and emanates outward. By default, the first color starts at the center position of the element and then fade to the end color towards the edge of the element. Fade happens at an equal rate until specified.Syntax: " }, { "code": null, "e": 24614, "s": 24523, "text": "background-image: radial-gradient( shape size at position, start-color, ..., last-color );" }, { "code": null, "e": 24690, "s": 24614, "text": "Parameters: This function accepts many parameters which are listed below: " }, { "code": null, "e": 24834, "s": 24690, "text": "shape: This parameter is used to define the shape of gradient. It has two possible value circle or ellipse. The default shape value is ellipse." }, { "code": null, "e": 24991, "s": 24834, "text": "size: This parameter is used to define the size of gradient. The possible value are: farthest-corner (default), closest-side, closest-corner, farthest-side." }, { "code": null, "e": 25089, "s": 24991, "text": "position: This parameter is used to define the position of gradient. The default value is center." }, { "code": null, "e": 25206, "s": 25089, "text": "start-color, ..., last-color: This parameter is used to hold the color value followed by its optional stop position." }, { "code": null, "e": 25283, "s": 25206, "text": "Below example illustrates the radial-gradient() function in CSS:Program 1: " }, { "code": null, "e": 25288, "s": 25283, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS Gradients</title> <style> #main { height: 250px; width: 600px; background-color: white; background-image: radial-gradient(#090, #fff, #2a4f32); } .gfg { text-align:center; font-size:40px; font-weight:bold; padding-top:80px; } .geeks { font-size:17px; text-align:center; } </style> </head> <body> <div id=\"main\"> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> </div> </body></html> ", "e": 26068, "s": 25288, "text": null }, { "code": null, "e": 26078, "s": 26068, "text": "Output: " }, { "code": null, "e": 26091, "s": 26078, "text": "Program 2: " }, { "code": null, "e": 26096, "s": 26091, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>CSS Gradients</title> <style> #main { height: 400px; width: 600px; background-color: white; background-image: radial-gradient(circle, green, white, blue); } .gfg { text-align:center; font-size:40px; font-weight:bold; padding-top:155px; } .geeks { font-size:17px; text-align:center; } </style> </head> <body> <div id=\"main\"> <div class = \"gfg\">GeeksforGeeks</div> <div class = \"geeks\">A computer science portal for geeks</div> </div> </body></html> ", "e": 26884, "s": 26096, "text": null }, { "code": null, "e": 26894, "s": 26884, "text": "Output: " }, { "code": null, "e": 26913, "s": 26894, "text": "Supported Browser:" }, { "code": null, "e": 26927, "s": 26913, "text": "Google Chrome" }, { "code": null, "e": 26945, "s": 26927, "text": "Internet Explorer" }, { "code": null, "e": 26953, "s": 26945, "text": "Firefox" }, { "code": null, "e": 26959, "s": 26953, "text": "Opera" }, { "code": null, "e": 26966, "s": 26959, "text": "Safari" }, { "code": null, "e": 27103, "s": 26966, "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": 27115, "s": 27103, "text": "ysachin2314" }, { "code": null, "e": 27129, "s": 27115, "text": "CSS-Functions" }, { "code": null, "e": 27133, "s": 27129, "text": "CSS" }, { "code": null, "e": 27138, "s": 27133, "text": "HTML" }, { "code": null, "e": 27155, "s": 27138, "text": "Web Technologies" }, { "code": null, "e": 27160, "s": 27155, "text": "HTML" }, { "code": null, "e": 27258, "s": 27160, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27308, "s": 27258, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27370, "s": 27308, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27418, "s": 27370, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27476, "s": 27418, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27531, "s": 27476, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 27581, "s": 27531, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27643, "s": 27581, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27691, "s": 27643, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 27751, "s": 27691, "text": "How to set the default value for an HTML <select> element ?" } ]
Vector removeIf() method in Java - GeeksforGeeks
18 Sep, 2018 The removeIf() method of Vector removes all of those elements from Vector which satisfies the condition passed as a parameter to this method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition checking function, which checks the given input for a given condition and returns a boolean result for the same indicating whether the condition was met or not. Syntax: public boolean removeIf(Predicate<? super E> filter) Parameter: This method takes a parameter filter which represents a predicate which returns true for elements to be removed. Returns: This method returns True if predicate returns true and some elements were removed. Exception: This method throws NullPointerException if the specified filter is null. Below programs illustrate removeIf() method of Vector: Example 1: To demonstrate removeIf() method on vector which contains a set of Numbers and only the numbers which are divisible by 2 will be removed. // Java Program Demonstrate removeIf()// method of Vector import java.util.*; public class GFG { public static void main(String[] args) { // create an Vector which going to // contains a list of Numbers Vector<Integer> Numbers = new Vector<Integer>(); // Add Number to list Numbers.add(22); Numbers.add(33); Numbers.add(55); Numbers.add(62); // apply removeIf() method // to remove numbers divisible by 2 Numbers.removeIf(n -> (n % 2 == 0)); System.out.println("All Numbers not divisible by 2 are:"); // print list for (int i : Numbers) { System.out.println(i); } }} All Numbers not divisible by 2 are: 33 55 Example 2: To demonstrate removeIf() method on Vector which contains set of Students Names and to remove all 4 char long name. // Java Program Demonstrate removeIf()// method of Vector import java.util.*; public class GFG { public static void main(String[] args) { // create a Vector // containing a list of string values Vector<String> students = new Vector<String>(); // Add Strings to list // each string represents student name students.add("Rama"); students.add("Mohan"); students.add("Sohan"); students.add("Rabi"); students.add("Shabbir"); // apply removeIf() method // to remove names contains 4 chars students.removeIf(n -> (n.length() == 4)); System.out.println("Students name do not contain 4 char are"); // print list for (String str : students) { System.out.println(str); } }} Students name do not contain 4 char are Mohan Sohan Shabbir Example 3: To demonstrate NullpointerException in removeIf() method on Vector. // Java Program Demonstrate removeIf()// method of Vector import java.util.*; public class GFG { public static void main(String[] args) { // create a Vector // containing a list of string values Vector<String> students = new Vector<String>(); // Add Strings to list // each string represents student name students.add("Rama"); students.add("Mohan"); students.add("Sohan"); students.add("Rabi"); students.add("Shabbir"); try { // apply removeIf() method with null filter students.removeIf(null); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html#removeIf-java.util.function.Predicate- java-basics Java-Functions Java-Vector Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples Reverse a string in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java
[ { "code": null, "e": 25519, "s": 25491, "text": "\n18 Sep, 2018" }, { "code": null, "e": 25731, "s": 25519, "text": "The removeIf() method of Vector removes all of those elements from Vector which satisfies the condition passed as a parameter to this method. This method returns true if some element are removed from the Vector." }, { "code": null, "e": 25992, "s": 25731, "text": "Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition checking function, which checks the given input for a given condition and returns a boolean result for the same indicating whether the condition was met or not." }, { "code": null, "e": 26000, "s": 25992, "text": "Syntax:" }, { "code": null, "e": 26053, "s": 26000, "text": "public boolean removeIf(Predicate<? super E> filter)" }, { "code": null, "e": 26177, "s": 26053, "text": "Parameter: This method takes a parameter filter which represents a predicate which returns true for elements to be removed." }, { "code": null, "e": 26269, "s": 26177, "text": "Returns: This method returns True if predicate returns true and some elements were removed." }, { "code": null, "e": 26353, "s": 26269, "text": "Exception: This method throws NullPointerException if the specified filter is null." }, { "code": null, "e": 26408, "s": 26353, "text": "Below programs illustrate removeIf() method of Vector:" }, { "code": null, "e": 26557, "s": 26408, "text": "Example 1: To demonstrate removeIf() method on vector which contains a set of Numbers and only the numbers which are divisible by 2 will be removed." }, { "code": "// Java Program Demonstrate removeIf()// method of Vector import java.util.*; public class GFG { public static void main(String[] args) { // create an Vector which going to // contains a list of Numbers Vector<Integer> Numbers = new Vector<Integer>(); // Add Number to list Numbers.add(22); Numbers.add(33); Numbers.add(55); Numbers.add(62); // apply removeIf() method // to remove numbers divisible by 2 Numbers.removeIf(n -> (n % 2 == 0)); System.out.println(\"All Numbers not divisible by 2 are:\"); // print list for (int i : Numbers) { System.out.println(i); } }}", "e": 27261, "s": 26557, "text": null }, { "code": null, "e": 27304, "s": 27261, "text": "All Numbers not divisible by 2 are:\n33\n55\n" }, { "code": null, "e": 27431, "s": 27304, "text": "Example 2: To demonstrate removeIf() method on Vector which contains set of Students Names and to remove all 4 char long name." }, { "code": "// Java Program Demonstrate removeIf()// method of Vector import java.util.*; public class GFG { public static void main(String[] args) { // create a Vector // containing a list of string values Vector<String> students = new Vector<String>(); // Add Strings to list // each string represents student name students.add(\"Rama\"); students.add(\"Mohan\"); students.add(\"Sohan\"); students.add(\"Rabi\"); students.add(\"Shabbir\"); // apply removeIf() method // to remove names contains 4 chars students.removeIf(n -> (n.length() == 4)); System.out.println(\"Students name do not contain 4 char are\"); // print list for (String str : students) { System.out.println(str); } }}", "e": 28245, "s": 27431, "text": null }, { "code": null, "e": 28306, "s": 28245, "text": "Students name do not contain 4 char are\nMohan\nSohan\nShabbir\n" }, { "code": null, "e": 28385, "s": 28306, "text": "Example 3: To demonstrate NullpointerException in removeIf() method on Vector." }, { "code": "// Java Program Demonstrate removeIf()// method of Vector import java.util.*; public class GFG { public static void main(String[] args) { // create a Vector // containing a list of string values Vector<String> students = new Vector<String>(); // Add Strings to list // each string represents student name students.add(\"Rama\"); students.add(\"Mohan\"); students.add(\"Sohan\"); students.add(\"Rabi\"); students.add(\"Shabbir\"); try { // apply removeIf() method with null filter students.removeIf(null); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 29096, "s": 28385, "text": null }, { "code": null, "e": 29139, "s": 29096, "text": "Exception: java.lang.NullPointerException\n" }, { "code": null, "e": 29253, "s": 29139, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html#removeIf-java.util.function.Predicate-" }, { "code": null, "e": 29265, "s": 29253, "text": "java-basics" }, { "code": null, "e": 29280, "s": 29265, "text": "Java-Functions" }, { "code": null, "e": 29292, "s": 29280, "text": "Java-Vector" }, { "code": null, "e": 29297, "s": 29292, "text": "Java" }, { "code": null, "e": 29302, "s": 29297, "text": "Java" }, { "code": null, "e": 29400, "s": 29302, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29415, "s": 29400, "text": "Arrays in Java" }, { "code": null, "e": 29459, "s": 29415, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29481, "s": 29459, "text": "For-each loop in Java" }, { "code": null, "e": 29532, "s": 29481, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29568, "s": 29532, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 29593, "s": 29568, "text": "Reverse a string in Java" }, { "code": null, "e": 29623, "s": 29593, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29642, "s": 29623, "text": "Interfaces in Java" }, { "code": null, "e": 29657, "s": 29642, "text": "Stream In Java" } ]
Python - Check for Key in Dictionary Value list - GeeksforGeeks
01 Mar, 2020 Sometimes, while working with data, we might have a problem we receive a dictionary whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let’s discuss certain ways in which this task can be performed. Method #1 : Using any()This is simple and most recommended way in which this task can be performed. In this, we just check for the key inside the values by iteration. # Python3 code to demonstrate working of # Check for Key in Dictionary Value list# Using any() # initializing dictionary test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing keykey = "GATE" # Check for Key in Dictionary Value list# Using any()res = any(key in ele for ele in test_dict['Gfg']) # printing result print("Is key present in nested dictionary list ? : " + str(res)) The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3} Is key present in nested dictionary list ? : True Method #2 : Using list comprehension + in operatorThe combination of above functionalities can be used to perform this task. In this, we iterate through the list using comprehension and perform key flattening and store keys. Then we check for desired key using in operator. # Python3 code to demonstrate working of # Check for Key in Dictionary Value list# Using list comprehension + in operator # initializing dictionary test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3} # printing original dictionary print("The original dictionary is : " + str(test_dict)) # initializing keykey = "GATE" # Check for Key in Dictionary Value list# Using list comprehension + in operatorres = key in [sub for ele in test_dict['Gfg'] for sub in ele.keys()] # printing result print("Is key present in nested dictionary list ? : " + str(res)) The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3} Is key present in nested dictionary list ? : True Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25625, "s": 25597, "text": "\n01 Mar, 2020" }, { "code": null, "e": 25894, "s": 25625, "text": "Sometimes, while working with data, we might have a problem we receive a dictionary whole key has list of dictionaries as value. In this scenario, we might need to find if a particular key exists in that. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26061, "s": 25894, "text": "Method #1 : Using any()This is simple and most recommended way in which this task can be performed. In this, we just check for the key inside the values by iteration." }, { "code": "# Python3 code to demonstrate working of # Check for Key in Dictionary Value list# Using any() # initializing dictionary test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3} # printing original dictionary print(\"The original dictionary is : \" + str(test_dict)) # initializing keykey = \"GATE\" # Check for Key in Dictionary Value list# Using any()res = any(key in ele for ele in test_dict['Gfg']) # printing result print(\"Is key present in nested dictionary list ? : \" + str(res)) ", "e": 26577, "s": 26061, "text": null }, { "code": null, "e": 26711, "s": 26577, "text": "The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}\nIs key present in nested dictionary list ? : True\n" }, { "code": null, "e": 26987, "s": 26713, "text": "Method #2 : Using list comprehension + in operatorThe combination of above functionalities can be used to perform this task. In this, we iterate through the list using comprehension and perform key flattening and store keys. Then we check for desired key using in operator." }, { "code": "# Python3 code to demonstrate working of # Check for Key in Dictionary Value list# Using list comprehension + in operator # initializing dictionary test_dict = {'Gfg' : [{'CS' : 5}, {'GATE' : 6}], 'for' : 2, 'CS' : 3} # printing original dictionary print(\"The original dictionary is : \" + str(test_dict)) # initializing keykey = \"GATE\" # Check for Key in Dictionary Value list# Using list comprehension + in operatorres = key in [sub for ele in test_dict['Gfg'] for sub in ele.keys()] # printing result print(\"Is key present in nested dictionary list ? : \" + str(res)) ", "e": 27576, "s": 26987, "text": null }, { "code": null, "e": 27710, "s": 27576, "text": "The original dictionary is : {'Gfg': [{'CS': 5}, {'GATE': 6}], 'for': 2, 'CS': 3}\nIs key present in nested dictionary list ? : True\n" }, { "code": null, "e": 27737, "s": 27710, "text": "Python dictionary-programs" }, { "code": null, "e": 27744, "s": 27737, "text": "Python" }, { "code": null, "e": 27760, "s": 27744, "text": "Python Programs" }, { "code": null, "e": 27858, "s": 27760, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27876, "s": 27858, "text": "Python Dictionary" }, { "code": null, "e": 27911, "s": 27876, "text": "Read a file line by line in Python" }, { "code": null, "e": 27943, "s": 27911, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27965, "s": 27943, "text": "Enumerate() in Python" }, { "code": null, "e": 28007, "s": 27965, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28050, "s": 28007, "text": "Python program to convert a list to string" }, { "code": null, "e": 28072, "s": 28050, "text": "Defaultdict in Python" }, { "code": null, "e": 28118, "s": 28072, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28156, "s": 28118, "text": "Python | Convert a list to dictionary" } ]
Operating Systems | CPU Scheduling | Question 1 - GeeksforGeeks
03 Oct, 2019 Consider three processes (process id 0, 1, 2 respectively) with compute time bursts 2, 4 and 8 time units. All processes arrive at time zero. Consider the longest remaining time first (LRTF) scheduling algorithm. In LRTF ties are broken by giving priority to the process with the lowest process id. The average turn around time is:(A) 13 units(B) 14 units(C) 15 units(D) 16 unitsAnswer: (A)Explanation: Let the processes be p0, p1 and p2. These processes will be executed in following order. p2 p1 p2 p1 p2 p0 p1 p2 p0 p1 p2 0 4 5 6 7 8 9 10 11 12 13 14 Turn around time of a process is total time between submission of the process and its completion.Turn around time of p0 = 12 (12-0)Turn around time of p1 = 13 (13-0)Turn around time of p2 = 14 (14-0) Average turn around time is (12+13+14)/3 = 13.Quiz of this Question cpu-scheduling Operating Systems-CPU Scheduling Operating Systems Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Memory Management in Operating System File Allocation Methods Logical and Physical Address in Operating System Difference between Internal and External fragmentation File Access Methods in Operating System Memory Hierarchy Design and its Characteristics File Systems in Operating System Process Table and Process Control Block (PCB) States of a Process in Operating Systems Introduction of Process Management
[ { "code": null, "e": 25761, "s": 25733, "text": "\n03 Oct, 2019" }, { "code": null, "e": 26253, "s": 25761, "text": "Consider three processes (process id 0, 1, 2 respectively) with compute time bursts 2, 4 and 8 time units. All processes arrive at time zero. Consider the longest remaining time first (LRTF) scheduling algorithm. In LRTF ties are broken by giving priority to the process with the lowest process id. The average turn around time is:(A) 13 units(B) 14 units(C) 15 units(D) 16 unitsAnswer: (A)Explanation: Let the processes be p0, p1 and p2. These processes will be executed in following order." }, { "code": null, "e": 26356, "s": 26253, "text": " p2 p1 p2 p1 p2 p0 p1 p2 p0 p1 p2\n0 4 5 6 7 8 9 10 11 12 13 14 \n" }, { "code": null, "e": 26556, "s": 26356, "text": "Turn around time of a process is total time between submission of the process and its completion.Turn around time of p0 = 12 (12-0)Turn around time of p1 = 13 (13-0)Turn around time of p2 = 14 (14-0)" }, { "code": null, "e": 26624, "s": 26556, "text": "Average turn around time is (12+13+14)/3 = 13.Quiz of this Question" }, { "code": null, "e": 26639, "s": 26624, "text": "cpu-scheduling" }, { "code": null, "e": 26672, "s": 26639, "text": "Operating Systems-CPU Scheduling" }, { "code": null, "e": 26690, "s": 26672, "text": "Operating Systems" }, { "code": null, "e": 26708, "s": 26690, "text": "Operating Systems" }, { "code": null, "e": 26806, "s": 26708, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26844, "s": 26806, "text": "Memory Management in Operating System" }, { "code": null, "e": 26868, "s": 26844, "text": "File Allocation Methods" }, { "code": null, "e": 26917, "s": 26868, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 26972, "s": 26917, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27012, "s": 26972, "text": "File Access Methods in Operating System" }, { "code": null, "e": 27060, "s": 27012, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27093, "s": 27060, "text": "File Systems in Operating System" }, { "code": null, "e": 27139, "s": 27093, "text": "Process Table and Process Control Block (PCB)" }, { "code": null, "e": 27180, "s": 27139, "text": "States of a Process in Operating Systems" } ]
AngularJS | ng-switch Directive - GeeksforGeeks
28 Mar, 2019 The ng-switch Directive in AngularJS is used to specify the condition to show/hide the child elements in HTML DOM. The HTML element will be displayed only if the expression inside ng-switch directive returns true otherwise it will be hidden. It is supported by all HTML elements. Syntax: <element ng-switch="expression"> <element ng-switch-when="value"> Contents... </element> <element ng-switch-when="value"> Contents... </element> <element ng-switch-default> Contents... </element> </element> Example 1: This example uses ng-switch Directive to switch the element. <!DOCTYPE html><html> <head> <title>ng-switch Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script></head> <body ng-app="" style=""> <h1 style="color:green;">GeeksforGeeks</h1> <h2>ng-switch Directive</h2> <div> <form> <label> <input type="radio" value="search" ng-model="switch.Data"> Searching Algorithms </label> <label> <input type="radio" value="sort" ng-model="switch.Data"> Sorting Algorithms </label> </form> <div ng-switch="switch.Data" id="wrapper"> <div ng-switch-when="search"> <h2> Searching Algorithms</h2> <ul> <li>Binary Search <li>Linear Search </ul> </div> <div ng-switch-when="sort"> <h2>Sorting Algorithms</h2> <ul> <li>Merge Sort <li>Quick Sort </ul> </div> </div> </div></body> </html> Output: Before Click on the radio button: After Clicking the Searching radio button: After Clicking the Sorting radio button: Example 2: This example uses ng-switch Directive to display the entered number. <!DOCTYPE html><html> <head> <title>ng-switch Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"></head> <body ng-app="" style="text-align:center;"> <h1 style="color:green;">GeeksforGeeks</h1> <h2 style="">ng-switch Directive</h2> <div> <div class="col-md-3"> Type Number(1-2): <input ng-model="number" type="number" /> </div><br> <div ng-switch="number" class="col-md-3"> <div ng-switch-when="1" class="btn btn-danger"> You entered {{number}} </div> <div ng-switch-when="2" class="btn btn-primary"> You entered {{number}} </div> <div ng-switch-default class="well"> This is the default section. </div> </div> </div></body> </html> Output: Before Input the text: After Input the text: AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26070, "s": 26042, "text": "\n28 Mar, 2019" }, { "code": null, "e": 26350, "s": 26070, "text": "The ng-switch Directive in AngularJS is used to specify the condition to show/hide the child elements in HTML DOM. The HTML element will be displayed only if the expression inside ng-switch directive returns true otherwise it will be hidden. It is supported by all HTML elements." }, { "code": null, "e": 26358, "s": 26350, "text": "Syntax:" }, { "code": null, "e": 26572, "s": 26358, "text": "<element ng-switch=\"expression\">\n <element ng-switch-when=\"value\"> Contents... </element>\n <element ng-switch-when=\"value\"> Contents... </element>\n <element ng-switch-default> Contents... </element>\n</element>\n" }, { "code": null, "e": 26644, "s": 26572, "text": "Example 1: This example uses ng-switch Directive to switch the element." }, { "code": "<!DOCTYPE html><html> <head> <title>ng-switch Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script></head> <body ng-app=\"\" style=\"\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2>ng-switch Directive</h2> <div> <form> <label> <input type=\"radio\" value=\"search\" ng-model=\"switch.Data\"> Searching Algorithms </label> <label> <input type=\"radio\" value=\"sort\" ng-model=\"switch.Data\"> Sorting Algorithms </label> </form> <div ng-switch=\"switch.Data\" id=\"wrapper\"> <div ng-switch-when=\"search\"> <h2> Searching Algorithms</h2> <ul> <li>Binary Search <li>Linear Search </ul> </div> <div ng-switch-when=\"sort\"> <h2>Sorting Algorithms</h2> <ul> <li>Merge Sort <li>Quick Sort </ul> </div> </div> </div></body> </html> ", "e": 27837, "s": 26644, "text": null }, { "code": null, "e": 27845, "s": 27837, "text": "Output:" }, { "code": null, "e": 27879, "s": 27845, "text": "Before Click on the radio button:" }, { "code": null, "e": 27922, "s": 27879, "text": "After Clicking the Searching radio button:" }, { "code": null, "e": 27963, "s": 27922, "text": "After Clicking the Sorting radio button:" }, { "code": null, "e": 28043, "s": 27963, "text": "Example 2: This example uses ng-switch Directive to display the entered number." }, { "code": "<!DOCTYPE html><html> <head> <title>ng-switch Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css\"></head> <body ng-app=\"\" style=\"text-align:center;\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2 style=\"\">ng-switch Directive</h2> <div> <div class=\"col-md-3\"> Type Number(1-2): <input ng-model=\"number\" type=\"number\" /> </div><br> <div ng-switch=\"number\" class=\"col-md-3\"> <div ng-switch-when=\"1\" class=\"btn btn-danger\"> You entered {{number}} </div> <div ng-switch-when=\"2\" class=\"btn btn-primary\"> You entered {{number}} </div> <div ng-switch-default class=\"well\"> This is the default section. </div> </div> </div></body> </html> ", "e": 29103, "s": 28043, "text": null }, { "code": null, "e": 29111, "s": 29103, "text": "Output:" }, { "code": null, "e": 29134, "s": 29111, "text": "Before Input the text:" }, { "code": null, "e": 29156, "s": 29134, "text": "After Input the text:" }, { "code": null, "e": 29177, "s": 29156, "text": "AngularJS-Directives" }, { "code": null, "e": 29187, "s": 29177, "text": "AngularJS" }, { "code": null, "e": 29204, "s": 29187, "text": "Web Technologies" }, { "code": null, "e": 29302, "s": 29204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29337, "s": 29302, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 29368, "s": 29337, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 29403, "s": 29368, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 29445, "s": 29403, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 29490, "s": 29445, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 29530, "s": 29490, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29563, "s": 29530, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29608, "s": 29563, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29651, "s": 29608, "text": "How to fetch data from an API in ReactJS ?" } ]
Perfect power (1, 4, 8, 9, 16, 25, 27, ...) - GeeksforGeeks
07 Jul, 2021 A perfect power is a number that can be expressed as power of another positive integer. Given a number n, find count of numbers from 1 to n that are of type xy where x >= 1 and y > 1Examples : Input : n = 10 Output : 4 1 4 8 and 9 are the numbers that are of form x ^ y where x > 0 and y > 1 Input : n = 50 Output : 10 A simple solution is to go through all powers of numbers from i = 2 to square root of n. C++ Java Python3 C# PHP Javascript // CPP program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1#include <bits/stdc++.h>using namespace std; // For our convenience#define ll long long // Function that keeps all the odd power// numbers upto nint powerNumbers(int n){ // v is going to store all power numbers vector<int> v; v.push_back(1); // Traverse through all base numbers and // compute all their powers smaller than // or equal to n. for (ll i = 2; i * i <= n; i++) { ll j = i * i; v.push_back(j); while (j * i <= n) { v.push_back(j * i); j = j * i; } } // Remove all duplicates sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); return v.size();} int main(){ cout << powerNumbers(50); return 0;} // Java program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1import java.io.*;import java.util.*; public class GFG { // Function that keeps all the odd power // numbers upto n static int powerNumbers(int n) { // v is going to store all unique // power numbers HashSet<Integer> v = new HashSet<Integer>(); v.add(1); // Traverse through all base numbers // and compute all their powers // smaller than or equal to n. for (int i = 2; i * i <= n; i++) { int j = i * i; v.add(j); while (j * i <= n) { v.add(j * i); j = j * i; } } return v.size(); } // Driver code public static void main(String args[]) { System.out.print(powerNumbers(50)); }} // This code is contributed by Manish Shaw// (manishshaw1) # Python3 program to count number# of numbers from 1 to n are of# type x^y where x>0 and y>1 # Function that keeps all the odd# power numbers upto ndef powerNumbers(n): # v is going to store all # unique power numbers v = set(); v.add(1); # Traverse through all base # numbers and compute all # their powers smaller than # or equal to n. for i in range(2, n+1): if(i * i <= n): j = i * i; v.add(j); while (j * i <= n): v.add(j * i); j = j * i; return len(v); print (powerNumbers(50));# This code is contributed by# Manish Shaw (manishshaw1) // C# program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1using System;using System.Collections.Generic;using System.Linq; class GFG { // Function that keeps all the odd power // numbers upto n static int powerNumbers(int n) { // v is going to store all unique // power numbers HashSet<int> v = new HashSet<int>(); v.Add(1); // Traverse through all base numbers // and compute all their powers // smaller than or equal to n. for (int i = 2; i * i <= n; i++) { int j = i * i; v.Add(j); while (j * i <= n) { v.Add(j * i); j = j * i; } } return v.Count; } // Driver code public static void Main() { Console.WriteLine(powerNumbers(50)); }} // This code is contributed by Manish Shaw// (manishshaw1) <?php// PHP program to count number of// numbers from 1 to n are of type// x^y where x>0 and y>1 // Function that keeps all the// odd power numbers upto nfunction powerNumbers($n){ // v is going to store // all power numbers $v = array(); array_push($v, 1); // Traverse through all base // numbers and compute all // their powers smaller than // or equal to n. for ($i = 2; $i * $i <= $n; $i++) { $j = $i * $i; array_push($v, $j); while ($j * $i <= $n) { array_push($v, $j * $i); $j = $j * $i; } } // Remove all duplicates sort($v); $v = array_unique($v); return count($v);} // Driver Codeecho (powerNumbers(50)); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // JavaScript program to count number of numbers from // 1 to n are of type x^y where x>0 and y>1 // Function that keeps all the odd power // numbers upto n function powerNumbers(n) { // v is going to store all unique // power numbers let v = new Set(); v.add(1); // Traverse through all base numbers // and compute all their powers // smaller than or equal to n. for (let i = 2; i * i <= n; i++) { let j = i * i; v.add(j); while (j * i <= n) { v.add(j * i); j = j * i; } } return v.size; } document.write(powerNumbers(50)); </script> 10 Efficient Solution We divide output set into subsets. Even Powers: Simply we need to square root n. The count of even powers smaller than n is square root of n. For example even powers smaller than 25 are (1, 4, 9, 16 and 25). Odd Powers: We modify above function to consider only odd powers. C++ Java Python3 C# PHP Javascript // C++ program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1#include <bits/stdc++.h>using namespace std; // For our convenience#define ll long long // Function that keeps all the odd power// numbers upto nint powerNumbers(int n){ vector<int> v; for (ll i = 2; i * i * i <= n; i++) { ll j = i * i; while (j * i <= n) { j *= i; // We need exclude perfect // squares. ll s = sqrt(j); if (s * s != j) v.push_back(j); } } // sort the vector sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); // Return sum of odd and even powers. return v.size() + (ll)sqrt(n);} int main(){ cout << powerNumbers(50); return 0;} // Java program to count number// of numbers from 1 to n are// of type x^y where x>0 and y>1import java.io.*;import java.util.*; class GFG{ // Function that keeps all // the odd power numbers upto n static long powerNumbers(int n) { HashSet<Long> v = new HashSet<Long>(); for (long i = 2; i * i * i <= n; i++) { long j = i * i; while (j * i <= n) { j *= i; // We need exclude // perfect squares. long s = (long)Math.sqrt(j); if (s * s != j) v.add(j); } } // sort the vector // v.Sort(); // v.erase(unique(v.begin(), // v.end()), v.end()); // Return sum of odd // and even powers. return v.size() + (long)Math.sqrt(n); } // Driver Code public static void main(String args[]) { System.out.print(powerNumbers(50)); }} // This code is contributed by// Manish Shaw(manishshaw1) # Python3 program to count number of# numbers from 1 to n are of type x^y# where x>0 and y>1import math # Function that keeps all the odd power# numbers upto ndef powerNumbers( n): v = [] for i in range(2, int(math.pow(n, 1.0 / 3.0)) + 1) : j = i * i while (j * i <= n) : j = j * i # We need exclude perfect # squares. s = int(math.sqrt(j)) if (s * s != j): v.append(j) # sort the vector v.sort() v = list(dict.fromkeys(v)) # Return sum of odd and even powers. return len(v) + int(math.sqrt(n)) # Driver Codeif __name__=='__main__': print (powerNumbers(50)) # This code is contributed by Arnab Kundu // C# program to count number// of numbers from 1 to n are// of type x^y where x>0 and y>1using System;using System.Collections.Generic; class GFG{ // Function that keeps all // the odd power numbers upto n static long powerNumbers(int n) { HashSet<long> v = new HashSet<long>(); for (long i = 2; i * i * i <= n; i++) { long j = i * i; while (j * i <= n) { j *= i; // We need exclude // perfect squares. long s = (long)Math.Sqrt(j); if (s * s != j) v.Add(j); } } // sort the vector //v.Sort(); //v.erase(unique(v.begin(), // v.end()), v.end()); // Return sum of odd // and even powers. return v.Count + (long)Math.Sqrt(n); } // Driver Code static void Main() { Console.Write(powerNumbers(50)); }} // This code is contributed by// Manish Shaw(manishshaw1) <?php// PHP program to count number// of numbers from 1 to n are// of type x^y where x>0 and y>1 // Function that keeps all the// odd power numbers upto nfunction powerNumbers($n){ $v = array(); for ($i = 2; $i * $i * $i <= $n; $i++) { $j = $i * $i; while ($j * $i <= $n) { $j *= $i; // We need exclude perfect // squares. $s = sqrt($j); if ($s * $s != $j) array_push($v, $j); } } // sort the vector sort($v); $uni = array_unique($v); for ($i = 0; $i < count($uni); $i++) { $key = array_search($uni[$i], $v); unset($v[$key]); } // Return sum of odd // and even powers. return count($v) + 3 + intval(sqrt($n));} // Driver Codeecho (powerNumbers(50)); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // Javascript program to count number // of numbers from 1 to n are // of type x^y where x>0 and y>1 // Function that keeps all // the odd power numbers upto n function powerNumbers(n) { let v = new Set(); for (let i = 2; i * i * i <= n; i++) { let j = i * i; while (j * i <= n) { j *= i; // We need exclude // perfect squares. let s = parseInt(Math.sqrt(j), 10); if (s * s != j) v.add(j); } } // sort the vector // v.Sort(); // v.erase(unique(v.begin(), // v.end()), v.end()); // Return sum of odd // and even powers. return v.size + parseInt(Math.sqrt(n), 10); } document.write(powerNumbers(50)); // This code is contributed by vaibhavrabadiya3.</script> 10 manishshaw1 andrew1234 vaibhavrabadiya117 vaibhavrabadiya3 cpp-vector number-theory Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Sieve of Eratosthenes Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++ Program for factorial of a number
[ { "code": null, "e": 26487, "s": 26459, "text": "\n07 Jul, 2021" }, { "code": null, "e": 26682, "s": 26487, "text": "A perfect power is a number that can be expressed as power of another positive integer. Given a number n, find count of numbers from 1 to n that are of type xy where x >= 1 and y > 1Examples : " }, { "code": null, "e": 26809, "s": 26682, "text": "Input : n = 10\nOutput : 4\n1 4 8 and 9 are the numbers that are\nof form x ^ y where x > 0 and y > 1\n\nInput : n = 50\nOutput : 10" }, { "code": null, "e": 26902, "s": 26811, "text": "A simple solution is to go through all powers of numbers from i = 2 to square root of n. " }, { "code": null, "e": 26906, "s": 26902, "text": "C++" }, { "code": null, "e": 26911, "s": 26906, "text": "Java" }, { "code": null, "e": 26919, "s": 26911, "text": "Python3" }, { "code": null, "e": 26922, "s": 26919, "text": "C#" }, { "code": null, "e": 26926, "s": 26922, "text": "PHP" }, { "code": null, "e": 26937, "s": 26926, "text": "Javascript" }, { "code": "// CPP program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1#include <bits/stdc++.h>using namespace std; // For our convenience#define ll long long // Function that keeps all the odd power// numbers upto nint powerNumbers(int n){ // v is going to store all power numbers vector<int> v; v.push_back(1); // Traverse through all base numbers and // compute all their powers smaller than // or equal to n. for (ll i = 2; i * i <= n; i++) { ll j = i * i; v.push_back(j); while (j * i <= n) { v.push_back(j * i); j = j * i; } } // Remove all duplicates sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); return v.size();} int main(){ cout << powerNumbers(50); return 0;}", "e": 27747, "s": 26937, "text": null }, { "code": "// Java program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1import java.io.*;import java.util.*; public class GFG { // Function that keeps all the odd power // numbers upto n static int powerNumbers(int n) { // v is going to store all unique // power numbers HashSet<Integer> v = new HashSet<Integer>(); v.add(1); // Traverse through all base numbers // and compute all their powers // smaller than or equal to n. for (int i = 2; i * i <= n; i++) { int j = i * i; v.add(j); while (j * i <= n) { v.add(j * i); j = j * i; } } return v.size(); } // Driver code public static void main(String args[]) { System.out.print(powerNumbers(50)); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 28666, "s": 27747, "text": null }, { "code": "# Python3 program to count number# of numbers from 1 to n are of# type x^y where x>0 and y>1 # Function that keeps all the odd# power numbers upto ndef powerNumbers(n): # v is going to store all # unique power numbers v = set(); v.add(1); # Traverse through all base # numbers and compute all # their powers smaller than # or equal to n. for i in range(2, n+1): if(i * i <= n): j = i * i; v.add(j); while (j * i <= n): v.add(j * i); j = j * i; return len(v); print (powerNumbers(50));# This code is contributed by# Manish Shaw (manishshaw1)", "e": 29318, "s": 28666, "text": null }, { "code": "// C# program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1using System;using System.Collections.Generic;using System.Linq; class GFG { // Function that keeps all the odd power // numbers upto n static int powerNumbers(int n) { // v is going to store all unique // power numbers HashSet<int> v = new HashSet<int>(); v.Add(1); // Traverse through all base numbers // and compute all their powers // smaller than or equal to n. for (int i = 2; i * i <= n; i++) { int j = i * i; v.Add(j); while (j * i <= n) { v.Add(j * i); j = j * i; } } return v.Count; } // Driver code public static void Main() { Console.WriteLine(powerNumbers(50)); }} // This code is contributed by Manish Shaw// (manishshaw1)", "e": 30236, "s": 29318, "text": null }, { "code": "<?php// PHP program to count number of// numbers from 1 to n are of type// x^y where x>0 and y>1 // Function that keeps all the// odd power numbers upto nfunction powerNumbers($n){ // v is going to store // all power numbers $v = array(); array_push($v, 1); // Traverse through all base // numbers and compute all // their powers smaller than // or equal to n. for ($i = 2; $i * $i <= $n; $i++) { $j = $i * $i; array_push($v, $j); while ($j * $i <= $n) { array_push($v, $j * $i); $j = $j * $i; } } // Remove all duplicates sort($v); $v = array_unique($v); return count($v);} // Driver Codeecho (powerNumbers(50)); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 31015, "s": 30236, "text": null }, { "code": "<script> // JavaScript program to count number of numbers from // 1 to n are of type x^y where x>0 and y>1 // Function that keeps all the odd power // numbers upto n function powerNumbers(n) { // v is going to store all unique // power numbers let v = new Set(); v.add(1); // Traverse through all base numbers // and compute all their powers // smaller than or equal to n. for (let i = 2; i * i <= n; i++) { let j = i * i; v.add(j); while (j * i <= n) { v.add(j * i); j = j * i; } } return v.size; } document.write(powerNumbers(50)); </script>", "e": 31746, "s": 31015, "text": null }, { "code": null, "e": 31749, "s": 31746, "text": "10" }, { "code": null, "e": 31770, "s": 31751, "text": "Efficient Solution" }, { "code": null, "e": 32046, "s": 31770, "text": "We divide output set into subsets. Even Powers: Simply we need to square root n. The count of even powers smaller than n is square root of n. For example even powers smaller than 25 are (1, 4, 9, 16 and 25). Odd Powers: We modify above function to consider only odd powers. " }, { "code": null, "e": 32050, "s": 32046, "text": "C++" }, { "code": null, "e": 32055, "s": 32050, "text": "Java" }, { "code": null, "e": 32063, "s": 32055, "text": "Python3" }, { "code": null, "e": 32066, "s": 32063, "text": "C#" }, { "code": null, "e": 32070, "s": 32066, "text": "PHP" }, { "code": null, "e": 32081, "s": 32070, "text": "Javascript" }, { "code": "// C++ program to count number of numbers from// 1 to n are of type x^y where x>0 and y>1#include <bits/stdc++.h>using namespace std; // For our convenience#define ll long long // Function that keeps all the odd power// numbers upto nint powerNumbers(int n){ vector<int> v; for (ll i = 2; i * i * i <= n; i++) { ll j = i * i; while (j * i <= n) { j *= i; // We need exclude perfect // squares. ll s = sqrt(j); if (s * s != j) v.push_back(j); } } // sort the vector sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); // Return sum of odd and even powers. return v.size() + (ll)sqrt(n);} int main(){ cout << powerNumbers(50); return 0;}", "e": 32874, "s": 32081, "text": null }, { "code": "// Java program to count number// of numbers from 1 to n are// of type x^y where x>0 and y>1import java.io.*;import java.util.*; class GFG{ // Function that keeps all // the odd power numbers upto n static long powerNumbers(int n) { HashSet<Long> v = new HashSet<Long>(); for (long i = 2; i * i * i <= n; i++) { long j = i * i; while (j * i <= n) { j *= i; // We need exclude // perfect squares. long s = (long)Math.sqrt(j); if (s * s != j) v.add(j); } } // sort the vector // v.Sort(); // v.erase(unique(v.begin(), // v.end()), v.end()); // Return sum of odd // and even powers. return v.size() + (long)Math.sqrt(n); } // Driver Code public static void main(String args[]) { System.out.print(powerNumbers(50)); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 33911, "s": 32874, "text": null }, { "code": "# Python3 program to count number of# numbers from 1 to n are of type x^y# where x>0 and y>1import math # Function that keeps all the odd power# numbers upto ndef powerNumbers( n): v = [] for i in range(2, int(math.pow(n, 1.0 / 3.0)) + 1) : j = i * i while (j * i <= n) : j = j * i # We need exclude perfect # squares. s = int(math.sqrt(j)) if (s * s != j): v.append(j) # sort the vector v.sort() v = list(dict.fromkeys(v)) # Return sum of odd and even powers. return len(v) + int(math.sqrt(n)) # Driver Codeif __name__=='__main__': print (powerNumbers(50)) # This code is contributed by Arnab Kundu", "e": 34691, "s": 33911, "text": null }, { "code": "// C# program to count number// of numbers from 1 to n are// of type x^y where x>0 and y>1using System;using System.Collections.Generic; class GFG{ // Function that keeps all // the odd power numbers upto n static long powerNumbers(int n) { HashSet<long> v = new HashSet<long>(); for (long i = 2; i * i * i <= n; i++) { long j = i * i; while (j * i <= n) { j *= i; // We need exclude // perfect squares. long s = (long)Math.Sqrt(j); if (s * s != j) v.Add(j); } } // sort the vector //v.Sort(); //v.erase(unique(v.begin(), // v.end()), v.end()); // Return sum of odd // and even powers. return v.Count + (long)Math.Sqrt(n); } // Driver Code static void Main() { Console.Write(powerNumbers(50)); }} // This code is contributed by// Manish Shaw(manishshaw1)", "e": 35710, "s": 34691, "text": null }, { "code": "<?php// PHP program to count number// of numbers from 1 to n are// of type x^y where x>0 and y>1 // Function that keeps all the// odd power numbers upto nfunction powerNumbers($n){ $v = array(); for ($i = 2; $i * $i * $i <= $n; $i++) { $j = $i * $i; while ($j * $i <= $n) { $j *= $i; // We need exclude perfect // squares. $s = sqrt($j); if ($s * $s != $j) array_push($v, $j); } } // sort the vector sort($v); $uni = array_unique($v); for ($i = 0; $i < count($uni); $i++) { $key = array_search($uni[$i], $v); unset($v[$key]); } // Return sum of odd // and even powers. return count($v) + 3 + intval(sqrt($n));} // Driver Codeecho (powerNumbers(50)); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 36584, "s": 35710, "text": null }, { "code": "<script> // Javascript program to count number // of numbers from 1 to n are // of type x^y where x>0 and y>1 // Function that keeps all // the odd power numbers upto n function powerNumbers(n) { let v = new Set(); for (let i = 2; i * i * i <= n; i++) { let j = i * i; while (j * i <= n) { j *= i; // We need exclude // perfect squares. let s = parseInt(Math.sqrt(j), 10); if (s * s != j) v.add(j); } } // sort the vector // v.Sort(); // v.erase(unique(v.begin(), // v.end()), v.end()); // Return sum of odd // and even powers. return v.size + parseInt(Math.sqrt(n), 10); } document.write(powerNumbers(50)); // This code is contributed by vaibhavrabadiya3.</script>", "e": 37516, "s": 36584, "text": null }, { "code": null, "e": 37519, "s": 37516, "text": "10" }, { "code": null, "e": 37533, "s": 37521, "text": "manishshaw1" }, { "code": null, "e": 37544, "s": 37533, "text": "andrew1234" }, { "code": null, "e": 37563, "s": 37544, "text": "vaibhavrabadiya117" }, { "code": null, "e": 37580, "s": 37563, "text": "vaibhavrabadiya3" }, { "code": null, "e": 37591, "s": 37580, "text": "cpp-vector" }, { "code": null, "e": 37605, "s": 37591, "text": "number-theory" }, { "code": null, "e": 37618, "s": 37605, "text": "Mathematical" }, { "code": null, "e": 37632, "s": 37618, "text": "number-theory" }, { "code": null, "e": 37645, "s": 37632, "text": "Mathematical" }, { "code": null, "e": 37743, "s": 37645, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37767, "s": 37743, "text": "Merge two sorted arrays" }, { "code": null, "e": 37810, "s": 37767, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 37824, "s": 37810, "text": "Prime Numbers" }, { "code": null, "e": 37866, "s": 37824, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 37888, "s": 37866, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 37961, "s": 37888, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 38002, "s": 37961, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 38045, "s": 38002, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 38066, "s": 38045, "text": "Operators in C / C++" } ]
Why it is important to write "using namespace std" in C++ program? - GeeksforGeeks
22 Nov, 2021 In this article, we will discuss the use of “using namespace std” in the C++ program. Need of namespace: As the same name can’t be given to multiple variables, functions, classes, etc. in the same scope. So to overcome this situation namespace is introduced. Program 1: Below is the C++ program illustrating the use of namespace with the same name of function and variables: C++ // C++ program to illustrate the use// of namespace with same name of// function and variables#include <iostream>using namespace std; // Namespace n1namespace n1 {int x = 2; // Function to display the message// for namespace n1void fun(){ cout << "This is fun() of n1" << endl;}} // Namespace n2namespace n2 { int x = 5; // Function to display the message// for namespace n2void fun(){ cout << "This is fun() of n2" << endl;}} // Driver Codeint main(){ // The methods and variables called // using scope resolution(::) cout << n1::x << endl; // Function call n1::fun(); cout << n2::x << endl; // Function ca;; n2::fun(); return 0;} 2 This is fun() of n1 5 This is fun() of n2 Explanation: In the above example program, both n1 and n2 have a variable and function of the same name x and fun() respectively. The namespace is used to decrease or limit the scope of any variable or function. As in the above code variable x and method fun() were limited to namespaces n1 and n2. Thus, their scope was not outside the n1 or n2. Every time using the scope resolution operator (::) in a variable or a function defined is not required, it can be solved with “using” directive. The using directive means to include the whole code written in the namespace in the closing scope. Program 2: Below is the C++ program demonstrating the use of the “using” directive: C++ // C++ program to demonstrate the use// of "using" directive#include <iostream>using namespace std; // Namespace n1namespace n1 {int x = 2;void fun(){ cout << "This is fun() of n1" << endl;}} // Namespace is includedusing namespace n1; // Driver Codeint main(){ cout << x << endl; // Function Call fun(); return 0;} 2 This is fun() of n1 Explanation: In the above program, after writing “using namespace n1“, there is no need to use the scope resolution for utilizing the members of n1. It can be interpreted as “using” copies of the code written in the namespace to the scope in which it has been written. If “using namespace n1” is written inside the main() and tries to use the members (fun() and x in this case) in the different functions it would give a compile-time error. Program 3: Below is the C++ program illustrating the use of “using namespace” inside main() function: C++ // C++ program illustrating the use// of "using namespace" inside main() #include <iostream>using namespace std; // Namespace n1namespace n1 {int x = 2;void fun(){ cout << "This is fun() of n1" << endl;}} // Function calling functionvoid print(){ // Gives error, used without :: fun();} // Driver Codeint main(){ // Namespace inside main using namespace n1; cout << x << endl; // Function Call fun(); return 0;} Output: Explanation: It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program. So the members of the “std” namespace are cout, cin, endl, etc. This namespace is present in the iostream.h header file. Below is the code snippet in C++ showing content written inside iostream.h: C++ // Code written in the iostream.h file namespace std {ostream cout;i0stream cin;// and some more code} Explanation: Now when cout<<“GeeksforGeeks”; is written, the compiler searches for cout in our program which is kept in the std namespace, so the instruction given to the compiler that if the compiler doesn’t find anything in the current scope, try finding it in the std namespace. It is not necessary to write namespaced, simply use scope resolution (::) every time uses the members of std. For example, std::cout, std::cin, std::endl etc. Program 4: Below is the C++ program illustrating the use of std: C++ // C++ program to illustrate// the use of std#include <iostream> // Driver Codeint main(){ int x = 10; std::cout << " The value of x is " << x << std::endl; return 0;} The value of x is 10 Explanation: The output of the program will be the same whether write “using namespace std” or use the scope resolution. saurabh1990aror CPP-Basics C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Operator Overloading in C++ Polymorphism in C++ Sorting a vector in C++ Friend class and function in C++ std::string class in C++ Header files in C/C++ and its uses Program to print ASCII Value of a character How to return multiple values from a function in C or C++? C++ Program for QuickSort Sorting a Map by value in C++ STL
[ { "code": null, "e": 25367, "s": 25339, "text": "\n22 Nov, 2021" }, { "code": null, "e": 25453, "s": 25367, "text": "In this article, we will discuss the use of “using namespace std” in the C++ program." }, { "code": null, "e": 25472, "s": 25453, "text": "Need of namespace:" }, { "code": null, "e": 25571, "s": 25472, "text": "As the same name can’t be given to multiple variables, functions, classes, etc. in the same scope." }, { "code": null, "e": 25626, "s": 25571, "text": "So to overcome this situation namespace is introduced." }, { "code": null, "e": 25637, "s": 25626, "text": "Program 1:" }, { "code": null, "e": 25742, "s": 25637, "text": "Below is the C++ program illustrating the use of namespace with the same name of function and variables:" }, { "code": null, "e": 25746, "s": 25742, "text": "C++" }, { "code": "// C++ program to illustrate the use// of namespace with same name of// function and variables#include <iostream>using namespace std; // Namespace n1namespace n1 {int x = 2; // Function to display the message// for namespace n1void fun(){ cout << \"This is fun() of n1\" << endl;}} // Namespace n2namespace n2 { int x = 5; // Function to display the message// for namespace n2void fun(){ cout << \"This is fun() of n2\" << endl;}} // Driver Codeint main(){ // The methods and variables called // using scope resolution(::) cout << n1::x << endl; // Function call n1::fun(); cout << n2::x << endl; // Function ca;; n2::fun(); return 0;}", "e": 26431, "s": 25746, "text": null }, { "code": null, "e": 26475, "s": 26431, "text": "2\nThis is fun() of n1\n5\nThis is fun() of n2" }, { "code": null, "e": 26490, "s": 26477, "text": "Explanation:" }, { "code": null, "e": 26607, "s": 26490, "text": "In the above example program, both n1 and n2 have a variable and function of the same name x and fun() respectively." }, { "code": null, "e": 26689, "s": 26607, "text": "The namespace is used to decrease or limit the scope of any variable or function." }, { "code": null, "e": 26824, "s": 26689, "text": "As in the above code variable x and method fun() were limited to namespaces n1 and n2. Thus, their scope was not outside the n1 or n2." }, { "code": null, "e": 26970, "s": 26824, "text": "Every time using the scope resolution operator (::) in a variable or a function defined is not required, it can be solved with “using” directive." }, { "code": null, "e": 27069, "s": 26970, "text": "The using directive means to include the whole code written in the namespace in the closing scope." }, { "code": null, "e": 27080, "s": 27069, "text": "Program 2:" }, { "code": null, "e": 27153, "s": 27080, "text": "Below is the C++ program demonstrating the use of the “using” directive:" }, { "code": null, "e": 27157, "s": 27153, "text": "C++" }, { "code": "// C++ program to demonstrate the use// of \"using\" directive#include <iostream>using namespace std; // Namespace n1namespace n1 {int x = 2;void fun(){ cout << \"This is fun() of n1\" << endl;}} // Namespace is includedusing namespace n1; // Driver Codeint main(){ cout << x << endl; // Function Call fun(); return 0;}", "e": 27498, "s": 27157, "text": null }, { "code": null, "e": 27520, "s": 27498, "text": "2\nThis is fun() of n1" }, { "code": null, "e": 27535, "s": 27522, "text": "Explanation:" }, { "code": null, "e": 27671, "s": 27535, "text": "In the above program, after writing “using namespace n1“, there is no need to use the scope resolution for utilizing the members of n1." }, { "code": null, "e": 27791, "s": 27671, "text": "It can be interpreted as “using” copies of the code written in the namespace to the scope in which it has been written." }, { "code": null, "e": 27963, "s": 27791, "text": "If “using namespace n1” is written inside the main() and tries to use the members (fun() and x in this case) in the different functions it would give a compile-time error." }, { "code": null, "e": 27974, "s": 27963, "text": "Program 3:" }, { "code": null, "e": 28065, "s": 27974, "text": "Below is the C++ program illustrating the use of “using namespace” inside main() function:" }, { "code": null, "e": 28069, "s": 28065, "text": "C++" }, { "code": "// C++ program illustrating the use// of \"using namespace\" inside main() #include <iostream>using namespace std; // Namespace n1namespace n1 {int x = 2;void fun(){ cout << \"This is fun() of n1\" << endl;}} // Function calling functionvoid print(){ // Gives error, used without :: fun();} // Driver Codeint main(){ // Namespace inside main using namespace n1; cout << x << endl; // Function Call fun(); return 0;}", "e": 28519, "s": 28069, "text": null }, { "code": null, "e": 28527, "s": 28519, "text": "Output:" }, { "code": null, "e": 28541, "s": 28527, "text": "Explanation: " }, { "code": null, "e": 28650, "s": 28541, "text": "It is known that “std” (abbreviation for the standard) is a namespace whose members are used in the program." }, { "code": null, "e": 28714, "s": 28650, "text": "So the members of the “std” namespace are cout, cin, endl, etc." }, { "code": null, "e": 28771, "s": 28714, "text": "This namespace is present in the iostream.h header file." }, { "code": null, "e": 28847, "s": 28771, "text": "Below is the code snippet in C++ showing content written inside iostream.h:" }, { "code": null, "e": 28853, "s": 28849, "text": "C++" }, { "code": "// Code written in the iostream.h file namespace std {ostream cout;i0stream cin;// and some more code}", "e": 28956, "s": 28853, "text": null }, { "code": null, "e": 28969, "s": 28956, "text": "Explanation:" }, { "code": null, "e": 29238, "s": 28969, "text": "Now when cout<<“GeeksforGeeks”; is written, the compiler searches for cout in our program which is kept in the std namespace, so the instruction given to the compiler that if the compiler doesn’t find anything in the current scope, try finding it in the std namespace." }, { "code": null, "e": 29397, "s": 29238, "text": "It is not necessary to write namespaced, simply use scope resolution (::) every time uses the members of std. For example, std::cout, std::cin, std::endl etc." }, { "code": null, "e": 29408, "s": 29397, "text": "Program 4:" }, { "code": null, "e": 29462, "s": 29408, "text": "Below is the C++ program illustrating the use of std:" }, { "code": null, "e": 29466, "s": 29462, "text": "C++" }, { "code": "// C++ program to illustrate// the use of std#include <iostream> // Driver Codeint main(){ int x = 10; std::cout << \" The value of x is \" << x << std::endl; return 0;}", "e": 29656, "s": 29466, "text": null }, { "code": null, "e": 29677, "s": 29656, "text": "The value of x is 10" }, { "code": null, "e": 29800, "s": 29679, "text": "Explanation: The output of the program will be the same whether write “using namespace std” or use the scope resolution." }, { "code": null, "e": 29816, "s": 29800, "text": "saurabh1990aror" }, { "code": null, "e": 29827, "s": 29816, "text": "CPP-Basics" }, { "code": null, "e": 29831, "s": 29827, "text": "C++" }, { "code": null, "e": 29844, "s": 29831, "text": "C++ Programs" }, { "code": null, "e": 29848, "s": 29844, "text": "CPP" }, { "code": null, "e": 29946, "s": 29848, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29974, "s": 29946, "text": "Operator Overloading in C++" }, { "code": null, "e": 29994, "s": 29974, "text": "Polymorphism in C++" }, { "code": null, "e": 30018, "s": 29994, "text": "Sorting a vector in C++" }, { "code": null, "e": 30051, "s": 30018, "text": "Friend class and function in C++" }, { "code": null, "e": 30076, "s": 30051, "text": "std::string class in C++" }, { "code": null, "e": 30111, "s": 30076, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 30155, "s": 30111, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 30214, "s": 30155, "text": "How to return multiple values from a function in C or C++?" }, { "code": null, "e": 30240, "s": 30214, "text": "C++ Program for QuickSort" } ]
What are boolean operators in Python?
The logical operators and, or and not are also referred to as boolean operators. While and as well as or operator needs two operands, which may evaluate to true or false, not operator needs one operand evaluating to true or false. Boolean and operator returns true if both operands return true. >>> a=50 >>> b=25 >>> a>40 and b>40 False >>> a>100 and b<50 False >>> a==0 and b==0 False >>> a>0 and b>0 True Boolean or operator returns true if any one operand is true >>> a=50 >>> b=25 >>> a>40 or b>40 True >>> a>100 or b<50 True >>> a==0 or b==0 False >>> a>0 or b>0 True The not operator returns true if its operand is a false expression and returns false if it is true. >>> a=10 >>> a>10 False >>> not(a>10) True
[ { "code": null, "e": 1293, "s": 1062, "text": "The logical operators and, or and not are also referred to as boolean operators. While and as well as or operator needs two operands, which may evaluate to true or false, not operator needs one operand evaluating to true or false." }, { "code": null, "e": 1357, "s": 1293, "text": "Boolean and operator returns true if both operands return true." }, { "code": null, "e": 1469, "s": 1357, "text": ">>> a=50\n>>> b=25\n>>> a>40 and b>40\nFalse\n>>> a>100 and b<50\nFalse\n>>> a==0 and b==0\nFalse\n>>> a>0 and b>0\nTrue" }, { "code": null, "e": 1529, "s": 1469, "text": "Boolean or operator returns true if any one operand is true" }, { "code": null, "e": 1635, "s": 1529, "text": ">>> a=50\n>>> b=25\n>>> a>40 or b>40\nTrue\n>>> a>100 or b<50\nTrue\n>>> a==0 or b==0\nFalse\n>>> a>0 or b>0\nTrue" }, { "code": null, "e": 1735, "s": 1635, "text": "The not operator returns true if its operand is a false expression and returns false if it is true." }, { "code": null, "e": 1780, "s": 1735, "text": ">>> a=10\n>>> a>10\nFalse\n>>> not(a>10)\nTrue\n\n" } ]
Underscore.js _.where() Function
24 Nov, 2021 The Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _.where() function is used to find all the elements that matches the searching condition. Suppose to find all the student details of a class then apply the _.where() function to the list of all the sections and pass the condition as the section name. So, the names of all the students of that specific section will be displayed. Syntax: _.where( list, [predicate], [context] ) Parameters: This function accepts three parameters as mentioned above and described below: List: This parameter is used to hold the list of data. Predicate: This parameter is used to hold the test condition. Context: The text which need to display. Return values: This function return an array containing all the elements which match the given condition along with their full details. Difference between _.findWhere() and _.where() function: Both the functions takes an array name and the property to match but the _.where() function displays all the matches whereas, _.findWhere) function matches only the first match. Passing an array to the _.where() function: The ._where() function takes the element from the list one by one and matches the specified condition on the elements details. It will check for those elements which will have ‘true’ in the ‘hasLong’ property. After traversing and checking all the elements, the _.where() function ends. The array of all the elements with this property will be displayed. Example: HTML <html> <head> <title>_.where() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var people = [ {"name": "sakshi", "hasLong": "false"}, {"name": "aishwarya", "hasLong": "true"}, {"name": "akansha", "hasLong": "true"}, {"name": "preeti", "hasLong": "true"} ] console.log(_.where(people, {hasLong: "true"})); </script> </body> </html> Output: Passing a list of elements with a number of properties to _.where() function: Firstly, declare the whole list with all the properties of each element mentioned and then pass the array name along with the property on the basis of which need to match the elements to the _.where() function. It will traverse the whole list and display the details of all the elements which match the given condition. Example: HTML <html> <head> <title>_.where() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var goal = [ { "category" : "education", "title" : "harry University", "value" : 50000, "id":"1" }, { "category" : "traveling", "title" : "tommy University", "value" : 50000, "id":"2" }, { "category" : "education", "title" : "jerry University", "value" : 50000, "id":"3" }, { "category" : "business", "title" : "Charlie University", "value" : 50000, "id":"4" } ] console.log(_.where(goal, {category: "education"})); </script> </body></html> Output: Passing an array having numbers as one of it’s property to _.where() function: Declare the array (here array is ‘users’) then choose one condition on which need to check like ‘id’ which has numbers in its details and finally console.log the final answer. The final output will contain all the elements that match. Example: HTML <html> <head> <title>_.where() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var users = [{id: 1, name: "harry"}, {id: 2, name: "jerry"}, {id: 2, name: "jack"}]; console.log(_.where(users, {id:2})); </script> </body></html> Output: _.where() function as _.findWhere() function: The _.where() function can also work as _.findWhere() function under some conditions. Like if there is only one such element in the array that matches the given condition. As here the output will be an array containing only one element. Example: HTML <html> <head> <title>_.where() function</title> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js" > </script> <script type="text/javascript" src= "https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"> </script> </head> <body> <script type="text/javascript"> var studentArray=[ {name:"Sam", score:34}, {name:"Johny", score:31}, {name:"Smithy", score:23}, {name:"Rahul", score:39}, ]; console.log("student with score 23: ", _.where(studentArray, { 'score': 23 })); </script> </body></html> Output: arorakashish0911 rajeev0719singh JavaScript - Underscore.js JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2021" }, { "code": null, "e": 561, "s": 28, "text": "The Underscore.js is a JavaScript library that provides a lot of useful functions that help in the programming in a big way like the map, filter, invokes, etc even without using any built-in objects. The _.where() function is used to find all the elements that matches the searching condition. Suppose to find all the student details of a class then apply the _.where() function to the list of all the sections and pass the condition as the section name. So, the names of all the students of that specific section will be displayed." }, { "code": null, "e": 570, "s": 561, "text": "Syntax: " }, { "code": null, "e": 610, "s": 570, "text": "_.where( list, [predicate], [context] )" }, { "code": null, "e": 703, "s": 610, "text": "Parameters: This function accepts three parameters as mentioned above and described below: " }, { "code": null, "e": 758, "s": 703, "text": "List: This parameter is used to hold the list of data." }, { "code": null, "e": 820, "s": 758, "text": "Predicate: This parameter is used to hold the test condition." }, { "code": null, "e": 861, "s": 820, "text": "Context: The text which need to display." }, { "code": null, "e": 997, "s": 861, "text": "Return values: This function return an array containing all the elements which match the given condition along with their full details." }, { "code": null, "e": 1232, "s": 997, "text": "Difference between _.findWhere() and _.where() function: Both the functions takes an array name and the property to match but the _.where() function displays all the matches whereas, _.findWhere) function matches only the first match." }, { "code": null, "e": 1631, "s": 1232, "text": "Passing an array to the _.where() function: The ._where() function takes the element from the list one by one and matches the specified condition on the elements details. It will check for those elements which will have ‘true’ in the ‘hasLong’ property. After traversing and checking all the elements, the _.where() function ends. The array of all the elements with this property will be displayed." }, { "code": null, "e": 1642, "s": 1631, "text": "Example: " }, { "code": null, "e": 1647, "s": 1642, "text": "HTML" }, { "code": "<html> <head> <title>_.where() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var people = [ {\"name\": \"sakshi\", \"hasLong\": \"false\"}, {\"name\": \"aishwarya\", \"hasLong\": \"true\"}, {\"name\": \"akansha\", \"hasLong\": \"true\"}, {\"name\": \"preeti\", \"hasLong\": \"true\"} ] console.log(_.where(people, {hasLong: \"true\"})); </script> </body> </html>", "e": 2415, "s": 1647, "text": null }, { "code": null, "e": 2424, "s": 2415, "text": "Output: " }, { "code": null, "e": 2822, "s": 2424, "text": "Passing a list of elements with a number of properties to _.where() function: Firstly, declare the whole list with all the properties of each element mentioned and then pass the array name along with the property on the basis of which need to match the elements to the _.where() function. It will traverse the whole list and display the details of all the elements which match the given condition." }, { "code": null, "e": 2833, "s": 2822, "text": "Example: " }, { "code": null, "e": 2838, "s": 2833, "text": "HTML" }, { "code": "<html> <head> <title>_.where() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var goal = [ { \"category\" : \"education\", \"title\" : \"harry University\", \"value\" : 50000, \"id\":\"1\" }, { \"category\" : \"traveling\", \"title\" : \"tommy University\", \"value\" : 50000, \"id\":\"2\" }, { \"category\" : \"education\", \"title\" : \"jerry University\", \"value\" : 50000, \"id\":\"3\" }, { \"category\" : \"business\", \"title\" : \"Charlie University\", \"value\" : 50000, \"id\":\"4\" } ] console.log(_.where(goal, {category: \"education\"})); </script> </body></html>", "e": 4166, "s": 2838, "text": null }, { "code": null, "e": 4175, "s": 4166, "text": "Output: " }, { "code": null, "e": 4489, "s": 4175, "text": "Passing an array having numbers as one of it’s property to _.where() function: Declare the array (here array is ‘users’) then choose one condition on which need to check like ‘id’ which has numbers in its details and finally console.log the final answer. The final output will contain all the elements that match." }, { "code": null, "e": 4500, "s": 4489, "text": "Example: " }, { "code": null, "e": 4505, "s": 4500, "text": "HTML" }, { "code": "<html> <head> <title>_.where() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var users = [{id: 1, name: \"harry\"}, {id: 2, name: \"jerry\"}, {id: 2, name: \"jack\"}]; console.log(_.where(users, {id:2})); </script> </body></html>", "e": 5152, "s": 4505, "text": null }, { "code": null, "e": 5161, "s": 5152, "text": "Output: " }, { "code": null, "e": 5444, "s": 5161, "text": "_.where() function as _.findWhere() function: The _.where() function can also work as _.findWhere() function under some conditions. Like if there is only one such element in the array that matches the given condition. As here the output will be an array containing only one element." }, { "code": null, "e": 5455, "s": 5444, "text": "Example: " }, { "code": null, "e": 5460, "s": 5455, "text": "HTML" }, { "code": "<html> <head> <title>_.where() function</title> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\" > </script> <script type=\"text/javascript\" src= \"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js\"> </script> </head> <body> <script type=\"text/javascript\"> var studentArray=[ {name:\"Sam\", score:34}, {name:\"Johny\", score:31}, {name:\"Smithy\", score:23}, {name:\"Rahul\", score:39}, ]; console.log(\"student with score 23: \", _.where(studentArray, { 'score': 23 })); </script> </body></html>", "e": 6205, "s": 5460, "text": null }, { "code": null, "e": 6214, "s": 6205, "text": "Output: " }, { "code": null, "e": 6233, "s": 6216, "text": "arorakashish0911" }, { "code": null, "e": 6249, "s": 6233, "text": "rajeev0719singh" }, { "code": null, "e": 6276, "s": 6249, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 6287, "s": 6276, "text": "JavaScript" }, { "code": null, "e": 6294, "s": 6287, "text": "JQuery" }, { "code": null, "e": 6311, "s": 6294, "text": "Web Technologies" } ]
NPDA for accepting the language L = {an bn | n>=1}
03 Jun, 2022 Prerequisite – Pushdown automata, Pushdown automata acceptance by final state Problem – Design a non deterministic PDA for accepting the language L = {[Tex]b^n [/Tex]| n>=1}, i.e., L = {ab, aabb, aaabbb, aaaabbbb, ......} In each of the string, the number of a’s are followed by equal number of b’s. Explanation – Here, we need to maintain the order of a’s and b’s. That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets: = { a, z } Where, = set of all the stack alphabet z = stack start symbol Approach used in the construction of PDA – As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. Stack transition functions – (q0, a, z) (q0, az)(q0, a, a) (q0, aa)(q0, b, a) (q1, )(q1, b, a) (q1, )(q1, , z) (qf, z) Where, q0 = Initial state qf = Final state = indicates pop operation So, this is our required non deterministic PDA for accepting the language L = {[Tex]b^n [/Tex]: n>=1}. simmytarika5 GATE CS Theory of Computation & Automata Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Jun, 2022" }, { "code": null, "e": 131, "s": 52, "text": "Prerequisite – Pushdown automata, Pushdown automata acceptance by final state " }, { "code": null, "e": 235, "s": 131, "text": "Problem – Design a non deterministic PDA for accepting the language L = {[Tex]b^n [/Tex]| n>=1}, i.e.," }, { "code": null, "e": 277, "s": 235, "text": "L = {ab, aabb, aaabbb, aaaabbbb, ......} " }, { "code": null, "e": 356, "s": 277, "text": "In each of the string, the number of a’s are followed by equal number of b’s. " }, { "code": null, "e": 630, "s": 356, "text": "Explanation – Here, we need to maintain the order of a’s and b’s. That is, all the a’s are coming first and then all the b’s are coming. Thus, we need a stack along with the state diagram. The count of a’s and b’s is maintained by the stack. We will take 2 stack alphabets:" }, { "code": null, "e": 642, "s": 630, "text": " = { a, z }" }, { "code": null, "e": 705, "s": 642, "text": "Where, = set of all the stack alphabet z = stack start symbol " }, { "code": null, "e": 1063, "s": 705, "text": "Approach used in the construction of PDA – As we want to design a NPDA, thus every time ‘a’ comes before ‘b’. When ‘a’ comes then push it in stack and if again ‘a’ comes then also push it. After that, when ‘b’ comes then pop one ‘a’ from the stack each time. So, at the end if the stack becomes empty then we can say that the string is accepted by the PDA. " }, { "code": null, "e": 1092, "s": 1063, "text": "Stack transition functions –" }, { "code": null, "e": 1202, "s": 1092, "text": "(q0, a, z) (q0, az)(q0, a, a) (q0, aa)(q0, b, a) (q1, )(q1, b, a) (q1, )(q1, , z) (qf, z) " }, { "code": null, "e": 1273, "s": 1202, "text": "Where, q0 = Initial state qf = Final state = indicates pop operation " }, { "code": null, "e": 1377, "s": 1273, "text": "So, this is our required non deterministic PDA for accepting the language L = {[Tex]b^n [/Tex]: n>=1}." }, { "code": null, "e": 1390, "s": 1377, "text": "simmytarika5" }, { "code": null, "e": 1398, "s": 1390, "text": "GATE CS" }, { "code": null, "e": 1431, "s": 1398, "text": "Theory of Computation & Automata" } ]
Length of longest common subsequence containing vowels
14 May, 2021 Given two strings X and Y of length m and n respectively. The problem is to find the length of the longest common subsequence of strings X and Y which contains all vowel characters. Examples: Input : X = "aieef" Y = "klaief" Output : aie Input : X = "geeksforgeeks" Y = "feroeeks" Output : eoee Source: Paytm Interview Experience ( Backend Developer ). Naive Approach: Generate all subsequences of both given sequences and find the longest matching subsequence which contains all vowel characters. This solution is exponential in term of time complexity. Efficient Approach (Dynamic Programming): This approach is a variation to Longest Common Subsequence | DP-4 problem. The difference in this post is just that the common subsequence characters must all be vowels. C++ Java Python3 C# PHP Javascript // C++ implementation to find the length of longest common// subsequence which contains all vowel characters#include <bits/stdc++.h> using namespace std; // function to check whether 'ch'// is a vowel or notbool isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} // function to find the length of longest common subsequence// which contains all vowel charactersint lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in bottom up fashion. Note // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1])) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n];} // Driver program to test aboveint main(){ char X[] = "aieef"; char Y[] = "klaief"; int m = strlen(X); int n = strlen(Y); cout << "Length of LCS = " << lcs(X, Y, m, n); return 0;} // Java implementation to find the// length of longest common subsequence// which contains all vowel charactersclass GFG{ // function to check whether 'ch'// is a vowel or notstatic boolean isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} // function to find the length of// longest common subsequence which// contains all vowel charactersstatic int lcs(String X, String Y, int m, int n){ int L[][] = new int[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i-1] and Y[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if ((X.charAt(i - 1) == Y.charAt(j - 1)) && isVowel(X.charAt(i - 1))) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n];} // Driver Codepublic static void main(String[] args){ String X = "aieef"; String Y = "klaief"; int m = X.length(); int n = Y.length(); System.out.println("Length of LCS = " + lcs(X, Y, m, n));}} // This code is contributed by Bilal # Python3 implementation to find the# length of longest common subsequence# which contains all vowel characters # function to check whether 'ch'# is a vowel or notdef isVowel(ch): if (ch == 'a' or ch == 'e' or ch == 'i'or ch == 'o' or ch == 'u'): return True return False # function to find the length of longest# common subsequence which contains all# vowel charactersdef lcs(X, Y, m, n): L = [[0 for i in range(n + 1)] for j in range(m + 1)] i, j = 0, 0 # Following steps build L[m+1][n+1] in # bottom up fashion. Note that L[i][j] # contains length of LCS of X[0..i-1] # and Y[0..j-1] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif ((X[i - 1] == Y[j - 1]) and isVowel(X[i - 1])): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of LCS for # X[0..n-1] and Y[0..m-1] which # contains all vowel characters return L[m][n] # Driver CodeX = "aieef"Y = "klaief" m = len(X)n = len(Y) print("Length of LCS =", lcs(X, Y, m, n)) # This code is contributed by Mohit Kumar // C# implementation to find the// length of longest common subsequence// which contains all vowel charactersusing System; class GFG{ // function to check whether// 'ch' is a vowel or notstatic int isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0;} // find max valuestatic int max(int a, int b){ return (a > b) ? a : b;} // function to find the length of// longest common subsequence which// contains all vowel charactersstatic int lcs(String X, String Y, int m, int n){ int [,]L = new int[m + 1, n + 1]; int i, j; // Following steps build L[m+1,n+1] // in bottom up fashion. Note that // L[i,j] contains length of LCS of // X[0..i-1] and Y[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1]) == 1) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = max(L[i - 1, j], L[i, j - 1]); } } // L[m,n] contains length of LCS // for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m, n];} // Driver Codestatic public void Main(String []args){ String X = "aieef"; String Y = "klaief"; int m = X.Length; int n = Y.Length; Console.WriteLine("Length of LCS = " + lcs(X, Y, m, n));}} // This code is contributed by Arnab Kundu <?php// PHP implementation to find the length of// longest common subsequence which contains// all vowel characters // function to check whether 'ch'// is a vowel or notfunction isVowel($ch){ if ($ch == 'a' || $ch == 'e' || $ch == 'i' || $ch == 'o' || $ch == 'u') return true; return false;} // function to find the length of longest common// subsequence which contains all vowel charactersfunction lcs($X, $Y, $m, $n){ $L = array_fill(0, $m + 1, array_fill(0, $n + 1, NULL)); // Following steps build L[m+1][n+1] in bottom // up fashion. Note that L[i][j] contains length // of LCS of X[0..i-1] and Y[0..j-1] for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if (($X[$i - 1] == $Y[$j - 1]) && isVowel($X[$i - 1])) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } // L[m][n] contains length of LCS for X[0..n-1] // and Y[0..m-1] which contains all vowel characters return $L[$m][$n];} // Driver Code$X = "aieef";$Y = "klaief"; $m = strlen($X);$n = strlen($Y); echo "Length of LCS = " . lcs($X, $Y, $m, $n); // This code is contributed by ita_c?> <script> // Javascript implementation to find the// length of longest common subsequence// which contains all vowel characters // Function to check whether 'ch'// is a vowel or notfunction isVowel(ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} // Function to find the length of// longest common subsequence which// contains all vowel charactersfunction lcs(X, Y, m, n){ let L = new Array(m + 1); let i, j; // Following steps build L[m+1][n+1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i-1] and Y[0..j-1] for(i = 0; i <= m; i++) { L[i] = new Array(n + 1); for(j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1])) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n];} // Driver Codelet X = "aieef";let Y = "klaief";let m = X.length;let n = Y.length; document.write("Length of LCS = " + lcs(X, Y, m, n)); // This code is contributed by avanitrachhadiya2155 </script> Length of LCS = 3 Time Complexity: O(m*n). Auxiliary Space: O(m*n). bilal-hungund andrew1234 ukasp mohit kumar 29 avanitrachhadiya2155 LCS subsequence vowel-consonant Dynamic Programming Strings Strings Dynamic Programming LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 May, 2021" }, { "code": null, "e": 236, "s": 54, "text": "Given two strings X and Y of length m and n respectively. The problem is to find the length of the longest common subsequence of strings X and Y which contains all vowel characters." }, { "code": null, "e": 247, "s": 236, "text": "Examples: " }, { "code": null, "e": 370, "s": 247, "text": "Input : X = \"aieef\" \n Y = \"klaief\"\nOutput : aie\n\n\nInput : X = \"geeksforgeeks\" \n Y = \"feroeeks\"\nOutput : eoee" }, { "code": null, "e": 630, "s": 370, "text": "Source: Paytm Interview Experience ( Backend Developer ). Naive Approach: Generate all subsequences of both given sequences and find the longest matching subsequence which contains all vowel characters. This solution is exponential in term of time complexity." }, { "code": null, "e": 747, "s": 630, "text": "Efficient Approach (Dynamic Programming): This approach is a variation to Longest Common Subsequence | DP-4 problem." }, { "code": null, "e": 843, "s": 747, "text": "The difference in this post is just that the common subsequence characters must all be vowels. " }, { "code": null, "e": 847, "s": 843, "text": "C++" }, { "code": null, "e": 852, "s": 847, "text": "Java" }, { "code": null, "e": 860, "s": 852, "text": "Python3" }, { "code": null, "e": 863, "s": 860, "text": "C#" }, { "code": null, "e": 867, "s": 863, "text": "PHP" }, { "code": null, "e": 878, "s": 867, "text": "Javascript" }, { "code": "// C++ implementation to find the length of longest common// subsequence which contains all vowel characters#include <bits/stdc++.h> using namespace std; // function to check whether 'ch'// is a vowel or notbool isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} // function to find the length of longest common subsequence// which contains all vowel charactersint lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] in bottom up fashion. Note // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1])) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n];} // Driver program to test aboveint main(){ char X[] = \"aieef\"; char Y[] = \"klaief\"; int m = strlen(X); int n = strlen(Y); cout << \"Length of LCS = \" << lcs(X, Y, m, n); return 0;}", "e": 2197, "s": 878, "text": null }, { "code": "// Java implementation to find the// length of longest common subsequence// which contains all vowel charactersclass GFG{ // function to check whether 'ch'// is a vowel or notstatic boolean isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} // function to find the length of// longest common subsequence which// contains all vowel charactersstatic int lcs(String X, String Y, int m, int n){ int L[][] = new int[m + 1][n + 1]; int i, j; // Following steps build L[m+1][n+1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i-1] and Y[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if ((X.charAt(i - 1) == Y.charAt(j - 1)) && isVowel(X.charAt(i - 1))) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n];} // Driver Codepublic static void main(String[] args){ String X = \"aieef\"; String Y = \"klaief\"; int m = X.length(); int n = Y.length(); System.out.println(\"Length of LCS = \" + lcs(X, Y, m, n));}} // This code is contributed by Bilal", "e": 3724, "s": 2197, "text": null }, { "code": "# Python3 implementation to find the# length of longest common subsequence# which contains all vowel characters # function to check whether 'ch'# is a vowel or notdef isVowel(ch): if (ch == 'a' or ch == 'e' or ch == 'i'or ch == 'o' or ch == 'u'): return True return False # function to find the length of longest# common subsequence which contains all# vowel charactersdef lcs(X, Y, m, n): L = [[0 for i in range(n + 1)] for j in range(m + 1)] i, j = 0, 0 # Following steps build L[m+1][n+1] in # bottom up fashion. Note that L[i][j] # contains length of LCS of X[0..i-1] # and Y[0..j-1] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif ((X[i - 1] == Y[j - 1]) and isVowel(X[i - 1])): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of LCS for # X[0..n-1] and Y[0..m-1] which # contains all vowel characters return L[m][n] # Driver CodeX = \"aieef\"Y = \"klaief\" m = len(X)n = len(Y) print(\"Length of LCS =\", lcs(X, Y, m, n)) # This code is contributed by Mohit Kumar", "e": 4994, "s": 3724, "text": null }, { "code": "// C# implementation to find the// length of longest common subsequence// which contains all vowel charactersusing System; class GFG{ // function to check whether// 'ch' is a vowel or notstatic int isVowel(char ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return 1; return 0;} // find max valuestatic int max(int a, int b){ return (a > b) ? a : b;} // function to find the length of// longest common subsequence which// contains all vowel charactersstatic int lcs(String X, String Y, int m, int n){ int [,]L = new int[m + 1, n + 1]; int i, j; // Following steps build L[m+1,n+1] // in bottom up fashion. Note that // L[i,j] contains length of LCS of // X[0..i-1] and Y[0..j-1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1]) == 1) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = max(L[i - 1, j], L[i, j - 1]); } } // L[m,n] contains length of LCS // for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m, n];} // Driver Codestatic public void Main(String []args){ String X = \"aieef\"; String Y = \"klaief\"; int m = X.Length; int n = Y.Length; Console.WriteLine(\"Length of LCS = \" + lcs(X, Y, m, n));}} // This code is contributed by Arnab Kundu", "e": 6556, "s": 4994, "text": null }, { "code": "<?php// PHP implementation to find the length of// longest common subsequence which contains// all vowel characters // function to check whether 'ch'// is a vowel or notfunction isVowel($ch){ if ($ch == 'a' || $ch == 'e' || $ch == 'i' || $ch == 'o' || $ch == 'u') return true; return false;} // function to find the length of longest common// subsequence which contains all vowel charactersfunction lcs($X, $Y, $m, $n){ $L = array_fill(0, $m + 1, array_fill(0, $n + 1, NULL)); // Following steps build L[m+1][n+1] in bottom // up fashion. Note that L[i][j] contains length // of LCS of X[0..i-1] and Y[0..j-1] for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if (($X[$i - 1] == $Y[$j - 1]) && isVowel($X[$i - 1])) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } // L[m][n] contains length of LCS for X[0..n-1] // and Y[0..m-1] which contains all vowel characters return $L[$m][$n];} // Driver Code$X = \"aieef\";$Y = \"klaief\"; $m = strlen($X);$n = strlen($Y); echo \"Length of LCS = \" . lcs($X, $Y, $m, $n); // This code is contributed by ita_c?>", "e": 7918, "s": 6556, "text": null }, { "code": "<script> // Javascript implementation to find the// length of longest common subsequence// which contains all vowel characters // Function to check whether 'ch'// is a vowel or notfunction isVowel(ch){ if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') return true; return false;} // Function to find the length of// longest common subsequence which// contains all vowel charactersfunction lcs(X, Y, m, n){ let L = new Array(m + 1); let i, j; // Following steps build L[m+1][n+1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i-1] and Y[0..j-1] for(i = 0; i <= m; i++) { L[i] = new Array(n + 1); for(j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if ((X[i - 1] == Y[j - 1]) && isVowel(X[i - 1])) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n-1] and Y[0..m-1] // which contains all vowel characters return L[m][n];} // Driver Codelet X = \"aieef\";let Y = \"klaief\";let m = X.length;let n = Y.length; document.write(\"Length of LCS = \" + lcs(X, Y, m, n)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 9333, "s": 7918, "text": null }, { "code": null, "e": 9351, "s": 9333, "text": "Length of LCS = 3" }, { "code": null, "e": 9404, "s": 9353, "text": "Time Complexity: O(m*n). Auxiliary Space: O(m*n). " }, { "code": null, "e": 9418, "s": 9404, "text": "bilal-hungund" }, { "code": null, "e": 9429, "s": 9418, "text": "andrew1234" }, { "code": null, "e": 9435, "s": 9429, "text": "ukasp" }, { "code": null, "e": 9450, "s": 9435, "text": "mohit kumar 29" }, { "code": null, "e": 9471, "s": 9450, "text": "avanitrachhadiya2155" }, { "code": null, "e": 9475, "s": 9471, "text": "LCS" }, { "code": null, "e": 9487, "s": 9475, "text": "subsequence" }, { "code": null, "e": 9503, "s": 9487, "text": "vowel-consonant" }, { "code": null, "e": 9523, "s": 9503, "text": "Dynamic Programming" }, { "code": null, "e": 9531, "s": 9523, "text": "Strings" }, { "code": null, "e": 9539, "s": 9531, "text": "Strings" }, { "code": null, "e": 9559, "s": 9539, "text": "Dynamic Programming" }, { "code": null, "e": 9563, "s": 9559, "text": "LCS" } ]
Join two ArrayLists in Java
11 Dec, 2018 Given two ArrayLists in Java, the task is to join these ArrayLists. Examples: Input: ArrayList1: [Geeks, For, ForGeeks], ArrayList2: [GeeksForGeeks, A computer portal]Output: ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal] Input: ArrayList1: [G, e, e, k, s], ArrayList2: [F, o, r, G, e, e, k, s]Output: ArrayList: [G, e, e, k, s, F, o, r, G, e, e, k, s] Approach: ArrayLists can be joined in Java with the help of Collection.addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList. Syntax: ArrayList1.addAll(ArrayList2); Below is the implementation of the above approach: // Java program to demonstrate// How to sort ArrayList in descending order import java.util.*; public class GFG { public static void main(String args[]) { // Get the ArrayList1 ArrayList<String> list1 = new ArrayList<String>(); // Populate the ArrayList list1.add("Geeks"); list1.add("For"); list1.add("ForGeeks"); // Print the ArrayList 1 System.out.println("ArrayList 1: " + list1); // Get the ArrayList2 ArrayList<String> list2 = new ArrayList<String>(); list2.add("GeeksForGeeks"); list2.add("A computer portal"); // Print the ArrayList 2 System.out.println("ArrayList 2: " + list2); // Join the ArrayLists // using Collection.addAll() method list1.addAll(list2); // Print the joined ArrayList System.out.println("Joined ArrayLists: " + list1); }} Java - util package Java-ArrayList Java-Collections Java-List-Programs Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Dec, 2018" }, { "code": null, "e": 120, "s": 52, "text": "Given two ArrayLists in Java, the task is to join these ArrayLists." }, { "code": null, "e": 130, "s": 120, "text": "Examples:" }, { "code": null, "e": 295, "s": 130, "text": "Input: ArrayList1: [Geeks, For, ForGeeks], ArrayList2: [GeeksForGeeks, A computer portal]Output: ArrayList: [Geeks, For, ForGeeks, GeeksForGeeks, A computer portal]" }, { "code": null, "e": 426, "s": 295, "text": "Input: ArrayList1: [G, e, e, k, s], ArrayList2: [F, o, r, G, e, e, k, s]Output: ArrayList: [G, e, e, k, s, F, o, r, G, e, e, k, s]" }, { "code": null, "e": 708, "s": 426, "text": "Approach: ArrayLists can be joined in Java with the help of Collection.addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList." }, { "code": null, "e": 716, "s": 708, "text": "Syntax:" }, { "code": null, "e": 747, "s": 716, "text": "ArrayList1.addAll(ArrayList2);" }, { "code": null, "e": 798, "s": 747, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to demonstrate// How to sort ArrayList in descending order import java.util.*; public class GFG { public static void main(String args[]) { // Get the ArrayList1 ArrayList<String> list1 = new ArrayList<String>(); // Populate the ArrayList list1.add(\"Geeks\"); list1.add(\"For\"); list1.add(\"ForGeeks\"); // Print the ArrayList 1 System.out.println(\"ArrayList 1: \" + list1); // Get the ArrayList2 ArrayList<String> list2 = new ArrayList<String>(); list2.add(\"GeeksForGeeks\"); list2.add(\"A computer portal\"); // Print the ArrayList 2 System.out.println(\"ArrayList 2: \" + list2); // Join the ArrayLists // using Collection.addAll() method list1.addAll(list2); // Print the joined ArrayList System.out.println(\"Joined ArrayLists: \" + list1); }}", "e": 1810, "s": 798, "text": null }, { "code": null, "e": 1830, "s": 1810, "text": "Java - util package" }, { "code": null, "e": 1845, "s": 1830, "text": "Java-ArrayList" }, { "code": null, "e": 1862, "s": 1845, "text": "Java-Collections" }, { "code": null, "e": 1881, "s": 1862, "text": "Java-List-Programs" }, { "code": null, "e": 1886, "s": 1881, "text": "Java" }, { "code": null, "e": 1891, "s": 1886, "text": "Java" }, { "code": null, "e": 1908, "s": 1891, "text": "Java-Collections" } ]
ReactJS Reactstrap Carousel Component
22 Jul, 2021 Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Carousel component allows the user to show the sliding item, and it is used when there is a group of content on the same level. We can use the following approach in ReactJS to use the ReactJS Reactstrap Carousel Component. Carousel Props: activeIndex: It is used to control the current active visible slide. next: It is a callback function that is triggered when the next button is clicked. previous: It is a callback function that is triggered when the previous button is clicked. keyboard: It is used to indicate whether the carousel should react to the keyboard event or not. pause: It is used to pause the slide based on different mouse events. ride: It is used to autoplay the carousel after the user manually cycles the first item. interval: It is used to delay time between automatically cycling movement for these items. children: It is used to pass the children element to this component. mouseEnter: It is a callback function that is triggered when the mouse enters the Carousel. mouseLeave: It is a callback function that is triggered when the mouse exits the Carousel. slide: It is used to enable the animation between slides. cssModule: It is used to denote the CSS module for styling. enableTouch: It is used to indicate whether the touch gestures on the Carousel works or not. CarouselItem Props: tag: It is used to denote the tag for this component. in: It is used to denote whether to show an item or not. cssModule: It is used to denote the CSS module for styling. children: It is used to pass the children element to this component. slide: It is used to enable the animation between slides. CarouselControl Props: direction: It is used to denote the direction like next or previous. onClickHandler: It is a callback function that is triggered when it is clicked. cssModule: It is used to denote the CSS module for styling. directionText: It is used to denote the direction text. CarouselIndicators Props: items: It is used to denote the items array. activeIndex: It is used to control the current active visible slide. cssModule: It is used to denote the CSS module for styling. onClickHandler: It is a callback function that is triggered when it is clicked. CarouselCaption Props: captionHeader: It is used to denote the caption header value. captionText: It is used to denote the caption text value. cssModule: It is used to denote the CSS module for styling. UncontrolledCarousel Props: items: It is used to denote the items array. indicators: It is used to show a set of slide position indicators. controls: It is used to indicate whether it has controls or not. autoPlay: It is used to indicate whether it can be auto-played or not. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap Step 3: After creating the ReactJS application, Install the required module using the following command: npm install reactstrap bootstrap Project Structure: It will look like the following. Project Structure Example 1: Now write down the following code in the App.js file. Here, we have used the Carousel component with the carousel control buttons. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { CarouselControl, Carousel, CarouselItem, CarouselIndicators,} from 'reactstrap'; function App() { // State for Active index const [activeIndex, setActiveIndex] = React.useState(0); // State for Animation const [animating, setAnimating] = React.useState(false); // Sample items for Carousel const items = [ { caption: 'Sample Caption One',src: 'https://media.geeksforgeeks.org/wp-content/uploads/20210425122739/2-300x115.png', altText: 'Slide One' }, { caption: 'Sample Caption Two',src: 'https://media.geeksforgeeks.org/wp-content/uploads/20210425122716/1-300x115.png', altText: 'Slide Two' } ]; // Items array length const itemLength = items.length - 1 // Previous button for Carousel const previousButton = () => { if (animating) return; const nextIndex = activeIndex === 0 ? itemLength : activeIndex - 1; setActiveIndex(nextIndex); } // Next button for Carousel const nextButton = () => { if (animating) return; const nextIndex = activeIndex === itemLength ? 0 : activeIndex + 1; setActiveIndex(nextIndex); } // Carousel Item Data const carouselItemData = items.map((item) => { return ( <CarouselItem key={item.src} onExited={() => setAnimating(false)} onExiting={() => setAnimating(true)} > <img src={item.src} alt={item.altText} /> </CarouselItem> ); }); return ( <div style={{ display: 'block', width: 320, padding: 30 }}> <h8>ReactJS Reactstrap Carousel Component</h8> <Carousel previous={previousButton} next={nextButton} activeIndex={activeIndex}> <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={(newIndex) => { if (animating) return; setActiveIndex(newIndex); }} /> {carouselItemData} <CarouselControl directionText="Prev" direction="prev" onClickHandler={previousButton} /> <CarouselControl directionText="Next" direction="next" onClickHandler={nextButton} /> </Carousel> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Example 2: Now write down the following code in the App.js file. Here, we have used the Carousel component without the carousel control buttons. App.js import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Carousel, CarouselItem, CarouselIndicators,} from 'reactstrap'; function App() { // State for Active index const [activeIndex, setActiveIndex] = React.useState(0); // State for Animation const [animating, setAnimating] = React.useState(false); // Sample items for Carousel const items = [ {src: 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190603152813/ml_gaming.png', }, {src: 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190528184201/gateexam.png', } ]; // Items array length const itemLength = items.length - 1 // Previous button for Carousel const previousButton = () => { if (animating) return; const nextIndex = activeIndex === 0 ? itemLength : activeIndex - 1; setActiveIndex(nextIndex); } // Next button for Carousel const nextButton = () => { if (animating) return; const nextIndex = activeIndex === itemLength ? 0 : activeIndex + 1; setActiveIndex(nextIndex); } // Carousel Item Data const carouselItemData = items.map((item) => { return ( <CarouselItem key={item.src} onExited={() => setAnimating(false)} onExiting={() => setAnimating(true)} > <img src={item.src} alt={item.altText} /> </CarouselItem> ); }); return ( <div style={{ display: 'block', padding: 30 }}> <h1>ReactJS Reactstrap Carousel Component</h1> <Carousel previous={previousButton} next={nextButton} activeIndex={activeIndex}> <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={(newIndex) => { if (animating) return; setActiveIndex(newIndex); }} /> {carouselItemData} </Carousel> </div > );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://reactstrap.github.io/components/carousel/ Reactstrap ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jul, 2021" }, { "code": null, "e": 417, "s": 28, "text": "Reactstrap is a popular front-end library that is easy to use React Bootstrap 4 components. This library contains the stateless React components for Bootstrap 4. The Carousel component allows the user to show the sliding item, and it is used when there is a group of content on the same level. We can use the following approach in ReactJS to use the ReactJS Reactstrap Carousel Component." }, { "code": null, "e": 433, "s": 417, "text": "Carousel Props:" }, { "code": null, "e": 502, "s": 433, "text": "activeIndex: It is used to control the current active visible slide." }, { "code": null, "e": 585, "s": 502, "text": "next: It is a callback function that is triggered when the next button is clicked." }, { "code": null, "e": 676, "s": 585, "text": "previous: It is a callback function that is triggered when the previous button is clicked." }, { "code": null, "e": 773, "s": 676, "text": "keyboard: It is used to indicate whether the carousel should react to the keyboard event or not." }, { "code": null, "e": 843, "s": 773, "text": "pause: It is used to pause the slide based on different mouse events." }, { "code": null, "e": 932, "s": 843, "text": "ride: It is used to autoplay the carousel after the user manually cycles the first item." }, { "code": null, "e": 1023, "s": 932, "text": "interval: It is used to delay time between automatically cycling movement for these items." }, { "code": null, "e": 1092, "s": 1023, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 1184, "s": 1092, "text": "mouseEnter: It is a callback function that is triggered when the mouse enters the Carousel." }, { "code": null, "e": 1275, "s": 1184, "text": "mouseLeave: It is a callback function that is triggered when the mouse exits the Carousel." }, { "code": null, "e": 1333, "s": 1275, "text": "slide: It is used to enable the animation between slides." }, { "code": null, "e": 1393, "s": 1333, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 1486, "s": 1393, "text": "enableTouch: It is used to indicate whether the touch gestures on the Carousel works or not." }, { "code": null, "e": 1506, "s": 1486, "text": "CarouselItem Props:" }, { "code": null, "e": 1560, "s": 1506, "text": "tag: It is used to denote the tag for this component." }, { "code": null, "e": 1617, "s": 1560, "text": "in: It is used to denote whether to show an item or not." }, { "code": null, "e": 1677, "s": 1617, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 1746, "s": 1677, "text": "children: It is used to pass the children element to this component." }, { "code": null, "e": 1804, "s": 1746, "text": "slide: It is used to enable the animation between slides." }, { "code": null, "e": 1827, "s": 1804, "text": "CarouselControl Props:" }, { "code": null, "e": 1896, "s": 1827, "text": "direction: It is used to denote the direction like next or previous." }, { "code": null, "e": 1976, "s": 1896, "text": "onClickHandler: It is a callback function that is triggered when it is clicked." }, { "code": null, "e": 2036, "s": 1976, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 2092, "s": 2036, "text": "directionText: It is used to denote the direction text." }, { "code": null, "e": 2118, "s": 2092, "text": "CarouselIndicators Props:" }, { "code": null, "e": 2163, "s": 2118, "text": "items: It is used to denote the items array." }, { "code": null, "e": 2232, "s": 2163, "text": "activeIndex: It is used to control the current active visible slide." }, { "code": null, "e": 2292, "s": 2232, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 2372, "s": 2292, "text": "onClickHandler: It is a callback function that is triggered when it is clicked." }, { "code": null, "e": 2395, "s": 2372, "text": "CarouselCaption Props:" }, { "code": null, "e": 2457, "s": 2395, "text": "captionHeader: It is used to denote the caption header value." }, { "code": null, "e": 2515, "s": 2457, "text": "captionText: It is used to denote the caption text value." }, { "code": null, "e": 2575, "s": 2515, "text": "cssModule: It is used to denote the CSS module for styling." }, { "code": null, "e": 2603, "s": 2575, "text": "UncontrolledCarousel Props:" }, { "code": null, "e": 2648, "s": 2603, "text": "items: It is used to denote the items array." }, { "code": null, "e": 2715, "s": 2648, "text": "indicators: It is used to show a set of slide position indicators." }, { "code": null, "e": 2780, "s": 2715, "text": "controls: It is used to indicate whether it has controls or not." }, { "code": null, "e": 2851, "s": 2780, "text": "autoPlay: It is used to indicate whether it can be auto-played or not." }, { "code": null, "e": 2901, "s": 2851, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 2996, "s": 2901, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 3060, "s": 2996, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 3092, "s": 3060, "text": "npx create-react-app foldername" }, { "code": null, "e": 3205, "s": 3092, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 3305, "s": 3205, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 3319, "s": 3305, "text": "cd foldername" }, { "code": null, "e": 3456, "s": 3319, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install reactstrap bootstrap" }, { "code": null, "e": 3561, "s": 3456, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 3594, "s": 3561, "text": "npm install reactstrap bootstrap" }, { "code": null, "e": 3646, "s": 3594, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 3664, "s": 3646, "text": "Project Structure" }, { "code": null, "e": 3806, "s": 3664, "text": "Example 1: Now write down the following code in the App.js file. Here, we have used the Carousel component with the carousel control buttons." }, { "code": null, "e": 3813, "s": 3806, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { CarouselControl, Carousel, CarouselItem, CarouselIndicators,} from 'reactstrap'; function App() { // State for Active index const [activeIndex, setActiveIndex] = React.useState(0); // State for Animation const [animating, setAnimating] = React.useState(false); // Sample items for Carousel const items = [ { caption: 'Sample Caption One',src: 'https://media.geeksforgeeks.org/wp-content/uploads/20210425122739/2-300x115.png', altText: 'Slide One' }, { caption: 'Sample Caption Two',src: 'https://media.geeksforgeeks.org/wp-content/uploads/20210425122716/1-300x115.png', altText: 'Slide Two' } ]; // Items array length const itemLength = items.length - 1 // Previous button for Carousel const previousButton = () => { if (animating) return; const nextIndex = activeIndex === 0 ? itemLength : activeIndex - 1; setActiveIndex(nextIndex); } // Next button for Carousel const nextButton = () => { if (animating) return; const nextIndex = activeIndex === itemLength ? 0 : activeIndex + 1; setActiveIndex(nextIndex); } // Carousel Item Data const carouselItemData = items.map((item) => { return ( <CarouselItem key={item.src} onExited={() => setAnimating(false)} onExiting={() => setAnimating(true)} > <img src={item.src} alt={item.altText} /> </CarouselItem> ); }); return ( <div style={{ display: 'block', width: 320, padding: 30 }}> <h8>ReactJS Reactstrap Carousel Component</h8> <Carousel previous={previousButton} next={nextButton} activeIndex={activeIndex}> <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={(newIndex) => { if (animating) return; setActiveIndex(newIndex); }} /> {carouselItemData} <CarouselControl directionText=\"Prev\" direction=\"prev\" onClickHandler={previousButton} /> <CarouselControl directionText=\"Next\" direction=\"next\" onClickHandler={nextButton} /> </Carousel> </div > );} export default App;", "e": 6350, "s": 3813, "text": null }, { "code": null, "e": 6463, "s": 6350, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 6473, "s": 6463, "text": "npm start" }, { "code": null, "e": 6572, "s": 6473, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 6717, "s": 6572, "text": "Example 2: Now write down the following code in the App.js file. Here, we have used the Carousel component without the carousel control buttons." }, { "code": null, "e": 6724, "s": 6717, "text": "App.js" }, { "code": "import React from 'react'import 'bootstrap/dist/css/bootstrap.min.css';import { Carousel, CarouselItem, CarouselIndicators,} from 'reactstrap'; function App() { // State for Active index const [activeIndex, setActiveIndex] = React.useState(0); // State for Animation const [animating, setAnimating] = React.useState(false); // Sample items for Carousel const items = [ {src: 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190603152813/ml_gaming.png', }, {src: 'https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190528184201/gateexam.png', } ]; // Items array length const itemLength = items.length - 1 // Previous button for Carousel const previousButton = () => { if (animating) return; const nextIndex = activeIndex === 0 ? itemLength : activeIndex - 1; setActiveIndex(nextIndex); } // Next button for Carousel const nextButton = () => { if (animating) return; const nextIndex = activeIndex === itemLength ? 0 : activeIndex + 1; setActiveIndex(nextIndex); } // Carousel Item Data const carouselItemData = items.map((item) => { return ( <CarouselItem key={item.src} onExited={() => setAnimating(false)} onExiting={() => setAnimating(true)} > <img src={item.src} alt={item.altText} /> </CarouselItem> ); }); return ( <div style={{ display: 'block', padding: 30 }}> <h1>ReactJS Reactstrap Carousel Component</h1> <Carousel previous={previousButton} next={nextButton} activeIndex={activeIndex}> <CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={(newIndex) => { if (animating) return; setActiveIndex(newIndex); }} /> {carouselItemData} </Carousel> </div > );} export default App;", "e": 8845, "s": 6724, "text": null }, { "code": null, "e": 8958, "s": 8845, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 8968, "s": 8958, "text": "npm start" }, { "code": null, "e": 9067, "s": 8968, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 9129, "s": 9067, "text": "Reference: https://reactstrap.github.io/components/carousel/" }, { "code": null, "e": 9140, "s": 9129, "text": "Reactstrap" }, { "code": null, "e": 9148, "s": 9140, "text": "ReactJS" }, { "code": null, "e": 9165, "s": 9148, "text": "Web Technologies" } ]
Timer Objects in Python
28 Jun, 2017 Timer objects are used to represent actions that needs to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action was actually performed by the interpreter because it is the responsibility of the thread scheduler to actually schedule the thread corresponding to the timer object. Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly. Creating a Timer object Syntax: threading.Timer(interval, function, args = None, kwargs = None) Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used. # Program to demonstrate# timer objects in python import threadingdef gfg(): print("GeeksforGeeks\n") timer = threading.Timer(2.0, gfg)timer.start()print("Exit\n") Output: Exit GeeksforGeeks Explanation: The program above, schedules gfg() function to run after 5 seconds of interval since start() function call. Cancelling a timer Syntax: timer.cancel() Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage. # Program to cancel the timerimport threading def gfg(): print("GeeksforGeeks\n") timer = threading.Timer(5.0, gfg)timer.start()print("Cancelling timer\n")timer.cancel()print("Exit\n") Output: Cancelling timer Exit 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. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2017" }, { "code": null, "e": 519, "s": 54, "text": "Timer objects are used to represent actions that needs to be scheduled to run after a certain instant of time. These objects get scheduled to run on a separate thread that carries out the action. However, the interval that a timer is initialized with might not be the actual instant when the action was actually performed by the interpreter because it is the responsibility of the thread scheduler to actually schedule the thread corresponding to the timer object." }, { "code": null, "e": 660, "s": 519, "text": "Timer is a sub class of Thread class defined in python. It is started by calling the start() function corresponding to the timer explicitly." }, { "code": null, "e": 684, "s": 660, "text": "Creating a Timer object" }, { "code": null, "e": 692, "s": 684, "text": "Syntax:" }, { "code": null, "e": 757, "s": 692, "text": "threading.Timer(interval, function, args = None, kwargs = None) " }, { "code": null, "e": 1009, "s": 757, "text": "Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used." }, { "code": "# Program to demonstrate# timer objects in python import threadingdef gfg(): print(\"GeeksforGeeks\\n\") timer = threading.Timer(2.0, gfg)timer.start()print(\"Exit\\n\")", "e": 1178, "s": 1009, "text": null }, { "code": null, "e": 1186, "s": 1178, "text": "Output:" }, { "code": null, "e": 1205, "s": 1186, "text": "Exit\nGeeksforGeeks" }, { "code": null, "e": 1326, "s": 1205, "text": "Explanation: The program above, schedules gfg() function to run after 5 seconds of interval since start() function call." }, { "code": null, "e": 1345, "s": 1326, "text": "Cancelling a timer" }, { "code": null, "e": 1353, "s": 1345, "text": "Syntax:" }, { "code": null, "e": 1368, "s": 1353, "text": "timer.cancel()" }, { "code": null, "e": 1496, "s": 1368, "text": "Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage." }, { "code": "# Program to cancel the timerimport threading def gfg(): print(\"GeeksforGeeks\\n\") timer = threading.Timer(5.0, gfg)timer.start()print(\"Cancelling timer\\n\")timer.cancel()print(\"Exit\\n\")", "e": 1686, "s": 1496, "text": null }, { "code": null, "e": 1694, "s": 1686, "text": "Output:" }, { "code": null, "e": 1716, "s": 1694, "text": "Cancelling timer\nExit" }, { "code": null, "e": 2016, "s": 1716, "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": 2141, "s": 2016, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 2148, "s": 2141, "text": "Python" } ]
Construct a Binary Tree in Level Order using Recursion
08 Mar, 2022 Given an array of integers, the task is to construct a binary tree in level order fashion using Recursion. Examples Given an array arr[] = {15, 10, 20, 8, 12, 16, 25} Approach: Idea is to keep track of the number of child nodes in the left sub-tree and right sub-tree and then take the decision on the basis of these counts. When the count of children nodes in left and right sub-tree are equal, then the node has to be inserted in left sub-tree by creating a new level in the binary tree. When the count of children nodes in the left sub-tree is greater than the count of the children nodes in the right sub-tree then there are two cases. When the left sub-tree is perfect binary tree, then node is to be inserted in right sub-tree.When left sub-tree is not perfect binary tree, then node is to be inserted in left sub-tree. When the left sub-tree is perfect binary tree, then node is to be inserted in right sub-tree. When left sub-tree is not perfect binary tree, then node is to be inserted in left sub-tree. A perfect binary tree with n levels have 2(n-1) nodes with all the leaf nodes at same level. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ implementation to construct// Binary Tree in level order fashion#include <iostream>using namespace std; // Structure of the Node of Binary tree// with count of Children nodes in// left sub-tree and right sub-tree.struct Node { int data; int rcount; int lcount; struct Node* left; struct Node* right;}; // Function to check whether the given// Binary tree is a perfect binary tree// using the no. of nodes in tree.bool isPBT(int count){ count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false;} // Function to create a new Nodestruct Node* newNode(int data){ struct Node* temp = (struct Node*)malloc( sizeof(struct Node) ); temp->data = data; temp->right = NULL; temp->left = NULL; temp->rcount = 0; temp->lcount = 0;} // Recursive function to insert// elements in a binary treestruct Node* insert(struct Node* root, int data){ // Condition when root is NULL if (root == NULL) { struct Node* n = newNode(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root->rcount == root->lcount) { root->left = insert(root->left, data); root->lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root->rcount < root->lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root->lcount)) { root->right = insert(root->right, data); root->rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root->left = insert(root->left, data); root->lcount += 1; } } return root;} // Function for inorder Traversal of tree.void inorder(struct Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); }} // Driver Codeint main(){ int arr[] = { 8, 6, 7, 12, 5, 1, 9 }; int size = sizeof(arr) / sizeof(int); struct Node* root = NULL; // Loop to insert nodes in // Binary Tree in level order for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); return 0;} // Java implementation to construct// Binary Tree in level order fashion class Node { int data; int rcount; int lcount; Node left; Node right; Node(int data) { this.data = data; this.rcount = this.lcount = 0; this.left = this.right = null; } // Function for inorder Traversal of tree. static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + " "); inorder(root.right); } } // Function to check whether the given // Binary tree is a perfect binary tree // using the no. of nodes in tree. static boolean isPBT(int count) { count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false; } // Recursive function to insert // elements in a binary tree static Node insert(Node root, int data) { // Condition when root is NULL if (root == null) { Node n = new Node(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount) { root.left = insert(root.left, data); root.lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)) { root.right = insert(root.right, data); root.rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root.left = insert(root.left, data); root.lcount += 1; } } return root; } // Driver Code public static void main(String args[]) { int arr[] = { 8, 6, 7, 12, 5, 1, 9 }; int size = 7; Node root = null; // Loop to insert nodes in // Binary Tree in level order Traversal for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); }} # Python3 implementation to construct# Binary Tree in level order fashion # Structure of the Node of Binary tree# with count of Children nodes in# left sub-tree and right sub-tree.class Node: def __init__(self, data): self.data = data self.rcount = 0 self.lcount = 0 self.left = None self.right = None # Function to check whether the given# Binary tree is a perfect binary tree# using the no. of nodes in tree.def isPBT(count: int) -> bool: count = count + 1 # Loop to check the count is in # the form of 2^(n-1) while (count % 2 == 0): count = count / 2 if (count == 1): return True else: return False # Recursive function to insert# elements in a binary treedef insert(root: Node, data: int) -> Node: # Condition when root is NULL if (root is None): n = Node(data) return n # Condition when count of left sub-tree # nodes is equal to the count # of right sub-tree nodes if (root.rcount == root.lcount): root.left = insert(root.left, data) root.lcount += 1 # Condition when count of left sub-tree # nodes is greater than # the right sub-tree nodes elif (root.rcount < root.lcount): # Condition when left Sub-tree is # Perfect Binary Tree then Insert # in right sub-tree. if (isPBT(root.lcount)): root.right = insert(root.right, data) root.rcount += 1 # If Left Sub-tree is not Perfect # Binary Tree then Insert in left sub-tree else: root.left = insert(root.left, data) root.lcount += 1 return root # Function for inorder Traversal of tree.def inorder(root: Node) -> None: if root != None: inorder(root.left) print(root.data, end = " ") inorder(root.right) # Driver Codeif __name__ == "__main__": arr = [ 8, 6, 7, 12, 5, 1, 9 ] size = len(arr) root = None # Loop to insert nodes in # Binary Tree in level order for i in range(size): root = insert(root, arr[i]) inorder(root) # This code is contributed by sanjeev2552 // C# implementation to construct// Binary Tree in level order fashionusing System; class Node { public int data; public int rcount; public int lcount; public Node left; public Node right; public Node(int data) { this.data = data; this.rcount = this.lcount = 0; this.left = this.right = null; } // Function for inorder Traversal of tree. static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.data + " "); inorder(root.right); } } // Function to check whether the given // Binary tree is a perfect binary tree // using the no. of nodes in tree. static bool isPBT(int count) { count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false; } // Recursive function to insert // elements in a binary tree static Node insert(Node root, int data) { // Condition when root is NULL if (root == null) { Node n = new Node(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount) { root.left = insert(root.left, data); root.lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)) { root.right = insert(root.right, data); root.rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root.left = insert(root.left, data); root.lcount += 1; } } return root; } // Driver Code public static void Main(String []args) { int []arr = { 8, 6, 7, 12, 5, 1, 9 }; int size = 7; Node root = null; // Loop to insert nodes in // Binary Tree in level order Traversal for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation to construct// Binary Tree in level order fashion // Structure of the Node of Binary tree// with count of Children nodes in// left sub-tree and right sub-tree.class Node{ constructor(data){ this.data = data this.rcount = 0 this.lcount = 0 this.left = null this.right = null }} // Function to check whether the given// Binary tree is a perfect binary tree// using the no. of nodes in tree.function isPBT(count){ count = count + 1 // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2 if (count == 1) return true else return false} // Recursive function to insert// elements in a binary treefunction insert(root, data){ // Condition when root is NULL if (!root){ let n = new Node(data) return n } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount){ root.left = insert(root.left, data) root.lcount += 1 } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount){ // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)){ root.right = insert(root.right, data) root.rcount += 1 } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else{ root.left = insert(root.left, data) root.lcount += 1 } } return root} // Function for inorder Traversal of tree.function inorder(root){ if(root){ inorder(root.left) document.write(root.data," ") inorder(root.right) }} // Driver Code let arr = [ 8, 6, 7, 12, 5, 1, 9 ]let size = arr.lengthlet root = null // Loop to insert nodes in// Binary Tree in level orderfor(let i=0;i<size;i++) root = insert(root, arr[i]) inorder(root) // This code is contributed by shinjanpatra </script> 12 6 5 8 1 7 9 29AjayKumar sanjeev2552 udaykumar12381 shinjanpatra Binary Tree tree-level-order Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Mar, 2022" }, { "code": null, "e": 135, "s": 28, "text": "Given an array of integers, the task is to construct a binary tree in level order fashion using Recursion." }, { "code": null, "e": 145, "s": 135, "text": "Examples " }, { "code": null, "e": 198, "s": 145, "text": "Given an array arr[] = {15, 10, 20, 8, 12, 16, 25} " }, { "code": null, "e": 359, "s": 200, "text": "Approach: Idea is to keep track of the number of child nodes in the left sub-tree and right sub-tree and then take the decision on the basis of these counts. " }, { "code": null, "e": 524, "s": 359, "text": "When the count of children nodes in left and right sub-tree are equal, then the node has to be inserted in left sub-tree by creating a new level in the binary tree." }, { "code": null, "e": 860, "s": 524, "text": "When the count of children nodes in the left sub-tree is greater than the count of the children nodes in the right sub-tree then there are two cases. When the left sub-tree is perfect binary tree, then node is to be inserted in right sub-tree.When left sub-tree is not perfect binary tree, then node is to be inserted in left sub-tree." }, { "code": null, "e": 954, "s": 860, "text": "When the left sub-tree is perfect binary tree, then node is to be inserted in right sub-tree." }, { "code": null, "e": 1047, "s": 954, "text": "When left sub-tree is not perfect binary tree, then node is to be inserted in left sub-tree." }, { "code": null, "e": 1140, "s": 1047, "text": "A perfect binary tree with n levels have 2(n-1) nodes with all the leaf nodes at same level." }, { "code": null, "e": 1191, "s": 1140, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 1195, "s": 1191, "text": "C++" }, { "code": null, "e": 1200, "s": 1195, "text": "Java" }, { "code": null, "e": 1208, "s": 1200, "text": "Python3" }, { "code": null, "e": 1211, "s": 1208, "text": "C#" }, { "code": null, "e": 1222, "s": 1211, "text": "Javascript" }, { "code": "// C++ implementation to construct// Binary Tree in level order fashion#include <iostream>using namespace std; // Structure of the Node of Binary tree// with count of Children nodes in// left sub-tree and right sub-tree.struct Node { int data; int rcount; int lcount; struct Node* left; struct Node* right;}; // Function to check whether the given// Binary tree is a perfect binary tree// using the no. of nodes in tree.bool isPBT(int count){ count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false;} // Function to create a new Nodestruct Node* newNode(int data){ struct Node* temp = (struct Node*)malloc( sizeof(struct Node) ); temp->data = data; temp->right = NULL; temp->left = NULL; temp->rcount = 0; temp->lcount = 0;} // Recursive function to insert// elements in a binary treestruct Node* insert(struct Node* root, int data){ // Condition when root is NULL if (root == NULL) { struct Node* n = newNode(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root->rcount == root->lcount) { root->left = insert(root->left, data); root->lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root->rcount < root->lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root->lcount)) { root->right = insert(root->right, data); root->rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root->left = insert(root->left, data); root->lcount += 1; } } return root;} // Function for inorder Traversal of tree.void inorder(struct Node* root){ if (root != NULL) { inorder(root->left); cout << root->data << \" \"; inorder(root->right); }} // Driver Codeint main(){ int arr[] = { 8, 6, 7, 12, 5, 1, 9 }; int size = sizeof(arr) / sizeof(int); struct Node* root = NULL; // Loop to insert nodes in // Binary Tree in level order for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); return 0;}", "e": 3768, "s": 1222, "text": null }, { "code": "// Java implementation to construct// Binary Tree in level order fashion class Node { int data; int rcount; int lcount; Node left; Node right; Node(int data) { this.data = data; this.rcount = this.lcount = 0; this.left = this.right = null; } // Function for inorder Traversal of tree. static void inorder(Node root) { if (root != null) { inorder(root.left); System.out.print(root.data + \" \"); inorder(root.right); } } // Function to check whether the given // Binary tree is a perfect binary tree // using the no. of nodes in tree. static boolean isPBT(int count) { count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false; } // Recursive function to insert // elements in a binary tree static Node insert(Node root, int data) { // Condition when root is NULL if (root == null) { Node n = new Node(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount) { root.left = insert(root.left, data); root.lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)) { root.right = insert(root.right, data); root.rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root.left = insert(root.left, data); root.lcount += 1; } } return root; } // Driver Code public static void main(String args[]) { int arr[] = { 8, 6, 7, 12, 5, 1, 9 }; int size = 7; Node root = null; // Loop to insert nodes in // Binary Tree in level order Traversal for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); }}", "e": 6319, "s": 3768, "text": null }, { "code": "# Python3 implementation to construct# Binary Tree in level order fashion # Structure of the Node of Binary tree# with count of Children nodes in# left sub-tree and right sub-tree.class Node: def __init__(self, data): self.data = data self.rcount = 0 self.lcount = 0 self.left = None self.right = None # Function to check whether the given# Binary tree is a perfect binary tree# using the no. of nodes in tree.def isPBT(count: int) -> bool: count = count + 1 # Loop to check the count is in # the form of 2^(n-1) while (count % 2 == 0): count = count / 2 if (count == 1): return True else: return False # Recursive function to insert# elements in a binary treedef insert(root: Node, data: int) -> Node: # Condition when root is NULL if (root is None): n = Node(data) return n # Condition when count of left sub-tree # nodes is equal to the count # of right sub-tree nodes if (root.rcount == root.lcount): root.left = insert(root.left, data) root.lcount += 1 # Condition when count of left sub-tree # nodes is greater than # the right sub-tree nodes elif (root.rcount < root.lcount): # Condition when left Sub-tree is # Perfect Binary Tree then Insert # in right sub-tree. if (isPBT(root.lcount)): root.right = insert(root.right, data) root.rcount += 1 # If Left Sub-tree is not Perfect # Binary Tree then Insert in left sub-tree else: root.left = insert(root.left, data) root.lcount += 1 return root # Function for inorder Traversal of tree.def inorder(root: Node) -> None: if root != None: inorder(root.left) print(root.data, end = \" \") inorder(root.right) # Driver Codeif __name__ == \"__main__\": arr = [ 8, 6, 7, 12, 5, 1, 9 ] size = len(arr) root = None # Loop to insert nodes in # Binary Tree in level order for i in range(size): root = insert(root, arr[i]) inorder(root) # This code is contributed by sanjeev2552", "e": 8455, "s": 6319, "text": null }, { "code": "// C# implementation to construct// Binary Tree in level order fashionusing System; class Node { public int data; public int rcount; public int lcount; public Node left; public Node right; public Node(int data) { this.data = data; this.rcount = this.lcount = 0; this.left = this.right = null; } // Function for inorder Traversal of tree. static void inorder(Node root) { if (root != null) { inorder(root.left); Console.Write(root.data + \" \"); inorder(root.right); } } // Function to check whether the given // Binary tree is a perfect binary tree // using the no. of nodes in tree. static bool isPBT(int count) { count = count + 1; // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2; if (count == 1) return true; else return false; } // Recursive function to insert // elements in a binary tree static Node insert(Node root, int data) { // Condition when root is NULL if (root == null) { Node n = new Node(data); return n; } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount) { root.left = insert(root.left, data); root.lcount += 1; } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount) { // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)) { root.right = insert(root.right, data); root.rcount += 1; } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else { root.left = insert(root.left, data); root.lcount += 1; } } return root; } // Driver Code public static void Main(String []args) { int []arr = { 8, 6, 7, 12, 5, 1, 9 }; int size = 7; Node root = null; // Loop to insert nodes in // Binary Tree in level order Traversal for (int i = 0; i < size; i++) root = insert(root, arr[i]); inorder(root); }} // This code is contributed by 29AjayKumar", "e": 11105, "s": 8455, "text": null }, { "code": "<script> // JavaScript implementation to construct// Binary Tree in level order fashion // Structure of the Node of Binary tree// with count of Children nodes in// left sub-tree and right sub-tree.class Node{ constructor(data){ this.data = data this.rcount = 0 this.lcount = 0 this.left = null this.right = null }} // Function to check whether the given// Binary tree is a perfect binary tree// using the no. of nodes in tree.function isPBT(count){ count = count + 1 // Loop to check the count is in // the form of 2^(n-1) while (count % 2 == 0) count = count / 2 if (count == 1) return true else return false} // Recursive function to insert// elements in a binary treefunction insert(root, data){ // Condition when root is NULL if (!root){ let n = new Node(data) return n } // Condition when count of left sub-tree // nodes is equal to the count // of right sub-tree nodes if (root.rcount == root.lcount){ root.left = insert(root.left, data) root.lcount += 1 } // Condition when count of left sub-tree // nodes is greater than // the right sub-tree nodes else if (root.rcount < root.lcount){ // Condition when left Sub-tree is // Perfect Binary Tree then Insert // in right sub-tree. if (isPBT(root.lcount)){ root.right = insert(root.right, data) root.rcount += 1 } // If Left Sub-tree is not Perfect // Binary Tree then Insert in left sub-tree else{ root.left = insert(root.left, data) root.lcount += 1 } } return root} // Function for inorder Traversal of tree.function inorder(root){ if(root){ inorder(root.left) document.write(root.data,\" \") inorder(root.right) }} // Driver Code let arr = [ 8, 6, 7, 12, 5, 1, 9 ]let size = arr.lengthlet root = null // Loop to insert nodes in// Binary Tree in level orderfor(let i=0;i<size;i++) root = insert(root, arr[i]) inorder(root) // This code is contributed by shinjanpatra </script>", "e": 13252, "s": 11105, "text": null }, { "code": null, "e": 13267, "s": 13252, "text": "12 6 5 8 1 7 9" }, { "code": null, "e": 13281, "s": 13269, "text": "29AjayKumar" }, { "code": null, "e": 13293, "s": 13281, "text": "sanjeev2552" }, { "code": null, "e": 13308, "s": 13293, "text": "udaykumar12381" }, { "code": null, "e": 13321, "s": 13308, "text": "shinjanpatra" }, { "code": null, "e": 13333, "s": 13321, "text": "Binary Tree" }, { "code": null, "e": 13350, "s": 13333, "text": "tree-level-order" }, { "code": null, "e": 13355, "s": 13350, "text": "Tree" }, { "code": null, "e": 13360, "s": 13355, "text": "Tree" } ]
What is Vectorization in Machine Learning? | by Jalal Mansoori | Towards Data Science
Make your code execute fast using vectorization What is Vectorization?How Vectorization is important in Machine learning?Example: Unvectorized Vs Vectorized ImplementationAdvantages of Vectorized ImplementationDemonstration on jupyter notebook What is Vectorization? How Vectorization is important in Machine learning? Example: Unvectorized Vs Vectorized Implementation Advantages of Vectorized Implementation Demonstration on jupyter notebook The first time when I learned about the concept of Vectorization it was when I was learning the most well-known course Machine learning by Prof Andrew Ng on the Coursera platform. According to Prof Andrew Ng : “ The ability to perform Vectorization has become a key skill “ So let’s learn this skill and include it into our tools box :) Vectorization is a technique by which you can make your code execute fast. It is a very interesting and important way to optimize algorithms when you are implementing it from scratch. Now, with the help of highly optimized numerical linear algebra libraries in C/C++, Octave/Matlab, Python, ...etc. We can make our code run efficiently. Thanks to people specializing in numerical computing! In this tutorial, we will play with : Numpy: Fast Numerical Computing Library in Python Just like in the real-world we are interested in solving any kind of problem efficiently in such a way that the amount of error is reduced as much as possible. In machine learning, there’s a concept of an optimization algorithm that tries to reduce the error and computes to get the best parameters for the machine learning model. So by using a vectorized implementation in an optimization algorithm we can make the process of computation much faster compared to Unvectorized Implementation. A basic example of Optimization Algorithm: Gradient Descent Now let’s first play with Numpy to get some idea about using highly optimized computing library With Numpy: It took 1.52 ms to mean time per loop Without Numpy: It took 69.9 ms to mean time per loop # With Python Listsa=list(range(1000000)) #10^6 numbers generated%timeit [val + 5 for val in a] #Computing Element Wise Operation# With Numpy Arraysimport numpy as npa=np.array(a) #Converting into numpy array type%timeit a+5 range(): range function is used to generate a sequence of numbers over time %timeit: It is an ipython magic function that can be used to time a particular piece of code. Let’s understand the concept of vectorization using hypothesis function of linear regression in which theta represents weights/coefficients and x represents features Now there are two ways we can implement the above function : Using For loopsUsing Vectorization Using For loops Using Vectorization First, let’s generate random numbers for theta and x vectors n=10000# Generate n random numbers between 0 - 1theta = np.random.rand(n)#Generate n random integers between 0 - 100 x = np.random.randint(0, 100, n) Now observe the difference between Unvectorized vs Vectorized Code Both implementations give us the same output but the question is how efficiently one computes? Using Unvectorized Code: It took 6.46 ms to mean time per loop Using Vectorized Code: It took 18.8 μs to mean time per loop # Unvectorizeddef unvectorized(n, theta, x): prediction= 0.0 for j in range(n): prediction= prediction + theta[j]*x[j] return prediction# Vectorizeddef vectorized(theta, x): prediction= 0.0 prediction = np.dot(theta.transpose() , x) return prediction#Comparing Performance%timeit unvectorized(n, theta, x)%timeit vectorized(theta, x) Our code runs efficientlyOur code becomes simpler and easy to debug Our code runs efficiently Our code becomes simpler and easy to debug All the code used in this tutorial is available on my GitHub account Click Here In this tutorial, you learned about the vectorization technique that is one of the ways to make your code efficient. See you in the next tutorial :) Gmail-> [email protected] Github -> https://github.com/jalalmansoori19 https://speakerdeck.com/jakevdp/losing-your-loops-fast-numerical-computing-with-numpy-pycon-2015Machine Learning Course on Coursera by Prof Andrew Ng https://speakerdeck.com/jakevdp/losing-your-loops-fast-numerical-computing-with-numpy-pycon-2015 Machine Learning Course on Coursera by Prof Andrew Ng
[ { "code": null, "e": 220, "s": 172, "text": "Make your code execute fast using vectorization" }, { "code": null, "e": 416, "s": 220, "text": "What is Vectorization?How Vectorization is important in Machine learning?Example: Unvectorized Vs Vectorized ImplementationAdvantages of Vectorized ImplementationDemonstration on jupyter notebook" }, { "code": null, "e": 439, "s": 416, "text": "What is Vectorization?" }, { "code": null, "e": 491, "s": 439, "text": "How Vectorization is important in Machine learning?" }, { "code": null, "e": 542, "s": 491, "text": "Example: Unvectorized Vs Vectorized Implementation" }, { "code": null, "e": 582, "s": 542, "text": "Advantages of Vectorized Implementation" }, { "code": null, "e": 616, "s": 582, "text": "Demonstration on jupyter notebook" }, { "code": null, "e": 796, "s": 616, "text": "The first time when I learned about the concept of Vectorization it was when I was learning the most well-known course Machine learning by Prof Andrew Ng on the Coursera platform." }, { "code": null, "e": 826, "s": 796, "text": "According to Prof Andrew Ng :" }, { "code": null, "e": 890, "s": 826, "text": "“ The ability to perform Vectorization has become a key skill “" }, { "code": null, "e": 953, "s": 890, "text": "So let’s learn this skill and include it into our tools box :)" }, { "code": null, "e": 1137, "s": 953, "text": "Vectorization is a technique by which you can make your code execute fast. It is a very interesting and important way to optimize algorithms when you are implementing it from scratch." }, { "code": null, "e": 1290, "s": 1137, "text": "Now, with the help of highly optimized numerical linear algebra libraries in C/C++, Octave/Matlab, Python, ...etc. We can make our code run efficiently." }, { "code": null, "e": 1344, "s": 1290, "text": "Thanks to people specializing in numerical computing!" }, { "code": null, "e": 1382, "s": 1344, "text": "In this tutorial, we will play with :" }, { "code": null, "e": 1432, "s": 1382, "text": "Numpy: Fast Numerical Computing Library in Python" }, { "code": null, "e": 1592, "s": 1432, "text": "Just like in the real-world we are interested in solving any kind of problem efficiently in such a way that the amount of error is reduced as much as possible." }, { "code": null, "e": 1763, "s": 1592, "text": "In machine learning, there’s a concept of an optimization algorithm that tries to reduce the error and computes to get the best parameters for the machine learning model." }, { "code": null, "e": 1924, "s": 1763, "text": "So by using a vectorized implementation in an optimization algorithm we can make the process of computation much faster compared to Unvectorized Implementation." }, { "code": null, "e": 1984, "s": 1924, "text": "A basic example of Optimization Algorithm: Gradient Descent" }, { "code": null, "e": 2080, "s": 1984, "text": "Now let’s first play with Numpy to get some idea about using highly optimized computing library" }, { "code": null, "e": 2130, "s": 2080, "text": "With Numpy: It took 1.52 ms to mean time per loop" }, { "code": null, "e": 2183, "s": 2130, "text": "Without Numpy: It took 69.9 ms to mean time per loop" }, { "code": null, "e": 2408, "s": 2183, "text": "# With Python Listsa=list(range(1000000)) #10^6 numbers generated%timeit [val + 5 for val in a] #Computing Element Wise Operation# With Numpy Arraysimport numpy as npa=np.array(a) #Converting into numpy array type%timeit a+5" }, { "code": null, "e": 2484, "s": 2408, "text": "range(): range function is used to generate a sequence of numbers over time" }, { "code": null, "e": 2578, "s": 2484, "text": "%timeit: It is an ipython magic function that can be used to time a particular piece of code." }, { "code": null, "e": 2744, "s": 2578, "text": "Let’s understand the concept of vectorization using hypothesis function of linear regression in which theta represents weights/coefficients and x represents features" }, { "code": null, "e": 2805, "s": 2744, "text": "Now there are two ways we can implement the above function :" }, { "code": null, "e": 2840, "s": 2805, "text": "Using For loopsUsing Vectorization" }, { "code": null, "e": 2856, "s": 2840, "text": "Using For loops" }, { "code": null, "e": 2876, "s": 2856, "text": "Using Vectorization" }, { "code": null, "e": 2937, "s": 2876, "text": "First, let’s generate random numbers for theta and x vectors" }, { "code": null, "e": 3087, "s": 2937, "text": "n=10000# Generate n random numbers between 0 - 1theta = np.random.rand(n)#Generate n random integers between 0 - 100 x = np.random.randint(0, 100, n)" }, { "code": null, "e": 3154, "s": 3087, "text": "Now observe the difference between Unvectorized vs Vectorized Code" }, { "code": null, "e": 3249, "s": 3154, "text": "Both implementations give us the same output but the question is how efficiently one computes?" }, { "code": null, "e": 3312, "s": 3249, "text": "Using Unvectorized Code: It took 6.46 ms to mean time per loop" }, { "code": null, "e": 3373, "s": 3312, "text": "Using Vectorized Code: It took 18.8 μs to mean time per loop" }, { "code": null, "e": 3755, "s": 3373, "text": "# Unvectorizeddef unvectorized(n, theta, x): prediction= 0.0 for j in range(n): prediction= prediction + theta[j]*x[j] return prediction# Vectorizeddef vectorized(theta, x): prediction= 0.0 prediction = np.dot(theta.transpose() , x) return prediction#Comparing Performance%timeit unvectorized(n, theta, x)%timeit vectorized(theta, x)" }, { "code": null, "e": 3823, "s": 3755, "text": "Our code runs efficientlyOur code becomes simpler and easy to debug" }, { "code": null, "e": 3849, "s": 3823, "text": "Our code runs efficiently" }, { "code": null, "e": 3892, "s": 3849, "text": "Our code becomes simpler and easy to debug" }, { "code": null, "e": 3972, "s": 3892, "text": "All the code used in this tutorial is available on my GitHub account Click Here" }, { "code": null, "e": 4089, "s": 3972, "text": "In this tutorial, you learned about the vectorization technique that is one of the ways to make your code efficient." }, { "code": null, "e": 4121, "s": 4089, "text": "See you in the next tutorial :)" }, { "code": null, "e": 4155, "s": 4121, "text": "Gmail-> [email protected]" }, { "code": null, "e": 4200, "s": 4155, "text": "Github -> https://github.com/jalalmansoori19" }, { "code": null, "e": 4350, "s": 4200, "text": "https://speakerdeck.com/jakevdp/losing-your-loops-fast-numerical-computing-with-numpy-pycon-2015Machine Learning Course on Coursera by Prof Andrew Ng" }, { "code": null, "e": 4447, "s": 4350, "text": "https://speakerdeck.com/jakevdp/losing-your-loops-fast-numerical-computing-with-numpy-pycon-2015" } ]
How to select a value from a static dropdown in Selenium?
The various methods available under Select class in Selenium to select a value from a static dropdown. They are as listed below − selectByVisibleText(String args)This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values.Syntax −Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByVisibleText("Selenium"); selectByVisibleText(String args) This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values. Syntax − Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByVisibleText("Selenium"); selectByIndex(String args) selectByIndex(String args) This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values. This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values. Syntax −Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByIndex(1); Syntax − Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByIndex(1); selectByValue(String args)This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values.Syntax −Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByValue(“Testing”); selectByValue(String args) This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values. Syntax − Select s = new Select(driver.findElement(By.id("<< id exp>>"))); s.selectByValue(“Testing”); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; import org.openqa.selenium.support.ui.Select; public class SelectOptions{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/tutor_connect/index.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); Select s = new Select(driver.findElement(By.xpath("//select[@name=’selType’]"))); // select an option by value method s.selectByValue("name"); Thread.sleep(1000); // select an option by index method s.selectByIndex(0); Thread.sleep(1000); // select an option by visible text method s.selectByVisibleText("By Subject"); Thread.sleep(1000); driver.quit(); } }
[ { "code": null, "e": 1135, "s": 1062, "text": "The various methods available under Select class in Selenium to select a" }, { "code": null, "e": 1192, "s": 1135, "text": "value from a static dropdown. They are as listed below −" }, { "code": null, "e": 1539, "s": 1192, "text": "selectByVisibleText(String args)This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values.Syntax −Select s = new Select(driver.findElement(By.id(\"<< id exp>>\")));\ns.selectByVisibleText(\"Selenium\");" }, { "code": null, "e": 1572, "s": 1539, "text": "selectByVisibleText(String args)" }, { "code": null, "e": 1780, "s": 1572, "text": "This method is most commonly used in dropdowns. It is very simple to select an option in a dropdown and multiple selection box with this method. It takes a String parameter as argument and returns no values." }, { "code": null, "e": 1789, "s": 1780, "text": "Syntax −" }, { "code": null, "e": 1889, "s": 1789, "text": "Select s = new Select(driver.findElement(By.id(\"<< id exp>>\")));\ns.selectByVisibleText(\"Selenium\");" }, { "code": null, "e": 1916, "s": 1889, "text": "selectByIndex(String args)" }, { "code": null, "e": 1943, "s": 1916, "text": "selectByIndex(String args)" }, { "code": null, "e": 2073, "s": 1943, "text": "This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values." }, { "code": null, "e": 2203, "s": 2073, "text": "This method takes the index of the option to select in the dropdown. It takes an int parameter as argument and returns no values." }, { "code": null, "e": 2296, "s": 2203, "text": "Syntax −Select s = new Select(driver.findElement(By.id(\"<< id exp>>\")));\ns.selectByIndex(1);" }, { "code": null, "e": 2305, "s": 2296, "text": "Syntax −" }, { "code": null, "e": 2390, "s": 2305, "text": "Select s = new Select(driver.findElement(By.id(\"<< id exp>>\")));\ns.selectByIndex(1);" }, { "code": null, "e": 2648, "s": 2390, "text": "selectByValue(String args)This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values.Syntax −Select s = new Select(driver.findElement(By.id(\"<< id exp>>\")));\ns.selectByValue(“Testing”);" }, { "code": null, "e": 2675, "s": 2648, "text": "selectByValue(String args)" }, { "code": null, "e": 2807, "s": 2675, "text": "This method takes the value of the option to select in the dropdown. It takes a String parameter as argument and returns no values." }, { "code": null, "e": 2816, "s": 2807, "text": "Syntax −" }, { "code": null, "e": 2909, "s": 2816, "text": "Select s = new Select(driver.findElement(By.id(\"<< id exp>>\")));\ns.selectByValue(“Testing”);" }, { "code": null, "e": 3989, "s": 2909, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\nimport org.openqa.selenium.support.ui.Select;\npublic class SelectOptions{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/tutor_connect/index.php\"; driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n Select s = new Select(driver.findElement(By.xpath(\"//select[@name=’selType’]\")));\n // select an option by value method\n s.selectByValue(\"name\");\n Thread.sleep(1000);\n // select an option by index method\n s.selectByIndex(0);\n Thread.sleep(1000);\n // select an option by visible text method\n s.selectByVisibleText(\"By Subject\");\n Thread.sleep(1000);\n driver.quit();\n }\n}" } ]
Changing the Granularity of Data in Power BI | by Salvatore Cagliari | Towards Data Science
I use the Contoso sample dataset, like in my previous articles. You can download the ContosoRetailDW Dataset for free from Microsoft here. The Contoso Data can be freely used under the MIT License, as described here. Now, let’s look at the Online Sales Fact table (FactOnlineSales). When you look at the following picture, you can see that each order has one or more rows. Each row has a SalesOrderLineNumber, and each row has a ProductID. Now, I have one of the following problems: Too much data — I have too much data, and I want to reduce the amount of data to save space and memory to improve performance Reporting requirements — I need to create reports based on the Orders and Product Categories. I don’t need the highest granularity, and I want to remove the unnecessary details from my data So, I want to reduce the Granularity from Product to Product Subcategory and from OrderLineNumber to OrderNumber. Because of this reduction, I have to join the Product table to map the Product Subcategory. This Aggregation will reduce the dataset from 12'627'608 to 3'432'947 rows with retaining the SalesOrderNumber, the CustomerKey and other Dimension references. You can use one of three methods to reduce the granularity of your data: Change it when retrieving the data from the source systemChange it during the import in Power QueryChange it in DAX after loading the data in Power BI Change it when retrieving the data from the source system Change it during the import in Power Query Change it in DAX after loading the data in Power BI From these three variants, I like the first the most. My Mantra is: “If you need to change your data, do it as early as possible”. But let’s take a look at each of those variants in detail: If your source system is a relational database, write a SQL Query to aggregate your data. The Aggregation Query will look like this: SELECT [FOS].[DateKey], [FOS].[StoreKey], [FOS].[PromotionKey], [FOS].[CurrencyKey],[FOS].[CustomerKey], [P].[ProductSubcategoryKey], [FOS].[SalesOrderNumber],SUM([FOS].[SalesQuantity]) AS [SalesQuantity],SUM([FOS].[SalesAmount]) AS [SalesAmount],SUM([FOS].[ReturnQuantity]) AS [ReturnQuantity],SUM([FOS].[ReturnAmount]) AS [ReturnAmount],SUM([FOS].[DiscountQuantity]) AS [DiscountQuantity],SUM([FOS].[DiscountAmount]) AS [DiscountAmount],SUM([FOS].[TotalCost]) AS [TotalCost],SUM([FOS].[UnitCost]) AS [UnitCost],SUM([FOS].[UnitPrice]) AS [UnitPrice],[FOS].[UpdateDate], [FOS].[DueDate], [FOS].[ShipDate]FROM [dbo].[FactOnlineSales] AS [FOS] LEFT OUTER JOIN [dbo].[DimProduct] AS [P] ON [P].[ProductKey] = [FOS].[ProductKey]GROUP BY [FOS].[DateKey], [FOS].[StoreKey], [FOS].[PromotionKey], [FOS].[CurrencyKey], [FOS].[CustomerKey], [P].[ProductSubcategoryKey], [FOS].[SalesOrderNumber],[FOS].[UpdateDate], [FOS].[DueDate], [FOS].[ShipDate]; I aggregate all Measures with a SUM after analyzing the data. You need to select the correct aggregation function carefully, as a simple SUM is not always the right choice.And sometimes, you cannot simply aggregate your data. Possibly you need to do calculations with the aggregated data to get the correct Results. If the Source is not a relational database, try to prepare the data as much as possible in advance in the source system to reduce the transformation work in Power BI. Some application allows you to create Aggregation- or Reporting-Views over the data, which you can consume in Power BI. If none of this is possible, Power Query is the next step. You can use the Group By function in Power Query to reduce the granularity of your data. This feature calculates the Grouping and Aggregation in Power Query and loads the data into Power BI. However, this approach has the drawback that the Group By function doesn’t fold the Query back to SQL Server. This means that it has to load the entire dataset in the Power Query Engine. Only after all the data is loaded, it can perform the Grouping and Aggregations. From the perspective of Power BI, it makes no difference between using a Query/View in the Datasource or Power Query. Power BI still gets only the reduced dataset with the aggregated figures. Sometimes you need to do calculations on both the higher and the lower Granularity levels. In such a case, you need to have both tables, and you have to change your Data model to accommodate all requirements. In my case, my PBIX file needed ~15% more space after adding the aggregated table and a new table for the Product Categorizations. But, sometimes, this is not an option, as you may have much more data in your Fact table, and you cannot simply add one more large table to your model for various reasons. When you have huge Datasets, you can read my last article on this topic: towardsdatascience.com On the other side, if you have only a small amount of data, you may want to have only one Fact table, and you want to change the granularity on the fly in a Measure. Let’s look into this approach. Unfortunately, it’s not trivial to author a Measure while changing the granularity of your data.There are a lot of variables to consider. Let’s look at the following question: What is the Average Sales Amount overall Orders?I want to consider the entire orders, not the Sales Amount of each order line. So, I had to aggregate the Sum of SalesAmount per Order number. Then calculate the Average over the result. The Measure itself is not that difficult: AvgSalesOverOrders =VAR SalesPerOrder = SUMMARIZE(‘Online Sales’ ,’Online Sales’[Sales Order Number] ,”SalesAmountPerOrder”, SUMX(‘Online Sales’, [SalesAmount]))RETURNAVERAGEX(SalesPerOrder ,[SalesAmountPerOrder]) My first approach was to use AVERAGE() over the Table Variable SalesPerOrder.Unfortunately, AVERAGE can only work with a materialized table, which can also be a DAX table. But, I didn’t want to create a calculated DAX-table to solve this challenge. I aimed to create a DAX Measure without adding more tables to my data model. In this case, AVERAGEX() was the solution. But is the result correct?Well, it depends. As you might have read in one of my last Articles, there are multiple ways to calculate an Average: towardsdatascience.com In this case, it depends on the Granularity of the Data if the result is correct. I imported the aggregated data, prepared with the Power Query method described above as a new table named “‘Online Sales Aggr” in my data model. Look at the following Query: DEFINE MEASURE ‘Online Sales’[AvgSalesOverOrders] = VAR SalesPerOrder = SUMMARIZE(‘Online Sales’ ,’Online Sales’[Sales Order Number] ,”SalesAmountPerOrder” ,SUMX(‘Online Sales’, [SalesAmount]) ) RETURN AVERAGEX(SalesPerOrder ,[SalesAmountPerOrder]) MEASURE ‘Online Sales Aggr’[AvgSalesOverOrders_Aggr] = AVERAGE(‘Online Sales Aggr’[SalesAmount]) EVALUATE ROW( “AvgSalesOverOrders”, [AvgSalesOverOrders], “AvgSalesOverOrders_Aggr”, [AvgSalesOverOrders_Aggr] ) And here is the result: Why are they different? The first Measure aggregates the Data from the highest granularity, with all the Details, up to each Order Number. The second uses the pre-aggregated Data. But this table contains Details per Customer, Stores, promotions, etc. Therefore the table contains much more Details than the table generated in the Measure. As a consequence, the Pre-Aggregated Data have lower Numbers in the Sales Amount columns. This is the reason why the Average is lower. When I change the Granularity of the second Measure to the same level, the result is much more similar. Here is the full Query: DEFINE MEASURE ‘Online Sales’[AvgSalesOverOrders] = VAR SalesPerOrder = SUMMARIZE(‘Online Sales’ ,’Online Sales’[Sales Order Number] ,”SalesAmountPerOrder” ,SUMX(‘Online Sales’, [SalesAmount]) ) RETURN AVERAGEX(SalesPerOrder ,[SalesAmountPerOrder])MEASURE ‘Online Sales Aggr’[AvgSalesOverOrders_Aggr] = AVERAGE(‘Online Sales Aggr’[SalesAmount]) MEASURE ‘Online Sales’[AvgSalesOverOrders_Aggr_2] = VAR SalesPerOrder = SUMMARIZE(‘Online Sales Aggr’ ,’Online Sales Aggr’[Sales Order Number] ,”SalesAmountPerOrder” ,SUMX(‘Online Sales Aggr’ [SalesAmount]) ) RETURN AVERAGEX(SalesPerOrder ,[SalesAmountPerOrder]) EVALUATE ROW( “AvgSalesOverOrders”, [AvgSalesOverOrders], “AvgSalesOverOrders_Aggr”, [AvgSalesOverOrders_Aggr], “AvgSalesOverOrders_Aggr_2”, [AvgSalesOverOrders_Aggr_2] ) And here is the result: Anyway, the results can’t be equal as the base values are different. How the values per row can influence the outcome is only one variable of many. You need to validate the results and change your approach accordingly to get the correct result from your calculations. I have shown you three different approaches: Prepare the data in the SourceManipulate the Data in Power QueryCreate a Measure and change the granularity there Prepare the data in the Source Manipulate the Data in Power Query Create a Measure and change the granularity there I prefer the first option over the others as, in most cases, it is the most efficient way to do it. In case that your Source is a database, you can pass a Query to the Source and calculate the aggregations with it. The second option has some limitations. As mentioned above, Power Query cannot pass the Grouping and Aggregation of the data to SQL Server with Query folding. Therefore Power Query will always read the entire dataset and perform the Aggregation in Power Query, taking time and resources. You have to write a Measure when you want to keep the data at the lowest granularity.But caution. This approach can be the least performant solution. The first Measure shown above took almost two seconds to compute the result in a query showing only the total of the result: But it takes over 15 seconds when using it in a Matrix: The simpler version of the Measure on the Aggregated data took 65 ms to complete in Power BI: But the last Measure, which calculated the Average in the same way as the first Measure, took just ~25% less time to complete than the first one: Here from the Query: And here in Power BI, with the use of the same Matrix Visual as above: The correct solution depends on the requirements of your users. If those are not clear, you need to show them the differences and ask for a concise answer, which version is the correct one. The Average is only one example of calculations. But you need to clarify the requirement for all calculations bases on aggregated data. The same applies to the approach to aggregate the data in the first place. You may load the data twice. Once with all Details and once in an aggregated form to facilitate some calculations. But, take care of how you perform the aggregations. The wrong method can lead to bad results. I hope that I was able to give you some inspiration on how to approach such a scenario.
[ { "code": null, "e": 311, "s": 172, "text": "I use the Contoso sample dataset, like in my previous articles. You can download the ContosoRetailDW Dataset for free from Microsoft here." }, { "code": null, "e": 389, "s": 311, "text": "The Contoso Data can be freely used under the MIT License, as described here." }, { "code": null, "e": 455, "s": 389, "text": "Now, let’s look at the Online Sales Fact table (FactOnlineSales)." }, { "code": null, "e": 612, "s": 455, "text": "When you look at the following picture, you can see that each order has one or more rows. Each row has a SalesOrderLineNumber, and each row has a ProductID." }, { "code": null, "e": 655, "s": 612, "text": "Now, I have one of the following problems:" }, { "code": null, "e": 781, "s": 655, "text": "Too much data — I have too much data, and I want to reduce the amount of data to save space and memory to improve performance" }, { "code": null, "e": 875, "s": 781, "text": "Reporting requirements — I need to create reports based on the Orders and Product Categories." }, { "code": null, "e": 971, "s": 875, "text": "I don’t need the highest granularity, and I want to remove the unnecessary details from my data" }, { "code": null, "e": 1177, "s": 971, "text": "So, I want to reduce the Granularity from Product to Product Subcategory and from OrderLineNumber to OrderNumber. Because of this reduction, I have to join the Product table to map the Product Subcategory." }, { "code": null, "e": 1337, "s": 1177, "text": "This Aggregation will reduce the dataset from 12'627'608 to 3'432'947 rows with retaining the SalesOrderNumber, the CustomerKey and other Dimension references." }, { "code": null, "e": 1410, "s": 1337, "text": "You can use one of three methods to reduce the granularity of your data:" }, { "code": null, "e": 1561, "s": 1410, "text": "Change it when retrieving the data from the source systemChange it during the import in Power QueryChange it in DAX after loading the data in Power BI" }, { "code": null, "e": 1619, "s": 1561, "text": "Change it when retrieving the data from the source system" }, { "code": null, "e": 1662, "s": 1619, "text": "Change it during the import in Power Query" }, { "code": null, "e": 1714, "s": 1662, "text": "Change it in DAX after loading the data in Power BI" }, { "code": null, "e": 1768, "s": 1714, "text": "From these three variants, I like the first the most." }, { "code": null, "e": 1845, "s": 1768, "text": "My Mantra is: “If you need to change your data, do it as early as possible”." }, { "code": null, "e": 1904, "s": 1845, "text": "But let’s take a look at each of those variants in detail:" }, { "code": null, "e": 1994, "s": 1904, "text": "If your source system is a relational database, write a SQL Query to aggregate your data." }, { "code": null, "e": 2037, "s": 1994, "text": "The Aggregation Query will look like this:" }, { "code": null, "e": 2988, "s": 2037, "text": "SELECT [FOS].[DateKey], [FOS].[StoreKey], [FOS].[PromotionKey], [FOS].[CurrencyKey],[FOS].[CustomerKey], [P].[ProductSubcategoryKey], [FOS].[SalesOrderNumber],SUM([FOS].[SalesQuantity]) AS [SalesQuantity],SUM([FOS].[SalesAmount]) AS [SalesAmount],SUM([FOS].[ReturnQuantity]) AS [ReturnQuantity],SUM([FOS].[ReturnAmount]) AS [ReturnAmount],SUM([FOS].[DiscountQuantity]) AS [DiscountQuantity],SUM([FOS].[DiscountAmount]) AS [DiscountAmount],SUM([FOS].[TotalCost]) AS [TotalCost],SUM([FOS].[UnitCost]) AS [UnitCost],SUM([FOS].[UnitPrice]) AS [UnitPrice],[FOS].[UpdateDate], [FOS].[DueDate], [FOS].[ShipDate]FROM [dbo].[FactOnlineSales] AS [FOS] LEFT OUTER JOIN [dbo].[DimProduct] AS [P] ON [P].[ProductKey] = [FOS].[ProductKey]GROUP BY [FOS].[DateKey], [FOS].[StoreKey], [FOS].[PromotionKey], [FOS].[CurrencyKey], [FOS].[CustomerKey], [P].[ProductSubcategoryKey], [FOS].[SalesOrderNumber],[FOS].[UpdateDate], [FOS].[DueDate], [FOS].[ShipDate];" }, { "code": null, "e": 3304, "s": 2988, "text": "I aggregate all Measures with a SUM after analyzing the data. You need to select the correct aggregation function carefully, as a simple SUM is not always the right choice.And sometimes, you cannot simply aggregate your data. Possibly you need to do calculations with the aggregated data to get the correct Results." }, { "code": null, "e": 3471, "s": 3304, "text": "If the Source is not a relational database, try to prepare the data as much as possible in advance in the source system to reduce the transformation work in Power BI." }, { "code": null, "e": 3591, "s": 3471, "text": "Some application allows you to create Aggregation- or Reporting-Views over the data, which you can consume in Power BI." }, { "code": null, "e": 3650, "s": 3591, "text": "If none of this is possible, Power Query is the next step." }, { "code": null, "e": 3739, "s": 3650, "text": "You can use the Group By function in Power Query to reduce the granularity of your data." }, { "code": null, "e": 3841, "s": 3739, "text": "This feature calculates the Grouping and Aggregation in Power Query and loads the data into Power BI." }, { "code": null, "e": 4109, "s": 3841, "text": "However, this approach has the drawback that the Group By function doesn’t fold the Query back to SQL Server. This means that it has to load the entire dataset in the Power Query Engine. Only after all the data is loaded, it can perform the Grouping and Aggregations." }, { "code": null, "e": 4301, "s": 4109, "text": "From the perspective of Power BI, it makes no difference between using a Query/View in the Datasource or Power Query. Power BI still gets only the reduced dataset with the aggregated figures." }, { "code": null, "e": 4392, "s": 4301, "text": "Sometimes you need to do calculations on both the higher and the lower Granularity levels." }, { "code": null, "e": 4510, "s": 4392, "text": "In such a case, you need to have both tables, and you have to change your Data model to accommodate all requirements." }, { "code": null, "e": 4641, "s": 4510, "text": "In my case, my PBIX file needed ~15% more space after adding the aggregated table and a new table for the Product Categorizations." }, { "code": null, "e": 4813, "s": 4641, "text": "But, sometimes, this is not an option, as you may have much more data in your Fact table, and you cannot simply add one more large table to your model for various reasons." }, { "code": null, "e": 4886, "s": 4813, "text": "When you have huge Datasets, you can read my last article on this topic:" }, { "code": null, "e": 4909, "s": 4886, "text": "towardsdatascience.com" }, { "code": null, "e": 5075, "s": 4909, "text": "On the other side, if you have only a small amount of data, you may want to have only one Fact table, and you want to change the granularity on the fly in a Measure." }, { "code": null, "e": 5106, "s": 5075, "text": "Let’s look into this approach." }, { "code": null, "e": 5244, "s": 5106, "text": "Unfortunately, it’s not trivial to author a Measure while changing the granularity of your data.There are a lot of variables to consider." }, { "code": null, "e": 5517, "s": 5244, "text": "Let’s look at the following question: What is the Average Sales Amount overall Orders?I want to consider the entire orders, not the Sales Amount of each order line. So, I had to aggregate the Sum of SalesAmount per Order number. Then calculate the Average over the result." }, { "code": null, "e": 5559, "s": 5517, "text": "The Measure itself is not that difficult:" }, { "code": null, "e": 5834, "s": 5559, "text": "AvgSalesOverOrders =VAR SalesPerOrder = SUMMARIZE(‘Online Sales’ ,’Online Sales’[Sales Order Number] ,”SalesAmountPerOrder”, SUMX(‘Online Sales’, [SalesAmount]))RETURNAVERAGEX(SalesPerOrder ,[SalesAmountPerOrder])" }, { "code": null, "e": 6006, "s": 5834, "text": "My first approach was to use AVERAGE() over the Table Variable SalesPerOrder.Unfortunately, AVERAGE can only work with a materialized table, which can also be a DAX table." }, { "code": null, "e": 6160, "s": 6006, "text": "But, I didn’t want to create a calculated DAX-table to solve this challenge. I aimed to create a DAX Measure without adding more tables to my data model." }, { "code": null, "e": 6203, "s": 6160, "text": "In this case, AVERAGEX() was the solution." }, { "code": null, "e": 6247, "s": 6203, "text": "But is the result correct?Well, it depends." }, { "code": null, "e": 6347, "s": 6247, "text": "As you might have read in one of my last Articles, there are multiple ways to calculate an Average:" }, { "code": null, "e": 6370, "s": 6347, "text": "towardsdatascience.com" }, { "code": null, "e": 6452, "s": 6370, "text": "In this case, it depends on the Granularity of the Data if the result is correct." }, { "code": null, "e": 6597, "s": 6452, "text": "I imported the aggregated data, prepared with the Power Query method described above as a new table named “‘Online Sales Aggr” in my data model." }, { "code": null, "e": 6626, "s": 6597, "text": "Look at the following Query:" }, { "code": null, "e": 7258, "s": 6626, "text": "DEFINE MEASURE ‘Online Sales’[AvgSalesOverOrders] = VAR SalesPerOrder = SUMMARIZE(‘Online Sales’ ,’Online Sales’[Sales Order Number] ,”SalesAmountPerOrder” ,SUMX(‘Online Sales’, [SalesAmount]) ) RETURN AVERAGEX(SalesPerOrder ,[SalesAmountPerOrder]) MEASURE ‘Online Sales Aggr’[AvgSalesOverOrders_Aggr] = AVERAGE(‘Online Sales Aggr’[SalesAmount]) EVALUATE ROW( “AvgSalesOverOrders”, [AvgSalesOverOrders], “AvgSalesOverOrders_Aggr”, [AvgSalesOverOrders_Aggr] )" }, { "code": null, "e": 7282, "s": 7258, "text": "And here is the result:" }, { "code": null, "e": 7306, "s": 7282, "text": "Why are they different?" }, { "code": null, "e": 7756, "s": 7306, "text": "The first Measure aggregates the Data from the highest granularity, with all the Details, up to each Order Number. The second uses the pre-aggregated Data. But this table contains Details per Customer, Stores, promotions, etc. Therefore the table contains much more Details than the table generated in the Measure. As a consequence, the Pre-Aggregated Data have lower Numbers in the Sales Amount columns. This is the reason why the Average is lower." }, { "code": null, "e": 7860, "s": 7756, "text": "When I change the Granularity of the second Measure to the same level, the result is much more similar." }, { "code": null, "e": 7884, "s": 7860, "text": "Here is the full Query:" }, { "code": null, "e": 9027, "s": 7884, "text": "DEFINE MEASURE ‘Online Sales’[AvgSalesOverOrders] = VAR SalesPerOrder = SUMMARIZE(‘Online Sales’ ,’Online Sales’[Sales Order Number] ,”SalesAmountPerOrder” ,SUMX(‘Online Sales’, [SalesAmount]) ) RETURN AVERAGEX(SalesPerOrder ,[SalesAmountPerOrder])MEASURE ‘Online Sales Aggr’[AvgSalesOverOrders_Aggr] = AVERAGE(‘Online Sales Aggr’[SalesAmount]) MEASURE ‘Online Sales’[AvgSalesOverOrders_Aggr_2] = VAR SalesPerOrder = SUMMARIZE(‘Online Sales Aggr’ ,’Online Sales Aggr’[Sales Order Number] ,”SalesAmountPerOrder” ,SUMX(‘Online Sales Aggr’ [SalesAmount]) ) RETURN AVERAGEX(SalesPerOrder ,[SalesAmountPerOrder]) EVALUATE ROW( “AvgSalesOverOrders”, [AvgSalesOverOrders], “AvgSalesOverOrders_Aggr”, [AvgSalesOverOrders_Aggr], “AvgSalesOverOrders_Aggr_2”, [AvgSalesOverOrders_Aggr_2] )" }, { "code": null, "e": 9051, "s": 9027, "text": "And here is the result:" }, { "code": null, "e": 9120, "s": 9051, "text": "Anyway, the results can’t be equal as the base values are different." }, { "code": null, "e": 9319, "s": 9120, "text": "How the values per row can influence the outcome is only one variable of many. You need to validate the results and change your approach accordingly to get the correct result from your calculations." }, { "code": null, "e": 9364, "s": 9319, "text": "I have shown you three different approaches:" }, { "code": null, "e": 9478, "s": 9364, "text": "Prepare the data in the SourceManipulate the Data in Power QueryCreate a Measure and change the granularity there" }, { "code": null, "e": 9509, "s": 9478, "text": "Prepare the data in the Source" }, { "code": null, "e": 9544, "s": 9509, "text": "Manipulate the Data in Power Query" }, { "code": null, "e": 9594, "s": 9544, "text": "Create a Measure and change the granularity there" }, { "code": null, "e": 9694, "s": 9594, "text": "I prefer the first option over the others as, in most cases, it is the most efficient way to do it." }, { "code": null, "e": 9809, "s": 9694, "text": "In case that your Source is a database, you can pass a Query to the Source and calculate the aggregations with it." }, { "code": null, "e": 9968, "s": 9809, "text": "The second option has some limitations. As mentioned above, Power Query cannot pass the Grouping and Aggregation of the data to SQL Server with Query folding." }, { "code": null, "e": 10097, "s": 9968, "text": "Therefore Power Query will always read the entire dataset and perform the Aggregation in Power Query, taking time and resources." }, { "code": null, "e": 10247, "s": 10097, "text": "You have to write a Measure when you want to keep the data at the lowest granularity.But caution. This approach can be the least performant solution." }, { "code": null, "e": 10372, "s": 10247, "text": "The first Measure shown above took almost two seconds to compute the result in a query showing only the total of the result:" }, { "code": null, "e": 10428, "s": 10372, "text": "But it takes over 15 seconds when using it in a Matrix:" }, { "code": null, "e": 10522, "s": 10428, "text": "The simpler version of the Measure on the Aggregated data took 65 ms to complete in Power BI:" }, { "code": null, "e": 10668, "s": 10522, "text": "But the last Measure, which calculated the Average in the same way as the first Measure, took just ~25% less time to complete than the first one:" }, { "code": null, "e": 10689, "s": 10668, "text": "Here from the Query:" }, { "code": null, "e": 10760, "s": 10689, "text": "And here in Power BI, with the use of the same Matrix Visual as above:" }, { "code": null, "e": 10950, "s": 10760, "text": "The correct solution depends on the requirements of your users. If those are not clear, you need to show them the differences and ask for a concise answer, which version is the correct one." }, { "code": null, "e": 11086, "s": 10950, "text": "The Average is only one example of calculations. But you need to clarify the requirement for all calculations bases on aggregated data." }, { "code": null, "e": 11161, "s": 11086, "text": "The same applies to the approach to aggregate the data in the first place." }, { "code": null, "e": 11276, "s": 11161, "text": "You may load the data twice. Once with all Details and once in an aggregated form to facilitate some calculations." }, { "code": null, "e": 11370, "s": 11276, "text": "But, take care of how you perform the aggregations. The wrong method can lead to bad results." } ]
Maximum Frequency Stack in C++
Suppose we want to implement one stack called FreqStack, Our FreqStack has two functions − push(x), This will push an integer x onto the stack. push(x), This will push an integer x onto the stack. pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned. pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned. So, if the input is like push some elements like 7, 9, 7, 9, 6, 7, then perform the pop operations four times, then the output will be 7,9,7,6 respectively. To solve this, we will follow these steps − Define one map cnt Define one map cnt Define one map sts Define one map sts maxFreq := 0 maxFreq := 0 Define a function push(), this will take x, Define a function push(), this will take x, (increase cnt[x] by 1) (increase cnt[x] by 1) maxFreq := maximum of maxFreq and cnt[x] maxFreq := maximum of maxFreq and cnt[x] insert x into sts[cnt[x]] insert x into sts[cnt[x]] Define a function pop() Define a function pop() maxKey := maxFreq maxKey := maxFreq x := top element of sts[maxKey] x := top element of sts[maxKey] delete element from sts[maxKey] delete element from sts[maxKey] if size of sts[maxKey] is same as 0, then −delete maxKey from sts(decrease maxFreq by 1) if size of sts[maxKey] is same as 0, then − delete maxKey from sts delete maxKey from sts (decrease maxFreq by 1) (decrease maxFreq by 1) (decrease cnt[x] by 1) (decrease cnt[x] by 1) return x return x Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class FreqStack { public: unordered_map <int ,int > cnt; unordered_map <int, stack <int> >sts; int maxFreq = 0; FreqStack() { maxFreq = 0; cnt.clear(); sts.clear(); } void push(int x) { cnt[x]++; maxFreq = max(maxFreq, cnt[x]); sts[cnt[x]].push(x); } int pop() { int maxKey = maxFreq; int x = sts[maxKey].top(); sts[maxKey].pop(); if(sts[maxKey].size() == 0){ sts.erase(maxKey); maxFreq--; } cnt[x]--; return x; } }; main(){ FreqStack ob; ob.push(7); ob.push(9); ob.push(7); ob.push(9); ob.push(6); ob.push(7); cout << (ob.pop()) << endl; cout << (ob.pop()) << endl; cout << (ob.pop()) << endl; cout << (ob.pop()) << endl; } push elements 7, 9, 7, 9, 6, 7, then call pop() four times. 7 9 7 6
[ { "code": null, "e": 1153, "s": 1062, "text": "Suppose we want to implement one stack called FreqStack, Our FreqStack has two functions −" }, { "code": null, "e": 1206, "s": 1153, "text": "push(x), This will push an integer x onto the stack." }, { "code": null, "e": 1259, "s": 1206, "text": "push(x), This will push an integer x onto the stack." }, { "code": null, "e": 1466, "s": 1259, "text": "pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned." }, { "code": null, "e": 1673, "s": 1466, "text": "pop(), This will remove and returns the most frequent element in the stack. If there are more than one elements with same frequency, then the element closest to the top of the stack is removed and returned." }, { "code": null, "e": 1830, "s": 1673, "text": "So, if the input is like push some elements like 7, 9, 7, 9, 6, 7, then perform the pop operations four times, then the output will be 7,9,7,6 respectively." }, { "code": null, "e": 1874, "s": 1830, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1893, "s": 1874, "text": "Define one map cnt" }, { "code": null, "e": 1912, "s": 1893, "text": "Define one map cnt" }, { "code": null, "e": 1931, "s": 1912, "text": "Define one map sts" }, { "code": null, "e": 1950, "s": 1931, "text": "Define one map sts" }, { "code": null, "e": 1963, "s": 1950, "text": "maxFreq := 0" }, { "code": null, "e": 1976, "s": 1963, "text": "maxFreq := 0" }, { "code": null, "e": 2020, "s": 1976, "text": "Define a function push(), this will take x," }, { "code": null, "e": 2064, "s": 2020, "text": "Define a function push(), this will take x," }, { "code": null, "e": 2087, "s": 2064, "text": "(increase cnt[x] by 1)" }, { "code": null, "e": 2110, "s": 2087, "text": "(increase cnt[x] by 1)" }, { "code": null, "e": 2151, "s": 2110, "text": "maxFreq := maximum of maxFreq and cnt[x]" }, { "code": null, "e": 2192, "s": 2151, "text": "maxFreq := maximum of maxFreq and cnt[x]" }, { "code": null, "e": 2218, "s": 2192, "text": "insert x into sts[cnt[x]]" }, { "code": null, "e": 2244, "s": 2218, "text": "insert x into sts[cnt[x]]" }, { "code": null, "e": 2268, "s": 2244, "text": "Define a function pop()" }, { "code": null, "e": 2292, "s": 2268, "text": "Define a function pop()" }, { "code": null, "e": 2310, "s": 2292, "text": "maxKey := maxFreq" }, { "code": null, "e": 2328, "s": 2310, "text": "maxKey := maxFreq" }, { "code": null, "e": 2360, "s": 2328, "text": "x := top element of sts[maxKey]" }, { "code": null, "e": 2392, "s": 2360, "text": "x := top element of sts[maxKey]" }, { "code": null, "e": 2424, "s": 2392, "text": "delete element from sts[maxKey]" }, { "code": null, "e": 2456, "s": 2424, "text": "delete element from sts[maxKey]" }, { "code": null, "e": 2545, "s": 2456, "text": "if size of sts[maxKey] is same as 0, then −delete maxKey from sts(decrease maxFreq by 1)" }, { "code": null, "e": 2589, "s": 2545, "text": "if size of sts[maxKey] is same as 0, then −" }, { "code": null, "e": 2612, "s": 2589, "text": "delete maxKey from sts" }, { "code": null, "e": 2635, "s": 2612, "text": "delete maxKey from sts" }, { "code": null, "e": 2659, "s": 2635, "text": "(decrease maxFreq by 1)" }, { "code": null, "e": 2683, "s": 2659, "text": "(decrease maxFreq by 1)" }, { "code": null, "e": 2706, "s": 2683, "text": "(decrease cnt[x] by 1)" }, { "code": null, "e": 2729, "s": 2706, "text": "(decrease cnt[x] by 1)" }, { "code": null, "e": 2738, "s": 2729, "text": "return x" }, { "code": null, "e": 2747, "s": 2738, "text": "return x" }, { "code": null, "e": 2817, "s": 2747, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2828, "s": 2817, "text": " Live Demo" }, { "code": null, "e": 3658, "s": 2828, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass FreqStack {\n public:\n unordered_map <int ,int > cnt;\n unordered_map <int, stack <int> >sts;\n int maxFreq = 0;\n FreqStack() {\n maxFreq = 0;\n cnt.clear();\n sts.clear();\n }\n void push(int x) {\n cnt[x]++;\n maxFreq = max(maxFreq, cnt[x]);\n sts[cnt[x]].push(x);\n }\n int pop() {\n int maxKey = maxFreq;\n int x = sts[maxKey].top();\n sts[maxKey].pop();\n if(sts[maxKey].size() == 0){\n sts.erase(maxKey);\n maxFreq--;\n }\n cnt[x]--;\n return x;\n }\n};\nmain(){\n FreqStack ob;\n ob.push(7);\n ob.push(9);\n ob.push(7);\n ob.push(9);\n ob.push(6);\n ob.push(7);\n cout << (ob.pop()) << endl;\n cout << (ob.pop()) << endl;\n cout << (ob.pop()) << endl;\n cout << (ob.pop()) << endl;\n}" }, { "code": null, "e": 3718, "s": 3658, "text": "push elements 7, 9, 7, 9, 6, 7, then call pop() four times." }, { "code": null, "e": 3726, "s": 3718, "text": "7\n9\n7\n6" } ]
Rexx - find
This method is used to search for the first occurrence of a string in another string. find(string, phrase) string − The string value that needs to be searched for. string − The string value that needs to be searched for. phrase − This is the value that needs to be searched for in the string. phrase − This is the value that needs to be searched for in the string. The method returns the word number of the first word of phrase in string. /* Main program */ options arexx_bifs say find(' Hello World ','World') When we run the above program we will get the following result. 2 Print Add Notes Bookmark this page
[ { "code": null, "e": 2425, "s": 2339, "text": "This method is used to search for the first occurrence of a string in another string." }, { "code": null, "e": 2447, "s": 2425, "text": "find(string, phrase)\n" }, { "code": null, "e": 2504, "s": 2447, "text": "string − The string value that needs to be searched for." }, { "code": null, "e": 2561, "s": 2504, "text": "string − The string value that needs to be searched for." }, { "code": null, "e": 2633, "s": 2561, "text": "phrase − This is the value that needs to be searched for in the string." }, { "code": null, "e": 2705, "s": 2633, "text": "phrase − This is the value that needs to be searched for in the string." }, { "code": null, "e": 2779, "s": 2705, "text": "The method returns the word number of the first word of phrase in string." }, { "code": null, "e": 2854, "s": 2779, "text": "/* Main program */ \noptions arexx_bifs \nsay find(' Hello World ','World') " }, { "code": null, "e": 2918, "s": 2854, "text": "When we run the above program we will get the following result." }, { "code": null, "e": 2921, "s": 2918, "text": "2\n" }, { "code": null, "e": 2928, "s": 2921, "text": " Print" }, { "code": null, "e": 2939, "s": 2928, "text": " Add Notes" } ]
CSS Background - GeeksforGeeks
07 Oct, 2021 The CSS background properties are used to define the background effects for elements. There are lots of properties to design the background. CSS background properties are as follows: CSS Background-color Property: The background-color property in CSS is used to specify the background color of an element. CSS Background-image Property: The background-image property is used to set one or more background images to an element. CSS Background-repeat Property: The background-repeat property in CSS is used to repeat the background image both horizontally and vertically. CSS Background-attachment Property: The property background-attachment property in CSS is used to specify the kind of attachment of the background image with respect to its container. CSS Background-position Property: In CSS body-position property is mainly used to set an image at a certain position. CSS Background-origin Property: The background-origin is a property defined in CSS which helps in adjusting the background image of the webpage. CSS Background-clip Property: The background-clip property in CSS is used to define how to extend background (color or image) within an element. Background color Property: This property specifies the background color of an element. A color name can also be given as : “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”. Syntax: body { background-color:color name } Example: HTML <!DOCTYPE html><html> <head> <style> h1 { background-color: blue; } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html> Output: Background Image Property: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element. Syntax: body { background-image : link; } Example: HTML <!DOCTYPE html><html> <head> <style> body { background-image:url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png"); } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html> Output: Background repeat Property: By default the background image property repeats the image both horizontally and vertically. Syntax: To repeat an image horizontally body { background-image:link; background-repeat: repeat:x; } Example: HTML <!DOCTYPE html><html> <head> <style> body { background-image:url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png"); background-repeat: repeat-x; } </style></head> <body> <h1>"Hello world"</h1></body> </html> Output: Background-attachment Property: This property is used to fix the background ground image.The image will not scroll with the page. Syntax: body { background-attachment: fixed; } Example: HTML <!DOCTYPE html><html> <head> <style> body { background-image:url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png"); background-attachment: fixed; } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html> Output: Background-position Property: This property is used to set the image to a particular position. Syntax : body { background-repeat:no repeat; background-position:left top; } Example: html <!DOCTYPE html><html> <head> <style> body { background-image:url("https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png"); background-repeat: no-repeat; background-position: center; } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html> Output: Vijay Sirra yashjadhav1502 ysachin2314 shubhamyadav4 CSS-Basics CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28072, "s": 28044, "text": "\n07 Oct, 2021" }, { "code": null, "e": 28256, "s": 28072, "text": "The CSS background properties are used to define the background effects for elements. There are lots of properties to design the background. CSS background properties are as follows: " }, { "code": null, "e": 28379, "s": 28256, "text": "CSS Background-color Property: The background-color property in CSS is used to specify the background color of an element." }, { "code": null, "e": 28500, "s": 28379, "text": "CSS Background-image Property: The background-image property is used to set one or more background images to an element." }, { "code": null, "e": 28643, "s": 28500, "text": "CSS Background-repeat Property: The background-repeat property in CSS is used to repeat the background image both horizontally and vertically." }, { "code": null, "e": 28827, "s": 28643, "text": "CSS Background-attachment Property: The property background-attachment property in CSS is used to specify the kind of attachment of the background image with respect to its container." }, { "code": null, "e": 28945, "s": 28827, "text": "CSS Background-position Property: In CSS body-position property is mainly used to set an image at a certain position." }, { "code": null, "e": 29090, "s": 28945, "text": "CSS Background-origin Property: The background-origin is a property defined in CSS which helps in adjusting the background image of the webpage." }, { "code": null, "e": 29235, "s": 29090, "text": "CSS Background-clip Property: The background-clip property in CSS is used to define how to extend background (color or image) within an element." }, { "code": null, "e": 29436, "s": 29235, "text": "Background color Property: This property specifies the background color of an element. A color name can also be given as : “green”, a HEX value as “#5570f0”, an RGB value as “rgb(25, 255, 2)”. Syntax:" }, { "code": null, "e": 29476, "s": 29436, "text": "body {\n background-color:color name\n}" }, { "code": null, "e": 29485, "s": 29476, "text": "Example:" }, { "code": null, "e": 29490, "s": 29485, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { background-color: blue; } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html>", "e": 29653, "s": 29490, "text": null }, { "code": null, "e": 29663, "s": 29653, "text": "Output: " }, { "code": null, "e": 29837, "s": 29663, "text": "Background Image Property: This property specify an image to use as the background of an element. By default, the image is repeated so it covers the entire element. Syntax: " }, { "code": null, "e": 29874, "s": 29837, "text": "body {\n background-image : link;\n}" }, { "code": null, "e": 29884, "s": 29874, "text": "Example: " }, { "code": null, "e": 29889, "s": 29884, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { background-image:url(\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png\"); } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html>", "e": 30134, "s": 29889, "text": null }, { "code": null, "e": 30144, "s": 30134, "text": "Output: " }, { "code": null, "e": 30305, "s": 30144, "text": "Background repeat Property: By default the background image property repeats the image both horizontally and vertically. Syntax: To repeat an image horizontally" }, { "code": null, "e": 30372, "s": 30305, "text": "body {\n background-image:link;\n background-repeat: repeat:x;\n}" }, { "code": null, "e": 30381, "s": 30372, "text": "Example:" }, { "code": null, "e": 30386, "s": 30381, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { background-image:url(\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png\"); background-repeat: repeat-x; } </style></head> <body> <h1>\"Hello world\"</h1></body> </html>", "e": 30670, "s": 30386, "text": null }, { "code": null, "e": 30678, "s": 30670, "text": "Output:" }, { "code": null, "e": 30817, "s": 30678, "text": "Background-attachment Property: This property is used to fix the background ground image.The image will not scroll with the page. Syntax: " }, { "code": null, "e": 30859, "s": 30817, "text": "body {\n background-attachment: fixed;\n}" }, { "code": null, "e": 30869, "s": 30859, "text": "Example: " }, { "code": null, "e": 30874, "s": 30869, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { background-image:url(\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png\"); background-attachment: fixed; } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html>", "e": 31159, "s": 30874, "text": null }, { "code": null, "e": 31168, "s": 31159, "text": "Output: " }, { "code": null, "e": 31273, "s": 31168, "text": "Background-position Property: This property is used to set the image to a particular position. Syntax : " }, { "code": null, "e": 31347, "s": 31273, "text": "body {\n background-repeat:no repeat;\n background-position:left top;\n}" }, { "code": null, "e": 31357, "s": 31347, "text": "Example: " }, { "code": null, "e": 31362, "s": 31357, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> body { background-image:url(\"https://media.geeksforgeeks.org/wp-content/cdn-uploads/20190417124305/250.png\"); background-repeat: no-repeat; background-position: center; } </style></head> <body> <h1>Geeksforgeeks</h1></body> </html>", "e": 31687, "s": 31362, "text": null }, { "code": null, "e": 31696, "s": 31687, "text": "Output: " }, { "code": null, "e": 31708, "s": 31696, "text": "Vijay Sirra" }, { "code": null, "e": 31723, "s": 31708, "text": "yashjadhav1502" }, { "code": null, "e": 31735, "s": 31723, "text": "ysachin2314" }, { "code": null, "e": 31749, "s": 31735, "text": "shubhamyadav4" }, { "code": null, "e": 31760, "s": 31749, "text": "CSS-Basics" }, { "code": null, "e": 31764, "s": 31760, "text": "CSS" }, { "code": null, "e": 31781, "s": 31764, "text": "Web Technologies" }, { "code": null, "e": 31879, "s": 31781, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31929, "s": 31879, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31991, "s": 31929, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32049, "s": 31991, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 32097, "s": 32049, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32147, "s": 32097, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 32189, "s": 32147, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 32222, "s": 32189, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32265, "s": 32222, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 32327, "s": 32265, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
htdigest command in Linux with examples - GeeksforGeeks
26 Feb, 2019 “htdigest” command is used to create and update password file which is used by Apache HTTPD digest authentication. Basically, it stores usernames, realm, and password of HTTP users. Before sending any sensitive information such as online shopping transactions, it confirms identity of the users. Syntax: htdigest [-c] passwdfile realm username Options: [-c]: It is used to create a passwdfile, if this file does not exists then its created and if is already exists then that file is deleted and another file is recreated. passwdfile: It contains username, realm, and password of the user. realm: It is a string which is visible to the users to let them know which username and password to use. Username It create or updates passwdfile. If this username does not exists then a new entry is added and if it exists then the password is changed. Examples: Command to create a new Apache password file and adding a new user:# htdigest -c httpd-pwd-file realm username Example:Here, “httpd-pwd-file” is newly created password file which adds user gfg to the file, and “systemadmin” is the realm used here. # htdigest -c httpd-pwd-file realm username Example: Here, “httpd-pwd-file” is newly created password file which adds user gfg to the file, and “systemadmin” is the realm used here. Command to see Apache password file format: It is the format of the context of the password file which is created by the ht_digest command in the text file. In order to see the password file format, you need to use “cat” command with the created password file. The format is:username:realm name:encrypted passwordExample:Here, httpd-pwd-file is the file created above. username:realm name:encrypted password Example: Here, httpd-pwd-file is the file created above. Command to add another user to Apache password file:# htdigest httpd-pwd-file realm usernameExample:Here, user nidhi is added to httpd-pwd-file in realm author. Now, the format of the password will be:Here, password of two users are shown as the above httpd-pwd-file has two users now. # htdigest httpd-pwd-file realm username Example: Here, user nidhi is added to httpd-pwd-file in realm author. Now, the format of the password will be: Here, password of two users are shown as the above httpd-pwd-file has two users now. Command to change password of an user:# htdigest httpd-pwd-file realm usernameExample:Here, the password of the existing user can be changed. # htdigest httpd-pwd-file realm username Example: Here, the password of the existing user can be changed. Command to add users to multiple realms in password file:# htdigest httpd-pwd-file realm usernameExample:This command will add user nidhi to the existing httpd-pwd-file in the realm “systemadmin”.Note: There will be two password entries for user nidhi as it has different realms.Example: # htdigest httpd-pwd-file realm username Example: This command will add user nidhi to the existing httpd-pwd-file in the realm “systemadmin”. Note: There will be two password entries for user nidhi as it has different realms. Example: Command to delete an user from Apache file: To delete an user from Apache file use “vi” command i.e, (vi name of password file). linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ mv command in Linux with examples nohup Command in Linux with Examples scp command in Linux with Examples Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n26 Feb, 2019" }, { "code": null, "e": 24311, "s": 24015, "text": "“htdigest” command is used to create and update password file which is used by Apache HTTPD digest authentication. Basically, it stores usernames, realm, and password of HTTP users. Before sending any sensitive information such as online shopping transactions, it confirms identity of the users." }, { "code": null, "e": 24319, "s": 24311, "text": "Syntax:" }, { "code": null, "e": 24359, "s": 24319, "text": "htdigest [-c] passwdfile realm username" }, { "code": null, "e": 24368, "s": 24359, "text": "Options:" }, { "code": null, "e": 24537, "s": 24368, "text": "[-c]: It is used to create a passwdfile, if this file does not exists then its created and if is already exists then that file is deleted and another file is recreated." }, { "code": null, "e": 24604, "s": 24537, "text": "passwdfile: It contains username, realm, and password of the user." }, { "code": null, "e": 24709, "s": 24604, "text": "realm: It is a string which is visible to the users to let them know which username and password to use." }, { "code": null, "e": 24857, "s": 24709, "text": "Username It create or updates passwdfile. If this username does not exists then a new entry is added and if it exists then the password is changed." }, { "code": null, "e": 24867, "s": 24857, "text": "Examples:" }, { "code": null, "e": 25115, "s": 24867, "text": "Command to create a new Apache password file and adding a new user:# htdigest -c httpd-pwd-file realm username Example:Here, “httpd-pwd-file” is newly created password file which adds user gfg to the file, and “systemadmin” is the realm used here." }, { "code": null, "e": 25160, "s": 25115, "text": "# htdigest -c httpd-pwd-file realm username " }, { "code": null, "e": 25169, "s": 25160, "text": "Example:" }, { "code": null, "e": 25298, "s": 25169, "text": "Here, “httpd-pwd-file” is newly created password file which adds user gfg to the file, and “systemadmin” is the realm used here." }, { "code": null, "e": 25667, "s": 25298, "text": "Command to see Apache password file format: It is the format of the context of the password file which is created by the ht_digest command in the text file. In order to see the password file format, you need to use “cat” command with the created password file. The format is:username:realm name:encrypted passwordExample:Here, httpd-pwd-file is the file created above." }, { "code": null, "e": 25706, "s": 25667, "text": "username:realm name:encrypted password" }, { "code": null, "e": 25715, "s": 25706, "text": "Example:" }, { "code": null, "e": 25763, "s": 25715, "text": "Here, httpd-pwd-file is the file created above." }, { "code": null, "e": 26049, "s": 25763, "text": "Command to add another user to Apache password file:# htdigest httpd-pwd-file realm usernameExample:Here, user nidhi is added to httpd-pwd-file in realm author. Now, the format of the password will be:Here, password of two users are shown as the above httpd-pwd-file has two users now." }, { "code": null, "e": 26090, "s": 26049, "text": "# htdigest httpd-pwd-file realm username" }, { "code": null, "e": 26099, "s": 26090, "text": "Example:" }, { "code": null, "e": 26201, "s": 26099, "text": "Here, user nidhi is added to httpd-pwd-file in realm author. Now, the format of the password will be:" }, { "code": null, "e": 26286, "s": 26201, "text": "Here, password of two users are shown as the above httpd-pwd-file has two users now." }, { "code": null, "e": 26428, "s": 26286, "text": "Command to change password of an user:# htdigest httpd-pwd-file realm usernameExample:Here, the password of the existing user can be changed." }, { "code": null, "e": 26469, "s": 26428, "text": "# htdigest httpd-pwd-file realm username" }, { "code": null, "e": 26478, "s": 26469, "text": "Example:" }, { "code": null, "e": 26534, "s": 26478, "text": "Here, the password of the existing user can be changed." }, { "code": null, "e": 26822, "s": 26534, "text": "Command to add users to multiple realms in password file:# htdigest httpd-pwd-file realm usernameExample:This command will add user nidhi to the existing httpd-pwd-file in the realm “systemadmin”.Note: There will be two password entries for user nidhi as it has different realms.Example:" }, { "code": null, "e": 26863, "s": 26822, "text": "# htdigest httpd-pwd-file realm username" }, { "code": null, "e": 26872, "s": 26863, "text": "Example:" }, { "code": null, "e": 26964, "s": 26872, "text": "This command will add user nidhi to the existing httpd-pwd-file in the realm “systemadmin”." }, { "code": null, "e": 27048, "s": 26964, "text": "Note: There will be two password entries for user nidhi as it has different realms." }, { "code": null, "e": 27057, "s": 27048, "text": "Example:" }, { "code": null, "e": 27186, "s": 27057, "text": "Command to delete an user from Apache file: To delete an user from Apache file use “vi” command i.e, (vi name of password file)." }, { "code": null, "e": 27200, "s": 27186, "text": "linux-command" }, { "code": null, "e": 27207, "s": 27200, "text": "Picked" }, { "code": null, "e": 27218, "s": 27207, "text": "Linux-Unix" }, { "code": null, "e": 27316, "s": 27218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27325, "s": 27316, "text": "Comments" }, { "code": null, "e": 27338, "s": 27325, "text": "Old Comments" }, { "code": null, "e": 27364, "s": 27338, "text": "Thread functions in C/C++" }, { "code": null, "e": 27398, "s": 27364, "text": "mv command in Linux with examples" }, { "code": null, "e": 27435, "s": 27398, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27470, "s": 27435, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27496, "s": 27470, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27533, "s": 27496, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27573, "s": 27533, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 27602, "s": 27573, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27644, "s": 27602, "text": "Named Pipe or FIFO with example C program" } ]