title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Change the legend position in Matplotlib
26 May, 2021 In this article, we will learn how to Change the legend position in Matplotlib. Let’s discuss some concepts : Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002. A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes. The attribute Loc in legend() is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings best upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, and center place the legend at the corresponding corner of the axes/figure. Approach: Import Library (Matplotlib)Import / create data.Plot a chart.Add legend.Set position of legend using loc. Import Library (Matplotlib) Import / create data. Plot a chart. Add legend. Set position of legend using loc. Example 1: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legendplt.legend(['Legend'])plt.show() Output: Without setting location of legend (best) Example 2: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to upper leftplt.legend(['Legend'], loc='upper left')plt.show() Output: Legend in Upper left Example 3: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower left i.e; 4plt.legend(['Legend'], loc=4)plt.show() Output: Legend in Lower left Example 4: Python3 # importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower rightplt.legend(['Legend'], loc='lower right')plt.show() Output: Legend in Lower right sweetyty Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function Python Dictionary How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Taking input in Python Enumerate() in Python Read a file line by line in Python Python String | replace()
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2021" }, { "code": null, "e": 138, "s": 28, "text": "In this article, we will learn how to Change the legend position in Matplotlib. Let’s discuss some concepts :" }, { "code": null, "e": 418, "s": 138, "text": "Matplotlib is a tremendous visualization library in Python for 2D plots of arrays. Matplotlib may be a multi-platform data visualization library built on NumPy arrays and designed to figure with the broader SciPy stack. It had been introduced by John Hunter within the year 2002." }, { "code": null, "e": 583, "s": 418, "text": "A legend is an area describing the elements of the graph. In the matplotlib library, there’s a function called legend() which is used to Place a legend on the axes." }, { "code": null, "e": 913, "s": 583, "text": "The attribute Loc in legend() is used to specify the location of the legend.Default value of loc is loc=”best” (upper left). The strings best upper right, upper left, lower left, lower right, right, center left, center right, lower center, upper center, and center place the legend at the corresponding corner of the axes/figure." }, { "code": null, "e": 923, "s": 913, "text": "Approach:" }, { "code": null, "e": 1029, "s": 923, "text": "Import Library (Matplotlib)Import / create data.Plot a chart.Add legend.Set position of legend using loc." }, { "code": null, "e": 1057, "s": 1029, "text": "Import Library (Matplotlib)" }, { "code": null, "e": 1079, "s": 1057, "text": "Import / create data." }, { "code": null, "e": 1093, "s": 1079, "text": "Plot a chart." }, { "code": null, "e": 1105, "s": 1093, "text": "Add legend." }, { "code": null, "e": 1139, "s": 1105, "text": "Set position of legend using loc." }, { "code": null, "e": 1150, "s": 1139, "text": "Example 1:" }, { "code": null, "e": 1158, "s": 1150, "text": "Python3" }, { "code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legendplt.legend(['Legend'])plt.show()", "e": 1389, "s": 1158, "text": null }, { "code": null, "e": 1397, "s": 1389, "text": "Output:" }, { "code": null, "e": 1439, "s": 1397, "text": "Without setting location of legend (best)" }, { "code": null, "e": 1450, "s": 1439, "text": "Example 2:" }, { "code": null, "e": 1458, "s": 1450, "text": "Python3" }, { "code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to upper leftplt.legend(['Legend'], loc='upper left')plt.show()", "e": 1738, "s": 1458, "text": null }, { "code": null, "e": 1746, "s": 1738, "text": "Output:" }, { "code": null, "e": 1767, "s": 1746, "text": "Legend in Upper left" }, { "code": null, "e": 1778, "s": 1767, "text": "Example 3:" }, { "code": null, "e": 1786, "s": 1778, "text": "Python3" }, { "code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower left i.e; 4plt.legend(['Legend'], loc=4)plt.show()", "e": 2062, "s": 1786, "text": null }, { "code": null, "e": 2070, "s": 2062, "text": "Output:" }, { "code": null, "e": 2091, "s": 2070, "text": "Legend in Lower left" }, { "code": null, "e": 2102, "s": 2091, "text": "Example 4:" }, { "code": null, "e": 2110, "s": 2102, "text": "Python3" }, { "code": "# importing packagesimport numpy as npimport matplotlib.pyplot as plt # create datax = np.linspace(1, 50, 50)np.random.seed(1)y = np.random.randint(0, 20, 50) # plot graphplt.plot(x, y) # add legend and set position to lower rightplt.legend(['Legend'], loc='lower right')plt.show()", "e": 2392, "s": 2110, "text": null }, { "code": null, "e": 2400, "s": 2392, "text": "Output:" }, { "code": null, "e": 2422, "s": 2400, "text": "Legend in Lower right" }, { "code": null, "e": 2431, "s": 2422, "text": "sweetyty" }, { "code": null, "e": 2438, "s": 2431, "text": "Picked" }, { "code": null, "e": 2456, "s": 2438, "text": "Python-matplotlib" }, { "code": null, "e": 2463, "s": 2456, "text": "Python" }, { "code": null, "e": 2561, "s": 2463, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2589, "s": 2561, "text": "Read JSON file using Python" }, { "code": null, "e": 2639, "s": 2589, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 2661, "s": 2639, "text": "Python map() function" }, { "code": null, "e": 2679, "s": 2661, "text": "Python Dictionary" }, { "code": null, "e": 2723, "s": 2679, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 2765, "s": 2723, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2788, "s": 2765, "text": "Taking input in Python" }, { "code": null, "e": 2810, "s": 2788, "text": "Enumerate() in Python" }, { "code": null, "e": 2845, "s": 2810, "text": "Read a file line by line in Python" } ]
How to Sort a Pandas DataFrame by Both Index and Column?
23 Dec, 2021 In this article, we will discuss how to sort a Pandas dataframe by both index and columns. We can sort a Pandas DataFrame based on Index and column using sort_index method. To sort the DataFrame based on the index we need to pass axis=0 as a parameter to sort_index method. To sort the DataFrame based on the column name then we need to pass axis=1 as a parameter to sort_index method. Syntax DataFrame_Name.sort_index(axis=0, ascending=True, inplace=False, kind=’quicksort’) Parameters axis- Specifies on which basis to sort whether based on index or column. By default, it sorts based on index i.e. axis=0. ascending- Specifies on which order to sort whether in ascending or descending order. It accepts True or False. By default it is True. inplace- It specifies that the changes to the DataFrame is Temporary or Permanent. inplace=False indicates temporary and True indicates permanent. kind- Specifies which sorting algorithm to use. It accepts quicksort, mergesort, heapsort, etc. By default, it is quicksort if not mentioned. DataFrame col2 col1 3 150 70 2 170 55 1 160 60 This was the DataFrame we are using in the below codes for sorting. By specifying axis=0 in sort_index method we can sort the DataFrame. Even if we don’t specify axis parameter in sort_index by default it sorts the DataFrame based on row. Example: In this example, the DataFrame is a sorted DataFrame based on index labels and this was temporarily sorted in python language. Python3 # import necessary packagesimport pandas as pd # create 2 dataframes with different indexeshostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160], 'col1': [70, 55, 60]}, index=[3, 2, 1])print('original DataFrame')print(hostelCandidates1) # sorted temperorle based on index labelsprint('Sorted by index')hostelCandidates1.sort_index(axis=0) Output original DataFrame col2 col1 3 150 70 2 170 55 1 160 60 Sorted by index col2 col1 1 160 60 2 170 55 3 150 70 To sort the data in the DataFrame on the basis of column names, then we need to pass axis=1 as a parameter to sort_index method in python language. Python3 # import necessary packagesimport pandas as pd # create 2 dataframes with different indexeshostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160], 'col1': [70, 55, 60]}, index=[3, 2, 1])print('original DataFrame')print(hostelCandidates1) # sorted temperorle based on column labelsprint('Sorted by column name')hostelCandidates1.sort_index(axis=1) Output original DataFrame col2 col1 3 150 70 2 170 55 1 160 60 Sorted by column name col1 col2 3 70 150 2 55 170 1 60 160 Example Code to sort the DataFrame & save changes permanently on original DataFrame: Here the sort operation is performed directly on the original DataFrame and changes are saved permanently because of inplace=True argument. Python3 # import necessary packagesimport pandas as pd # create 2 dataframes with different indexeshostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160], 'col1': [70, 55, 60]}, index=[3, 2, 1])print('original DataFrame')print(hostelCandidates1) # sorted permanently based on column labelshostelCandidates1.sort_index(axis=1, inplace=True) print('Modified Original DataFrame')print(hostelCandidates1) Output original DataFrame col2 col1 3 150 70 2 170 55 1 160 60 Modified Original DataFrame col1 col2 3 70 150 2 55 170 1 60 160 simmytarika5 pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Dec, 2021" }, { "code": null, "e": 119, "s": 28, "text": "In this article, we will discuss how to sort a Pandas dataframe by both index and columns." }, { "code": null, "e": 201, "s": 119, "text": "We can sort a Pandas DataFrame based on Index and column using sort_index method." }, { "code": null, "e": 302, "s": 201, "text": "To sort the DataFrame based on the index we need to pass axis=0 as a parameter to sort_index method." }, { "code": null, "e": 414, "s": 302, "text": "To sort the DataFrame based on the column name then we need to pass axis=1 as a parameter to sort_index method." }, { "code": null, "e": 421, "s": 414, "text": "Syntax" }, { "code": null, "e": 504, "s": 421, "text": "DataFrame_Name.sort_index(axis=0, ascending=True, inplace=False, kind=’quicksort’)" }, { "code": null, "e": 515, "s": 504, "text": "Parameters" }, { "code": null, "e": 637, "s": 515, "text": "axis- Specifies on which basis to sort whether based on index or column. By default, it sorts based on index i.e. axis=0." }, { "code": null, "e": 772, "s": 637, "text": "ascending- Specifies on which order to sort whether in ascending or descending order. It accepts True or False. By default it is True." }, { "code": null, "e": 919, "s": 772, "text": "inplace- It specifies that the changes to the DataFrame is Temporary or Permanent. inplace=False indicates temporary and True indicates permanent." }, { "code": null, "e": 1061, "s": 919, "text": "kind- Specifies which sorting algorithm to use. It accepts quicksort, mergesort, heapsort, etc. By default, it is quicksort if not mentioned." }, { "code": null, "e": 1071, "s": 1061, "text": "DataFrame" }, { "code": null, "e": 1078, "s": 1073, "text": "col2" }, { "code": null, "e": 1083, "s": 1078, "text": "col1" }, { "code": null, "e": 1085, "s": 1083, "text": "3" }, { "code": null, "e": 1089, "s": 1085, "text": "150" }, { "code": null, "e": 1092, "s": 1089, "text": "70" }, { "code": null, "e": 1094, "s": 1092, "text": "2" }, { "code": null, "e": 1098, "s": 1094, "text": "170" }, { "code": null, "e": 1101, "s": 1098, "text": "55" }, { "code": null, "e": 1103, "s": 1101, "text": "1" }, { "code": null, "e": 1107, "s": 1103, "text": "160" }, { "code": null, "e": 1110, "s": 1107, "text": "60" }, { "code": null, "e": 1350, "s": 1110, "text": "This was the DataFrame we are using in the below codes for sorting. By specifying axis=0 in sort_index method we can sort the DataFrame. Even if we don’t specify axis parameter in sort_index by default it sorts the DataFrame based on row." }, { "code": null, "e": 1359, "s": 1350, "text": "Example:" }, { "code": null, "e": 1487, "s": 1359, "text": " In this example, the DataFrame is a sorted DataFrame based on index labels and this was temporarily sorted in python language." }, { "code": null, "e": 1495, "s": 1487, "text": "Python3" }, { "code": "# import necessary packagesimport pandas as pd # create 2 dataframes with different indexeshostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160], 'col1': [70, 55, 60]}, index=[3, 2, 1])print('original DataFrame')print(hostelCandidates1) # sorted temperorle based on index labelsprint('Sorted by index')hostelCandidates1.sort_index(axis=0)", "e": 1903, "s": 1495, "text": null }, { "code": null, "e": 1910, "s": 1903, "text": "Output" }, { "code": null, "e": 2071, "s": 1910, "text": "original DataFrame\n col2 col1\n3 150 70\n2 170 55\n1 160 60\nSorted by index\n\n col2 col1\n1 160 60\n2 170 55\n3 150 70" }, { "code": null, "e": 2219, "s": 2071, "text": "To sort the data in the DataFrame on the basis of column names, then we need to pass axis=1 as a parameter to sort_index method in python language." }, { "code": null, "e": 2227, "s": 2219, "text": "Python3" }, { "code": "# import necessary packagesimport pandas as pd # create 2 dataframes with different indexeshostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160], 'col1': [70, 55, 60]}, index=[3, 2, 1])print('original DataFrame')print(hostelCandidates1) # sorted temperorle based on column labelsprint('Sorted by column name')hostelCandidates1.sort_index(axis=1)", "e": 2642, "s": 2227, "text": null }, { "code": null, "e": 2649, "s": 2642, "text": "Output" }, { "code": null, "e": 2816, "s": 2649, "text": "original DataFrame\n col2 col1\n3 150 70\n2 170 55\n1 160 60\nSorted by column name\n\n col1 col2\n3 70 150\n2 55 170\n1 60 160" }, { "code": null, "e": 2901, "s": 2816, "text": "Example Code to sort the DataFrame & save changes permanently on original DataFrame:" }, { "code": null, "e": 3041, "s": 2901, "text": "Here the sort operation is performed directly on the original DataFrame and changes are saved permanently because of inplace=True argument." }, { "code": null, "e": 3049, "s": 3041, "text": "Python3" }, { "code": "# import necessary packagesimport pandas as pd # create 2 dataframes with different indexeshostelCandidates1 = pd.DataFrame({'col2': [150, 170, 160], 'col1': [70, 55, 60]}, index=[3, 2, 1])print('original DataFrame')print(hostelCandidates1) # sorted permanently based on column labelshostelCandidates1.sort_index(axis=1, inplace=True) print('Modified Original DataFrame')print(hostelCandidates1)", "e": 3510, "s": 3049, "text": null }, { "code": null, "e": 3517, "s": 3510, "text": "Output" }, { "code": null, "e": 3676, "s": 3517, "text": "original DataFrame\n col2 col1\n3 150 70\n2 170 55\n1 160 60\nModified Original DataFrame\n col1 col2\n3 70 150\n2 55 170\n1 60 160" }, { "code": null, "e": 3689, "s": 3676, "text": "simmytarika5" }, { "code": null, "e": 3714, "s": 3689, "text": "pandas-dataframe-program" }, { "code": null, "e": 3721, "s": 3714, "text": "Picked" }, { "code": null, "e": 3745, "s": 3721, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3759, "s": 3745, "text": "Python-pandas" }, { "code": null, "e": 3766, "s": 3759, "text": "Python" }, { "code": null, "e": 3864, "s": 3766, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3896, "s": 3864, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3923, "s": 3896, "text": "Python Classes and Objects" }, { "code": null, "e": 3944, "s": 3923, "text": "Python OOPs Concepts" }, { "code": null, "e": 3967, "s": 3944, "text": "Introduction To PYTHON" }, { "code": null, "e": 3998, "s": 3967, "text": "Python | os.path.join() method" }, { "code": null, "e": 4054, "s": 3998, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 4096, "s": 4054, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 4138, "s": 4096, "text": "Check if element exists in list in Python" }, { "code": null, "e": 4177, "s": 4138, "text": "Python | Get unique values from a list" } ]
Python | Combining two sorted lists
24 Dec, 2018 Many a times we encounter a problem where we wish to use the merge function of merge sort and is a classical problem that occurs many times while doing competitive programming. This type of problem when known shorter and compact way to perform them are always quite handy. Let’s discuss certain ways of combining two sorted list in Python. Method #1 : Naive Method Merge operation of merge sort can be performed using the naive method which has also been discussed earlier. We check for the smaller of two element on the current index and increment the index of the list whose no. is encountered. When either of the list gets exhausted, the other list is appended to the end of merged list. # Python3 code to demonstrate # to combine two sorted list # using naive method # initializing liststest_list1 = [1, 5, 6, 9, 11]test_list2 = [3, 4, 7, 8, 10] # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using naive method # to combine two sorted listssize_1 = len(test_list1)size_2 = len(test_list2) res = []i, j = 0, 0 while i < size_1 and j < size_2: if test_list1[i] < test_list2[j]: res.append(test_list1[i]) i += 1 else: res.append(test_list2[j]) j += 1 res = res + test_list1[i:] + test_list2[j:] # printing resultprint ("The combined sorted list is : " + str(res)) The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11] Method #2 : Using sorted() This function can be used to perform this task in just a 1 line but will take more time internally. It may have more time complexity as we append one list to another and again sort the resultant list. Should be used if we need to save the coding time. # Python3 code to demonstrate # to combine two sorted list # using sorted() # initializing liststest_list1 = [1, 5, 6, 9, 11]test_list2 = [3, 4, 7, 8, 10] # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using sorted()# to combine two sorted listsres = sorted(test_list1 + test_list2) # printing resultprint ("The combined sorted list is : " + str(res)) The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11] Method #3 : Using heapq.merge() Python also offers the inbuilt function to perform this particular task and performs the similar working in background as merge in naive method and should be used when wanting to deal with this kind of problem. # Python3 code to demonstrate # to combine two sorted list # using heapq.merge()from heapq import merge # initializing liststest_list1 = [1, 5, 6, 9, 11]test_list2 = [3, 4, 7, 8, 10] # printing original lists print ("The original list 1 is : " + str(test_list1))print ("The original list 2 is : " + str(test_list2)) # using heapq.merge()# to combine two sorted listsres = list(merge(test_list1, test_list2)) # printing resultprint ("The combined sorted list is : " + str(res)) The original list 1 is : [1, 5, 6, 9, 11] The original list 2 is : [3, 4, 7, 8, 10] The combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Dec, 2018" }, { "code": null, "e": 326, "s": 53, "text": "Many a times we encounter a problem where we wish to use the merge function of merge sort and is a classical problem that occurs many times while doing competitive programming. This type of problem when known shorter and compact way to perform them are always quite handy." }, { "code": null, "e": 393, "s": 326, "text": "Let’s discuss certain ways of combining two sorted list in Python." }, { "code": null, "e": 418, "s": 393, "text": "Method #1 : Naive Method" }, { "code": null, "e": 744, "s": 418, "text": "Merge operation of merge sort can be performed using the naive method which has also been discussed earlier. We check for the smaller of two element on the current index and increment the index of the list whose no. is encountered. When either of the list gets exhausted, the other list is appended to the end of merged list." }, { "code": "# Python3 code to demonstrate # to combine two sorted list # using naive method # initializing liststest_list1 = [1, 5, 6, 9, 11]test_list2 = [3, 4, 7, 8, 10] # printing original lists print (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using naive method # to combine two sorted listssize_1 = len(test_list1)size_2 = len(test_list2) res = []i, j = 0, 0 while i < size_1 and j < size_2: if test_list1[i] < test_list2[j]: res.append(test_list1[i]) i += 1 else: res.append(test_list2[j]) j += 1 res = res + test_list1[i:] + test_list2[j:] # printing resultprint (\"The combined sorted list is : \" + str(res))", "e": 1443, "s": 744, "text": null }, { "code": null, "e": 1591, "s": 1443, "text": "The original list 1 is : [1, 5, 6, 9, 11]\nThe original list 2 is : [3, 4, 7, 8, 10]\nThe combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n" }, { "code": null, "e": 1619, "s": 1591, "text": " Method #2 : Using sorted()" }, { "code": null, "e": 1871, "s": 1619, "text": "This function can be used to perform this task in just a 1 line but will take more time internally. It may have more time complexity as we append one list to another and again sort the resultant list. Should be used if we need to save the coding time." }, { "code": "# Python3 code to demonstrate # to combine two sorted list # using sorted() # initializing liststest_list1 = [1, 5, 6, 9, 11]test_list2 = [3, 4, 7, 8, 10] # printing original lists print (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using sorted()# to combine two sorted listsres = sorted(test_list1 + test_list2) # printing resultprint (\"The combined sorted list is : \" + str(res))", "e": 2316, "s": 1871, "text": null }, { "code": null, "e": 2464, "s": 2316, "text": "The original list 1 is : [1, 5, 6, 9, 11]\nThe original list 2 is : [3, 4, 7, 8, 10]\nThe combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n" }, { "code": null, "e": 2497, "s": 2464, "text": " Method #3 : Using heapq.merge()" }, { "code": null, "e": 2708, "s": 2497, "text": "Python also offers the inbuilt function to perform this particular task and performs the similar working in background as merge in naive method and should be used when wanting to deal with this kind of problem." }, { "code": "# Python3 code to demonstrate # to combine two sorted list # using heapq.merge()from heapq import merge # initializing liststest_list1 = [1, 5, 6, 9, 11]test_list2 = [3, 4, 7, 8, 10] # printing original lists print (\"The original list 1 is : \" + str(test_list1))print (\"The original list 2 is : \" + str(test_list2)) # using heapq.merge()# to combine two sorted listsres = list(merge(test_list1, test_list2)) # printing resultprint (\"The combined sorted list is : \" + str(res))", "e": 3189, "s": 2708, "text": null }, { "code": null, "e": 3337, "s": 3189, "text": "The original list 1 is : [1, 5, 6, 9, 11]\nThe original list 2 is : [3, 4, 7, 8, 10]\nThe combined sorted list is : [1, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n" }, { "code": null, "e": 3358, "s": 3337, "text": "Python list-programs" }, { "code": null, "e": 3365, "s": 3358, "text": "Python" }, { "code": null, "e": 3381, "s": 3365, "text": "Python Programs" }, { "code": null, "e": 3479, "s": 3381, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3521, "s": 3479, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3543, "s": 3521, "text": "Enumerate() in Python" }, { "code": null, "e": 3569, "s": 3543, "text": "Python String | replace()" }, { "code": null, "e": 3601, "s": 3569, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3630, "s": 3601, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3652, "s": 3630, "text": "Defaultdict in Python" }, { "code": null, "e": 3691, "s": 3652, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3729, "s": 3691, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 3766, "s": 3729, "text": "Python Program for Fibonacci numbers" } ]
SQLite - Transactions
A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program. A transaction is the propagation of one or more changes to the database. For example, if you are creating, updating, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors. Practically, you will club many SQLite queries into a group and you will execute all of them together as part of a transaction. Transactions have the following four standard properties, usually referred to by the acronym ACID. Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state. Consistency − Ensures that the database properly changes states upon a successfully committed transaction. Consistency − Ensures that the database properly changes states upon a successfully committed transaction. Isolation − Enables transactions to operate independently of and transparent to each other. Isolation − Enables transactions to operate independently of and transparent to each other. Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure. Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure. Following are the following commands used to control transactions: BEGIN TRANSACTION − To start a transaction. BEGIN TRANSACTION − To start a transaction. COMMIT − To save the changes, alternatively you can use END TRANSACTION command. COMMIT − To save the changes, alternatively you can use END TRANSACTION command. ROLLBACK − To rollback the changes. ROLLBACK − To rollback the changes. Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database. Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. However, a transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the simple syntax to start a transaction. BEGIN; or BEGIN TRANSACTION; COMMIT command is the transactional command used to save changes invoked by a transaction to the database. COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command. Following is the syntax for COMMIT command. COMMIT; or END TRANSACTION; ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database. ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued. Following is the syntax for ROLLBACK command. ROLLBACK; Example Consider COMPANY table with the following records. ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Now, let's start a transaction and delete records from the table having age = 25. Then, use ROLLBACK command to undo all the changes. sqlite> BEGIN; sqlite> DELETE FROM COMPANY WHERE AGE = 25; sqlite> ROLLBACK; Now, if you check COMPANY table, it still has the following records − ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 Let's start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes. sqlite> BEGIN; sqlite> DELETE FROM COMPANY WHERE AGE = 25; sqlite> COMMIT; If you now check COMPANY table is still has the following records − ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 3 Teddy 23 Norway 20000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0
[ { "code": null, "e": 3010, "s": 2772, "text": "A transaction is a unit of work that is performed against a database. Transactions are units or sequences of work accomplished in a logical order, whether in a manual fashion by a user or automatically by some sort of a database program." }, { "code": null, "e": 3310, "s": 3010, "text": "A transaction is the propagation of one or more changes to the database. For example, if you are creating, updating, or deleting a record from the table, then you are performing transaction on the table. It is important to control transactions to ensure data integrity and to handle database errors." }, { "code": null, "e": 3438, "s": 3310, "text": "Practically, you will club many SQLite queries into a group and you will execute all of them together as part of a transaction." }, { "code": null, "e": 3537, "s": 3438, "text": "Transactions have the following four standard properties, usually referred to by the acronym ACID." }, { "code": null, "e": 3751, "s": 3537, "text": "Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state." }, { "code": null, "e": 3965, "s": 3751, "text": "Atomicity − Ensures that all operations within the work unit are completed successfully; otherwise, the transaction is aborted at the point of failure and previous operations are rolled back to their former state." }, { "code": null, "e": 4072, "s": 3965, "text": "Consistency − Ensures that the database properly changes states upon a successfully committed transaction." }, { "code": null, "e": 4179, "s": 4072, "text": "Consistency − Ensures that the database properly changes states upon a successfully committed transaction." }, { "code": null, "e": 4271, "s": 4179, "text": "Isolation − Enables transactions to operate independently of and transparent to each other." }, { "code": null, "e": 4363, "s": 4271, "text": "Isolation − Enables transactions to operate independently of and transparent to each other." }, { "code": null, "e": 4475, "s": 4363, "text": "Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure." }, { "code": null, "e": 4587, "s": 4475, "text": "Durability − Ensures that the result or effect of a committed transaction persists in case of a system failure." }, { "code": null, "e": 4654, "s": 4587, "text": "Following are the following commands used to control transactions:" }, { "code": null, "e": 4698, "s": 4654, "text": "BEGIN TRANSACTION − To start a transaction." }, { "code": null, "e": 4742, "s": 4698, "text": "BEGIN TRANSACTION − To start a transaction." }, { "code": null, "e": 4823, "s": 4742, "text": "COMMIT − To save the changes, alternatively you can use END TRANSACTION command." }, { "code": null, "e": 4904, "s": 4823, "text": "COMMIT − To save the changes, alternatively you can use END TRANSACTION command." }, { "code": null, "e": 4940, "s": 4904, "text": "ROLLBACK − To rollback the changes." }, { "code": null, "e": 4976, "s": 4940, "text": "ROLLBACK − To rollback the changes." }, { "code": null, "e": 5196, "s": 4976, "text": "Transactional control commands are only used with DML commands INSERT, UPDATE, and DELETE. They cannot be used while creating tables or dropping them because these operations are automatically committed in the database." }, { "code": null, "e": 5511, "s": 5196, "text": "Transactions can be started using BEGIN TRANSACTION or simply BEGIN command. Such transactions usually persist until the next COMMIT or ROLLBACK command is encountered. However, a transaction will also ROLLBACK if the database is closed or if an error occurs. Following is the simple syntax to start a transaction." }, { "code": null, "e": 5542, "s": 5511, "text": "BEGIN;\nor \nBEGIN TRANSACTION;\n" }, { "code": null, "e": 5649, "s": 5542, "text": "COMMIT command is the transactional command used to save changes invoked by a transaction to the database." }, { "code": null, "e": 5746, "s": 5649, "text": "COMMIT command saves all transactions to the database since the last COMMIT or ROLLBACK command." }, { "code": null, "e": 5790, "s": 5746, "text": "Following is the syntax for COMMIT command." }, { "code": null, "e": 5819, "s": 5790, "text": "COMMIT;\nor\nEND TRANSACTION;\n" }, { "code": null, "e": 5941, "s": 5819, "text": "ROLLBACK command is the transactional command used to undo transactions that have not already been saved to the database." }, { "code": null, "e": 6050, "s": 5941, "text": "ROLLBACK command can only be used to undo transactions since the last COMMIT or ROLLBACK command was issued." }, { "code": null, "e": 6096, "s": 6050, "text": "Following is the syntax for ROLLBACK command." }, { "code": null, "e": 6107, "s": 6096, "text": "ROLLBACK;\n" }, { "code": null, "e": 6115, "s": 6107, "text": "Example" }, { "code": null, "e": 6166, "s": 6115, "text": "Consider COMPANY table with the following records." }, { "code": null, "e": 6672, "s": 6166, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 6806, "s": 6672, "text": "Now, let's start a transaction and delete records from the table having age = 25. Then, use ROLLBACK command to undo all the changes." }, { "code": null, "e": 6883, "s": 6806, "text": "sqlite> BEGIN;\nsqlite> DELETE FROM COMPANY WHERE AGE = 25;\nsqlite> ROLLBACK;" }, { "code": null, "e": 6953, "s": 6883, "text": "Now, if you check COMPANY table, it still has the following records −" }, { "code": null, "e": 7459, "s": 6953, "text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0" }, { "code": null, "e": 7602, "s": 7459, "text": "Let's start another transaction and delete records from the table having age = 25 and finally we use COMMIT command to commit all the changes." }, { "code": null, "e": 7677, "s": 7602, "text": "sqlite> BEGIN;\nsqlite> DELETE FROM COMPANY WHERE AGE = 25;\nsqlite> COMMIT;" }, { "code": null, "e": 7745, "s": 7677, "text": "If you now check COMPANY table is still has the following records −" } ]
C# | Tuple Class
29 Nov, 2019 In C#, Tuple class is used to provide static methods for creating tuples and this class defined under System namespace. This class itself does not represent a tuple, but it provides static methods that are used to create an instance of the tuple type. Or in other words, the Tuple class provides helper methods that are used to instantiate tuple objects without having to explicitly specify the type of each tuple component. In tuple, you can only store elements from one to eight, if you try to store elements greater than eight without nested tuple, then the compiler will give an error. Generally, tuples are used: To represent multiple data into a single data set. To create, manipulate, and access data set. To return multiple values from a method without using out parameters. To pass multiple values to a method with the help of single parameters. Note: You can also, create a tuple with the help of the constructors which are provided by tuple classes, but in constructors, you have to specify the type of the elements present in the tuple as shown in the below example: Example: // C# program to create tuple // using tuple constructor.using System; class GFG { // Main method static public void Main() { // Creating tuple with seven elements // Using Tuple<T1, T2, T3, T4, T5, T6, // T7>(T1, T2, T3, T4, T5, T6, T7) constructor Tuple<int, int, int, int, int, int, int> My_Tuple = new Tuple<int, int, int, int, int, int, int>(22, 334, 54, 65, 76, 87, 98); Console.WriteLine("Element 1: " + My_Tuple.Item1); Console.WriteLine("Element 2: " + My_Tuple.Item2); Console.WriteLine("Element 3: " + My_Tuple.Item3); Console.WriteLine("Element 4: " + My_Tuple.Item4); Console.WriteLine("Element 5: " + My_Tuple.Item5); Console.WriteLine("Element 6: " + My_Tuple.Item6); Console.WriteLine("Element 7: " + My_Tuple.Item7); }} Element 1: 22 Element 2: 334 Element 3: 54 Element 4: 65 Element 5: 76 Element 6: 87 Element 7: 98 Example: // C# program to create 3-tuple // using create methodusing System; class GFG { // Main method static public void Main() { // Creating tuple with three elements // Using Create method var My_Tuple = Tuple.Create("Geeks", 2323, 'g'); Console.WriteLine("Element 1: " + My_Tuple.Item1); Console.WriteLine("Element 2: " + My_Tuple.Item2); Console.WriteLine("Element 3: " + My_Tuple.Item3); }} Element 1: Geeks Element 2: 2323 Element 3: g Reference: https://docs.microsoft.com/en-us/dotnet/api/system.tuple?view=netframework-4.8#definition CSharp-Tuple C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 618, "s": 28, "text": "In C#, Tuple class is used to provide static methods for creating tuples and this class defined under System namespace. This class itself does not represent a tuple, but it provides static methods that are used to create an instance of the tuple type. Or in other words, the Tuple class provides helper methods that are used to instantiate tuple objects without having to explicitly specify the type of each tuple component. In tuple, you can only store elements from one to eight, if you try to store elements greater than eight without nested tuple, then the compiler will give an error." }, { "code": null, "e": 646, "s": 618, "text": "Generally, tuples are used:" }, { "code": null, "e": 697, "s": 646, "text": "To represent multiple data into a single data set." }, { "code": null, "e": 741, "s": 697, "text": "To create, manipulate, and access data set." }, { "code": null, "e": 811, "s": 741, "text": "To return multiple values from a method without using out parameters." }, { "code": null, "e": 883, "s": 811, "text": "To pass multiple values to a method with the help of single parameters." }, { "code": null, "e": 1107, "s": 883, "text": "Note: You can also, create a tuple with the help of the constructors which are provided by tuple classes, but in constructors, you have to specify the type of the elements present in the tuple as shown in the below example:" }, { "code": null, "e": 1116, "s": 1107, "text": "Example:" }, { "code": "// C# program to create tuple // using tuple constructor.using System; class GFG { // Main method static public void Main() { // Creating tuple with seven elements // Using Tuple<T1, T2, T3, T4, T5, T6, // T7>(T1, T2, T3, T4, T5, T6, T7) constructor Tuple<int, int, int, int, int, int, int> My_Tuple = new Tuple<int, int, int, int, int, int, int>(22, 334, 54, 65, 76, 87, 98); Console.WriteLine(\"Element 1: \" + My_Tuple.Item1); Console.WriteLine(\"Element 2: \" + My_Tuple.Item2); Console.WriteLine(\"Element 3: \" + My_Tuple.Item3); Console.WriteLine(\"Element 4: \" + My_Tuple.Item4); Console.WriteLine(\"Element 5: \" + My_Tuple.Item5); Console.WriteLine(\"Element 6: \" + My_Tuple.Item6); Console.WriteLine(\"Element 7: \" + My_Tuple.Item7); }}", "e": 1965, "s": 1116, "text": null }, { "code": null, "e": 2065, "s": 1965, "text": "Element 1: 22\nElement 2: 334\nElement 3: 54\nElement 4: 65\nElement 5: 76\nElement 6: 87\nElement 7: 98\n" }, { "code": null, "e": 2074, "s": 2065, "text": "Example:" }, { "code": "// C# program to create 3-tuple // using create methodusing System; class GFG { // Main method static public void Main() { // Creating tuple with three elements // Using Create method var My_Tuple = Tuple.Create(\"Geeks\", 2323, 'g'); Console.WriteLine(\"Element 1: \" + My_Tuple.Item1); Console.WriteLine(\"Element 2: \" + My_Tuple.Item2); Console.WriteLine(\"Element 3: \" + My_Tuple.Item3); }}", "e": 2524, "s": 2074, "text": null }, { "code": null, "e": 2571, "s": 2524, "text": "Element 1: Geeks\nElement 2: 2323\nElement 3: g\n" }, { "code": null, "e": 2582, "s": 2571, "text": "Reference:" }, { "code": null, "e": 2672, "s": 2582, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.tuple?view=netframework-4.8#definition" }, { "code": null, "e": 2685, "s": 2672, "text": "CSharp-Tuple" }, { "code": null, "e": 2688, "s": 2685, "text": "C#" } ]
Web Scraping – Amazon Customer Reviews
08 Sep, 2021 In this article, we are going to see how we can scrape the amazon customer review using Beautiful Soup in Python. bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal. pip install bs4 requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal. pip install requests To begin with web scraping, we first have to do some setup. Import all the required modules. Get the cookies data for making the request to amazon, without this you can not able to scrape. Create a header that contains your request cookies, without cookies you can not scrape amazon data it always shows some error. This website will provide you, specific user agent. Pass the URL in the getdata() function(User Defined Function) to that will request to a URL, it returns a response. We are using get method to retrieve information from the given server using a given URL. Syntax: requests.get(url, args) Convert that data into HTML code and then Parse the HTML content using bs4. Syntax: soup = BeautifulSoup(r.content, ‘html5lib’) Parameters: r.content : It is the raw HTML content. html.parser : Specifying the HTML parser we want to use. Now filter the required data using soup.Find_all function. Program: Python3 # import moduleimport requestsfrom bs4 import BeautifulSoup HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \ AppleWebKit/537.36 (KHTML, like Gecko) \ Chrome/90.0.4430.212 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) # user define function# Scrape the datadef getdata(url): r = requests.get(url, headers=HEADERS) return r.text def html_code(url): # pass the url # into getdata function htmldata = getdata(url) soup = BeautifulSoup(htmldata, 'html.parser') # display html code return (soup) url = "https://www.amazon.in/Columbia-Mens-wind-\resistant-Glove/dp/B0772WVHPS/?_encoding=UTF8&pd_rd\_w=d9RS9&pf_rd_p=3d2ae0df-d986-4d1d-8c95-aa25d2ade606&pf\_rd_r=7MP3ZDYBBV88PYJ7KEMJ&pd_rd_r=550bec4d-5268-41d5-\87cb-8af40554a01e&pd_rd_wg=oy8v8&ref_=pd_gw_cr_cartx&th=1" soup = html_code(url)print(soup) Output: Note: This is only HTML code or Raw data. Now since the core setup is done let us see how scraping for a specific requirement can be done. Now find the customer list with span tag where class_ = a-profile-name. You can open the webpage in the browser and inspect the relevant element by pressing right-click as shown in the figure. You have to pass the tag name and attribute with its corresponding value to the find_all() function. Code: Python def cus_data(soup): # find the Html tag # with find() # and convert into string data_str = "" cus_list = [] for item in soup.find_all("span", class_="a-profile-name"): data_str = data_str + item.get_text() cus_list.append(data_str) data_str = "" return cus_list cus_res = cus_data(soup)print(cus_res) Output: [‘Amaze’, ‘Robert’, ‘D. Kong’, ‘Alexey’, ‘Charl’, ‘RBostillo’] Now find the customer review as same above methods. Find the unique class name with a specific tag, here we use div tag. Code: Python3 def cus_rev(soup): # find the Html tag # with find() # and convert into string data_str = "" for item in soup.find_all("div", class_="a-expander-content \ reviewText review-text-content a-expander-partial-collapse-content"): data_str = data_str + item.get_text() result = data_str.split("\n") return (result) rev_data = cus_rev(soup)rev_result = []for i in rev_data: if i is "": pass else: rev_result.append(i)rev_result Output: Here we will scrape product information like product name, ASIN number, Weight, dimension. By doing this we will use the span tag and with a specific unique class name. Code: Python3 def product_info(soup): # find the Html tag # with find() # and convert into string data_str = "" pro_info = [] for item in soup.find_all("ul", class_="a-unordered-list a-nostyle\ a-vertical a-spacing-none detail-bullet-list"): data_str = data_str + item.get_text() pro_info.append(data_str.split("\n")) data_str = "" return pro_info pro_result = product_info(soup) # Filter the required datafor item in pro_result: for j in item: if j is "": pass else: print(j) Output: Here we will extract the image link from the review of the product using the same as the above methods. The tag name and attribute of the tag is passed to findAll() as above. Code: Python3 def rev_img(soup): # find the Html tag # with find() # and convert into string data_str = "" cus_list = [] images = [] for img in soup.findAll('img', class_="cr-lightbox-image-thumbnail"): images.append(img.get('src')) return images img_result = rev_img(soup)img_result Output: Here we will save the details into the CSV file, We will convert the data into dataframe and then export it into the CSV, Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. Syntax : to_csv(parameters)Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. Code: Python3 import pandas as pd # initialise data of lists.data = {'Name': cus_res, 'review': rev_result} # Create DataFramedf = pd.DataFrame(data) # Save the output.df.to_csv('amazon_review.csv') Output: sweetyty abhishek0719kadiyan Picked Python BeautifulSoup Python-requests Web-scraping Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Sep, 2021" }, { "code": null, "e": 142, "s": 28, "text": "In this article, we are going to see how we can scrape the amazon customer review using Beautiful Soup in Python." }, { "code": null, "e": 335, "s": 142, "text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 351, "s": 335, "text": "pip install bs4" }, { "code": null, "e": 533, "s": 351, "text": "requests: Request allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python. To install this type the below command in the terminal." }, { "code": null, "e": 554, "s": 533, "text": "pip install requests" }, { "code": null, "e": 922, "s": 554, "text": "To begin with web scraping, we first have to do some setup. Import all the required modules. Get the cookies data for making the request to amazon, without this you can not able to scrape. Create a header that contains your request cookies, without cookies you can not scrape amazon data it always shows some error. This website will provide you, specific user agent." }, { "code": null, "e": 1127, "s": 922, "text": "Pass the URL in the getdata() function(User Defined Function) to that will request to a URL, it returns a response. We are using get method to retrieve information from the given server using a given URL." }, { "code": null, "e": 1136, "s": 1127, "text": "Syntax: " }, { "code": null, "e": 1160, "s": 1136, "text": "requests.get(url, args)" }, { "code": null, "e": 1236, "s": 1160, "text": "Convert that data into HTML code and then Parse the HTML content using bs4." }, { "code": null, "e": 1288, "s": 1236, "text": "Syntax: soup = BeautifulSoup(r.content, ‘html5lib’)" }, { "code": null, "e": 1300, "s": 1288, "text": "Parameters:" }, { "code": null, "e": 1340, "s": 1300, "text": "r.content : It is the raw HTML content." }, { "code": null, "e": 1397, "s": 1340, "text": "html.parser : Specifying the HTML parser we want to use." }, { "code": null, "e": 1456, "s": 1397, "text": "Now filter the required data using soup.Find_all function." }, { "code": null, "e": 1465, "s": 1456, "text": "Program:" }, { "code": null, "e": 1473, "s": 1465, "text": "Python3" }, { "code": "# import moduleimport requestsfrom bs4 import BeautifulSoup HEADERS = ({'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) \\ AppleWebKit/537.36 (KHTML, like Gecko) \\ Chrome/90.0.4430.212 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5'}) # user define function# Scrape the datadef getdata(url): r = requests.get(url, headers=HEADERS) return r.text def html_code(url): # pass the url # into getdata function htmldata = getdata(url) soup = BeautifulSoup(htmldata, 'html.parser') # display html code return (soup) url = \"https://www.amazon.in/Columbia-Mens-wind-\\resistant-Glove/dp/B0772WVHPS/?_encoding=UTF8&pd_rd\\_w=d9RS9&pf_rd_p=3d2ae0df-d986-4d1d-8c95-aa25d2ade606&pf\\_rd_r=7MP3ZDYBBV88PYJ7KEMJ&pd_rd_r=550bec4d-5268-41d5-\\87cb-8af40554a01e&pd_rd_wg=oy8v8&ref_=pd_gw_cr_cartx&th=1\" soup = html_code(url)print(soup)", "e": 2380, "s": 1473, "text": null }, { "code": null, "e": 2388, "s": 2380, "text": "Output:" }, { "code": null, "e": 2430, "s": 2388, "text": "Note: This is only HTML code or Raw data." }, { "code": null, "e": 2527, "s": 2430, "text": "Now since the core setup is done let us see how scraping for a specific requirement can be done." }, { "code": null, "e": 2720, "s": 2527, "text": "Now find the customer list with span tag where class_ = a-profile-name. You can open the webpage in the browser and inspect the relevant element by pressing right-click as shown in the figure." }, { "code": null, "e": 2821, "s": 2720, "text": "You have to pass the tag name and attribute with its corresponding value to the find_all() function." }, { "code": null, "e": 2827, "s": 2821, "text": "Code:" }, { "code": null, "e": 2834, "s": 2827, "text": "Python" }, { "code": "def cus_data(soup): # find the Html tag # with find() # and convert into string data_str = \"\" cus_list = [] for item in soup.find_all(\"span\", class_=\"a-profile-name\"): data_str = data_str + item.get_text() cus_list.append(data_str) data_str = \"\" return cus_list cus_res = cus_data(soup)print(cus_res)", "e": 3182, "s": 2834, "text": null }, { "code": null, "e": 3190, "s": 3182, "text": "Output:" }, { "code": null, "e": 3253, "s": 3190, "text": "[‘Amaze’, ‘Robert’, ‘D. Kong’, ‘Alexey’, ‘Charl’, ‘RBostillo’]" }, { "code": null, "e": 3374, "s": 3253, "text": "Now find the customer review as same above methods. Find the unique class name with a specific tag, here we use div tag." }, { "code": null, "e": 3380, "s": 3374, "text": "Code:" }, { "code": null, "e": 3388, "s": 3380, "text": "Python3" }, { "code": "def cus_rev(soup): # find the Html tag # with find() # and convert into string data_str = \"\" for item in soup.find_all(\"div\", class_=\"a-expander-content \\ reviewText review-text-content a-expander-partial-collapse-content\"): data_str = data_str + item.get_text() result = data_str.split(\"\\n\") return (result) rev_data = cus_rev(soup)rev_result = []for i in rev_data: if i is \"\": pass else: rev_result.append(i)rev_result", "e": 3867, "s": 3388, "text": null }, { "code": null, "e": 3875, "s": 3867, "text": "Output:" }, { "code": null, "e": 4044, "s": 3875, "text": "Here we will scrape product information like product name, ASIN number, Weight, dimension. By doing this we will use the span tag and with a specific unique class name." }, { "code": null, "e": 4050, "s": 4044, "text": "Code:" }, { "code": null, "e": 4058, "s": 4050, "text": "Python3" }, { "code": "def product_info(soup): # find the Html tag # with find() # and convert into string data_str = \"\" pro_info = [] for item in soup.find_all(\"ul\", class_=\"a-unordered-list a-nostyle\\ a-vertical a-spacing-none detail-bullet-list\"): data_str = data_str + item.get_text() pro_info.append(data_str.split(\"\\n\")) data_str = \"\" return pro_info pro_result = product_info(soup) # Filter the required datafor item in pro_result: for j in item: if j is \"\": pass else: print(j)", "e": 4613, "s": 4058, "text": null }, { "code": null, "e": 4621, "s": 4613, "text": "Output:" }, { "code": null, "e": 4796, "s": 4621, "text": "Here we will extract the image link from the review of the product using the same as the above methods. The tag name and attribute of the tag is passed to findAll() as above." }, { "code": null, "e": 4802, "s": 4796, "text": "Code:" }, { "code": null, "e": 4810, "s": 4802, "text": "Python3" }, { "code": "def rev_img(soup): # find the Html tag # with find() # and convert into string data_str = \"\" cus_list = [] images = [] for img in soup.findAll('img', class_=\"cr-lightbox-image-thumbnail\"): images.append(img.get('src')) return images img_result = rev_img(soup)img_result", "e": 5116, "s": 4810, "text": null }, { "code": null, "e": 5124, "s": 5116, "text": "Output:" }, { "code": null, "e": 5379, "s": 5124, "text": "Here we will save the details into the CSV file, We will convert the data into dataframe and then export it into the CSV, Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file." }, { "code": null, "e": 5419, "s": 5379, "text": "Syntax : to_csv(parameters)Parameters :" }, { "code": null, "e": 5510, "s": 5419, "text": "path_or_buf : File path or object, if None is provided the result is returned as a string." }, { "code": null, "e": 5516, "s": 5510, "text": "Code:" }, { "code": null, "e": 5524, "s": 5516, "text": "Python3" }, { "code": "import pandas as pd # initialise data of lists.data = {'Name': cus_res, 'review': rev_result} # Create DataFramedf = pd.DataFrame(data) # Save the output.df.to_csv('amazon_review.csv')", "e": 5719, "s": 5524, "text": null }, { "code": null, "e": 5727, "s": 5719, "text": "Output:" }, { "code": null, "e": 5736, "s": 5727, "text": "sweetyty" }, { "code": null, "e": 5756, "s": 5736, "text": "abhishek0719kadiyan" }, { "code": null, "e": 5763, "s": 5756, "text": "Picked" }, { "code": null, "e": 5784, "s": 5763, "text": "Python BeautifulSoup" }, { "code": null, "e": 5800, "s": 5784, "text": "Python-requests" }, { "code": null, "e": 5813, "s": 5800, "text": "Web-scraping" }, { "code": null, "e": 5820, "s": 5813, "text": "Python" }, { "code": null, "e": 5918, "s": 5820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5950, "s": 5918, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5977, "s": 5950, "text": "Python Classes and Objects" }, { "code": null, "e": 5998, "s": 5977, "text": "Python OOPs Concepts" }, { "code": null, "e": 6021, "s": 5998, "text": "Introduction To PYTHON" }, { "code": null, "e": 6077, "s": 6021, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6108, "s": 6077, "text": "Python | os.path.join() method" }, { "code": null, "e": 6150, "s": 6108, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6192, "s": 6150, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 6231, "s": 6192, "text": "Python | Get unique values from a list" } ]
Lexicographically smallest string obtained after concatenating array
07 Jul, 2022 Given n strings, concatenate them in an order that produces the lexicographically smallest possible string.Examples: Input : a[] = ["c", "cb", "cba"] Output : cbacbc Possible strings are ccbcba, ccbacb, cbccba, cbcbac, cbacbc and cbaccb. Among all these strings, cbacbc is the lexicographically smallest. Input : a[] = ["aa", "ab", "aaa"] Output : aaaaaab One might think that sorting the given strings in the lexicographical order and then concatenating them produces the correct output. This approach produces the correct output for inputs like [“a”, “ab”, “abc”]. However, applying this method on [“c”, “cb”, “cba”] produces the wrong input and hence this approach is incorrect.The correct approach is to use a regular sorting algorithm. When two strings a and b are compared to decide if they have to be swapped or not, do not check if a is lexicographically smaller than b or not. Instead check if appending b at the end of a produces a lexicographically smaller string or appending a at the end of b does. This approach works because we want the concatenated string to be lexicographically small, not the individual strings to be in the lexicographical order. C++ Java Python 3 C# Javascript // CPP code to find the lexicographically// smallest string#include <bits/stdc++.h>using namespace std; // Compares two strings by checking if// which of the two concatenations causes// lexicographically smaller string.bool compare(string a, string b){ return (a+b < b+a);} string lexSmallest(string a[], int n){ // Sort strings using above compare() sort(a, a+n, compare); // Concatenating sorted strings string answer = ""; for (int i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codeint main(){ string a[] = { "c", "cb", "cba" }; int n = sizeof(a)/sizeof(a[0]); cout << lexSmallest(a, n); return 0;} // Java code to find the lexicographically// smallest string class GFG { // function to sort the// array of stringstatic void sort(String a[], int n){ //sort the array for(int i = 0;i < n;i++) { for(int j = i + 1;j < n;j++) { // comparing which of the // two concatenation causes // lexicographically smaller // string if((a[i] + a[j]).compareTo(a[j] + a[i]) > 0) { String s = a[i]; a[i] = a[j]; a[j] = s; } } }} static String lexsmallest(String a[], int n){ // Sort strings sort(a,n); // Concatenating sorted strings String answer = ""; for (int i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codepublic static void main(String args[]){ String a[] = {"c", "cb", "cba"}; int n = 3; System.out.println("lexicographically smallest string = " + lexsmallest(a, n)); }} // This code is contributed by Arnab Kundu # Python 3 code to find the lexicographically# smallest stringdef lexSmallest(a, n): # Sort strings using above compare() for i in range(0,n): for j in range(i+1,n): if(a[i]+a[j]>a[j]+a[i]): s=a[i] a[i]=a[j] a[j]=s # Concatenating sorted strings answer = "" for i in range( n): answer += a[i] return answer # Driver codeif __name__ == "__main__": a = [ "c", "cb", "cba" ] n = len(a) print(lexSmallest(a, n)) # This code is contributed by vibhu karnwal // C# code to find// the lexicographically// smallest stringusing System; class GFG { // function to sort the// array of stringstatic void sort(String []a, int n){ //sort the array for(int i = 0;i < n;i++) { for(int j = i + 1;j < n;j++) { // comparing which of the // two concatenation causes // lexicographically smaller // string if((a[i] + a[j]).CompareTo(a[j] + a[i]) > 0) { String s = a[i]; a[i] = a[j]; a[j] = s; } } }} static String lexsmallest(String []a, int n){ // Sort strings sort(a,n); // Concatenating sorted // strings String answer = ""; for (int i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codepublic static void Main(){ String []a = {"c", "cb", "cba"}; int n = 3; Console.Write("lexicographically smallest string = " + lexsmallest(a, n)); }} // This code is contributed by nitin mittal <script>// Javascript code to find the lexicographically// smallest string // function to sort the// array of stringfunction sort(a,n){ // sort the array for(let i = 0;i < n;i++) { for(let j = i + 1;j < n;j++) { // comparing which of the // two concatenation causes // lexicographically smaller // string if((a[i] + a[j])>(a[j] + a[i]) ) { let s = a[i]; a[i] = a[j]; a[j] = s; } } }} function lexsmallest(a,n){ // Sort strings sort(a,n); // Concatenating sorted strings let answer = ""; for (let i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codelet a=["c", "cb", "cba"];let n = 3;document.write("lexicographically smallest string = " + lexsmallest(a, n)); // This code is contributed by rag2127</script> cbacbc Time complexity : The above code runs in O(M * N * logN) where N is number of strings and M is maximum length of a string. Auxiliary Space: O(n) This article is contributed by Aarti_Rathi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. andrew1234 nitin mittal ukasp rag2127 vknwl077 akshaysingh98088 adi1212 lexicographic-ordering Sorting Strings Strings Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Time Complexities of all Sorting Algorithms Merge two sorted arrays Count Inversions in an array | Set 1 (Using Merge Sort) Radix Sort Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Check for Balanced Brackets in an expression (well-formedness) using Stack
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 173, "s": 54, "text": "Given n strings, concatenate them in an order that produces the lexicographically smallest possible string.Examples: " }, { "code": null, "e": 418, "s": 173, "text": "Input : a[] = [\"c\", \"cb\", \"cba\"]\nOutput : cbacbc\nPossible strings are ccbcba, ccbacb, \ncbccba, cbcbac, cbacbc and cbaccb. \nAmong all these strings, cbacbc is \nthe lexicographically smallest.\n\nInput : a[] = [\"aa\", \"ab\", \"aaa\"]\nOutput : aaaaaab" }, { "code": null, "e": 1232, "s": 420, "text": "One might think that sorting the given strings in the lexicographical order and then concatenating them produces the correct output. This approach produces the correct output for inputs like [“a”, “ab”, “abc”]. However, applying this method on [“c”, “cb”, “cba”] produces the wrong input and hence this approach is incorrect.The correct approach is to use a regular sorting algorithm. When two strings a and b are compared to decide if they have to be swapped or not, do not check if a is lexicographically smaller than b or not. Instead check if appending b at the end of a produces a lexicographically smaller string or appending a at the end of b does. This approach works because we want the concatenated string to be lexicographically small, not the individual strings to be in the lexicographical order. " }, { "code": null, "e": 1236, "s": 1232, "text": "C++" }, { "code": null, "e": 1241, "s": 1236, "text": "Java" }, { "code": null, "e": 1250, "s": 1241, "text": "Python 3" }, { "code": null, "e": 1253, "s": 1250, "text": "C#" }, { "code": null, "e": 1264, "s": 1253, "text": "Javascript" }, { "code": "// CPP code to find the lexicographically// smallest string#include <bits/stdc++.h>using namespace std; // Compares two strings by checking if// which of the two concatenations causes// lexicographically smaller string.bool compare(string a, string b){ return (a+b < b+a);} string lexSmallest(string a[], int n){ // Sort strings using above compare() sort(a, a+n, compare); // Concatenating sorted strings string answer = \"\"; for (int i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codeint main(){ string a[] = { \"c\", \"cb\", \"cba\" }; int n = sizeof(a)/sizeof(a[0]); cout << lexSmallest(a, n); return 0;}", "e": 1923, "s": 1264, "text": null }, { "code": "// Java code to find the lexicographically// smallest string class GFG { // function to sort the// array of stringstatic void sort(String a[], int n){ //sort the array for(int i = 0;i < n;i++) { for(int j = i + 1;j < n;j++) { // comparing which of the // two concatenation causes // lexicographically smaller // string if((a[i] + a[j]).compareTo(a[j] + a[i]) > 0) { String s = a[i]; a[i] = a[j]; a[j] = s; } } }} static String lexsmallest(String a[], int n){ // Sort strings sort(a,n); // Concatenating sorted strings String answer = \"\"; for (int i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codepublic static void main(String args[]){ String a[] = {\"c\", \"cb\", \"cba\"}; int n = 3; System.out.println(\"lexicographically smallest string = \" + lexsmallest(a, n)); }} // This code is contributed by Arnab Kundu", "e": 3004, "s": 1923, "text": null }, { "code": "# Python 3 code to find the lexicographically# smallest stringdef lexSmallest(a, n): # Sort strings using above compare() for i in range(0,n): for j in range(i+1,n): if(a[i]+a[j]>a[j]+a[i]): s=a[i] a[i]=a[j] a[j]=s # Concatenating sorted strings answer = \"\" for i in range( n): answer += a[i] return answer # Driver codeif __name__ == \"__main__\": a = [ \"c\", \"cb\", \"cba\" ] n = len(a) print(lexSmallest(a, n)) # This code is contributed by vibhu karnwal ", "e": 3514, "s": 3004, "text": null }, { "code": "// C# code to find// the lexicographically// smallest stringusing System; class GFG { // function to sort the// array of stringstatic void sort(String []a, int n){ //sort the array for(int i = 0;i < n;i++) { for(int j = i + 1;j < n;j++) { // comparing which of the // two concatenation causes // lexicographically smaller // string if((a[i] + a[j]).CompareTo(a[j] + a[i]) > 0) { String s = a[i]; a[i] = a[j]; a[j] = s; } } }} static String lexsmallest(String []a, int n){ // Sort strings sort(a,n); // Concatenating sorted // strings String answer = \"\"; for (int i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codepublic static void Main(){ String []a = {\"c\", \"cb\", \"cba\"}; int n = 3; Console.Write(\"lexicographically smallest string = \" + lexsmallest(a, n)); }} // This code is contributed by nitin mittal", "e": 4625, "s": 3514, "text": null }, { "code": "<script>// Javascript code to find the lexicographically// smallest string // function to sort the// array of stringfunction sort(a,n){ // sort the array for(let i = 0;i < n;i++) { for(let j = i + 1;j < n;j++) { // comparing which of the // two concatenation causes // lexicographically smaller // string if((a[i] + a[j])>(a[j] + a[i]) ) { let s = a[i]; a[i] = a[j]; a[j] = s; } } }} function lexsmallest(a,n){ // Sort strings sort(a,n); // Concatenating sorted strings let answer = \"\"; for (let i = 0; i < n; i++) answer += a[i]; return answer;} // Driver codelet a=[\"c\", \"cb\", \"cba\"];let n = 3;document.write(\"lexicographically smallest string = \" + lexsmallest(a, n)); // This code is contributed by rag2127</script>", "e": 5595, "s": 4625, "text": null }, { "code": null, "e": 5602, "s": 5595, "text": "cbacbc" }, { "code": null, "e": 5727, "s": 5604, "text": "Time complexity : The above code runs in O(M * N * logN) where N is number of strings and M is maximum length of a string." }, { "code": null, "e": 5749, "s": 5727, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 6170, "s": 5749, "text": "This article is contributed by Aarti_Rathi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 6181, "s": 6170, "text": "andrew1234" }, { "code": null, "e": 6194, "s": 6181, "text": "nitin mittal" }, { "code": null, "e": 6200, "s": 6194, "text": "ukasp" }, { "code": null, "e": 6208, "s": 6200, "text": "rag2127" }, { "code": null, "e": 6217, "s": 6208, "text": "vknwl077" }, { "code": null, "e": 6234, "s": 6217, "text": "akshaysingh98088" }, { "code": null, "e": 6242, "s": 6234, "text": "adi1212" }, { "code": null, "e": 6265, "s": 6242, "text": "lexicographic-ordering" }, { "code": null, "e": 6273, "s": 6265, "text": "Sorting" }, { "code": null, "e": 6281, "s": 6273, "text": "Strings" }, { "code": null, "e": 6289, "s": 6281, "text": "Strings" }, { "code": null, "e": 6297, "s": 6289, "text": "Sorting" }, { "code": null, "e": 6395, "s": 6297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6418, "s": 6395, "text": "std::sort() in C++ STL" }, { "code": null, "e": 6462, "s": 6418, "text": "Time Complexities of all Sorting Algorithms" }, { "code": null, "e": 6486, "s": 6462, "text": "Merge two sorted arrays" }, { "code": null, "e": 6542, "s": 6486, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" }, { "code": null, "e": 6553, "s": 6542, "text": "Radix Sort" }, { "code": null, "e": 6599, "s": 6553, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 6624, "s": 6599, "text": "Reverse a string in Java" }, { "code": null, "e": 6684, "s": 6624, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6699, "s": 6684, "text": "C++ Data Types" } ]
Matplotlib.pyplot.pcolor() function in Python
25 Nov, 2020 Matplotlib is the well-known Python package used in data visualization. Numpy is the numerical mathematics extension of Matplotlib. Matplotlib is capable of producing high-quality graphs, charts, and figures. Matplotlib produces object-oriented API for embedding plots into projects using GUI toolkits like Tkinter, wxPython, or Qt. John D. Hunter was the original developer of Matplotlib and it is distributed under a BSD-style license. Matplotlib contains a wide range of functions that help in performing different tasks, one of them is matplotlib.pyplot.pcolor() function. The pcolor() function in the pyplot module of the Matplotlib library helps to create a pseudo-color plot with a non-regular rectangular grid. Syntax: matplotlib.pyplot.pcolor(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, data=None, **kwargs)Call Signature: pcolor([X, Y,] C, **kwargs)Parameters:C: Denotes a scaler 2-D arrayX, Y: array_like, optional, coordinates of quadrilateral cornerscmap: str or Colormap, optionalnorm: Normalize, optionalvmin, vmax: scaler, optionaledgecolors: {‘none’, None, ‘face’, color sequence}, optionalalpha: scaler, optionalsnap: bool, optionalOther Parameters:antialiaseds: bool, optional**kwargsReturns: The function returns a collection i.e matplotlib.collections.Collection Note: In case of larger arrays, matplotlib.pyplot.pcolor() works very slow. Below examples demonstrate the working of matplotlib.pyplot.pcolor() function: Example 1: Generating images using pcolor() function With the help of pcolor() function, we can generate 2-D image-style plots, as shown below Python3 # Demonstration of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm Z = np.random.rand(4, 12) fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(Z)ax0.set_title('No edge image') c = ax1.pcolor(Z, edgecolors='k', linewidths=5)ax1.set_title('Thick edges image') fig.tight_layout()plt.show() Output: Example 2: Working of pcolor() with Log scale Python3 # Demonstration of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm N = 100X, Y = np.mgrid[-4:4:complex(0, N), -4:4:complex(0, N)] # Image show that a low hump with a spike coming out.# We need a z/colour axis on a log scale in order# to watch both hump and spike.Z1 = np.exp(-(X)**2 - (Y)**2)Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z,norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap=plt.cm.autumn) fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap=plt.cm.autumn)fig.colorbar(c, ax=ax1) plt.show() Output: Matplotlib Pyplot-class Python-matplotlib Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Nov, 2020" }, { "code": null, "e": 467, "s": 28, "text": "Matplotlib is the well-known Python package used in data visualization. Numpy is the numerical mathematics extension of Matplotlib. Matplotlib is capable of producing high-quality graphs, charts, and figures. Matplotlib produces object-oriented API for embedding plots into projects using GUI toolkits like Tkinter, wxPython, or Qt. John D. Hunter was the original developer of Matplotlib and it is distributed under a BSD-style license. " }, { "code": null, "e": 748, "s": 467, "text": "Matplotlib contains a wide range of functions that help in performing different tasks, one of them is matplotlib.pyplot.pcolor() function. The pcolor() function in the pyplot module of the Matplotlib library helps to create a pseudo-color plot with a non-regular rectangular grid." }, { "code": null, "e": 1332, "s": 748, "text": "Syntax: matplotlib.pyplot.pcolor(*args, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, data=None, **kwargs)Call Signature: pcolor([X, Y,] C, **kwargs)Parameters:C: Denotes a scaler 2-D arrayX, Y: array_like, optional, coordinates of quadrilateral cornerscmap: str or Colormap, optionalnorm: Normalize, optionalvmin, vmax: scaler, optionaledgecolors: {‘none’, None, ‘face’, color sequence}, optionalalpha: scaler, optionalsnap: bool, optionalOther Parameters:antialiaseds: bool, optional**kwargsReturns: The function returns a collection i.e matplotlib.collections.Collection" }, { "code": null, "e": 1408, "s": 1332, "text": "Note: In case of larger arrays, matplotlib.pyplot.pcolor() works very slow." }, { "code": null, "e": 1487, "s": 1408, "text": "Below examples demonstrate the working of matplotlib.pyplot.pcolor() function:" }, { "code": null, "e": 1540, "s": 1487, "text": "Example 1: Generating images using pcolor() function" }, { "code": null, "e": 1630, "s": 1540, "text": "With the help of pcolor() function, we can generate 2-D image-style plots, as shown below" }, { "code": null, "e": 1638, "s": 1630, "text": "Python3" }, { "code": "# Demonstration of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm Z = np.random.rand(4, 12) fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(Z)ax0.set_title('No edge image') c = ax1.pcolor(Z, edgecolors='k', linewidths=5)ax1.set_title('Thick edges image') fig.tight_layout()plt.show()", "e": 1990, "s": 1638, "text": null }, { "code": null, "e": 1998, "s": 1990, "text": "Output:" }, { "code": null, "e": 2044, "s": 1998, "text": "Example 2: Working of pcolor() with Log scale" }, { "code": null, "e": 2052, "s": 2044, "text": "Python3" }, { "code": "# Demonstration of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm N = 100X, Y = np.mgrid[-4:4:complex(0, N), -4:4:complex(0, N)] # Image show that a low hump with a spike coming out.# We need a z/colour axis on a log scale in order# to watch both hump and spike.Z1 = np.exp(-(X)**2 - (Y)**2)Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)Z = Z1 + 50 * Z2 fig, (ax0, ax1) = plt.subplots(2, 1) c = ax0.pcolor(X, Y, Z,norm=LogNorm(vmin=Z.min(), vmax=Z.max()), cmap=plt.cm.autumn) fig.colorbar(c, ax=ax0) c = ax1.pcolor(X, Y, Z, cmap=plt.cm.autumn)fig.colorbar(c, ax=ax1) plt.show()", "e": 2689, "s": 2052, "text": null }, { "code": null, "e": 2697, "s": 2689, "text": "Output:" }, { "code": null, "e": 2721, "s": 2697, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 2739, "s": 2721, "text": "Python-matplotlib" }, { "code": null, "e": 2763, "s": 2739, "text": "Technical Scripter 2020" }, { "code": null, "e": 2770, "s": 2763, "text": "Python" }, { "code": null, "e": 2789, "s": 2770, "text": "Technical Scripter" }, { "code": null, "e": 2887, "s": 2789, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2932, "s": 2887, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2982, "s": 2932, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2998, "s": 2982, "text": "Deque in Python" }, { "code": null, "e": 3014, "s": 2998, "text": "Queue in Python" }, { "code": null, "e": 3036, "s": 3014, "text": "Defaultdict in Python" }, { "code": null, "e": 3078, "s": 3036, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3105, "s": 3078, "text": "Python Classes and Objects" }, { "code": null, "e": 3128, "s": 3105, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 3147, "s": 3128, "text": "reduce() in Python" } ]
zlib.compress(s) in python
06 Mar, 2020 With the help of zlib.compress(s) method, we can get compress the bytes of string by using zlib.compress(s) method. Syntax : zlib.compress(string)Return : Return compressed string. Example #1 :In this example we can see that by using zlib.compress(s) method, we are able to compress the string in the byte format by using this method. # import zlib and compressimport zlibs = b'This is GFG author, and final year student.'print(len(s)) # using zlib.compress(s) methodt = zlib.compress(s)print(len(t)) Output : 4349 Example #2 : # import zlib and compressimport zlibs = b'GeeksForGeeks@12345678'print(len(s)) # using zlib.compress(s) methodt = zlib.compress(s)print(len(t)) Output : 2227 Python-Miscellaneous python-zlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Mar, 2020" }, { "code": null, "e": 144, "s": 28, "text": "With the help of zlib.compress(s) method, we can get compress the bytes of string by using zlib.compress(s) method." }, { "code": null, "e": 209, "s": 144, "text": "Syntax : zlib.compress(string)Return : Return compressed string." }, { "code": null, "e": 363, "s": 209, "text": "Example #1 :In this example we can see that by using zlib.compress(s) method, we are able to compress the string in the byte format by using this method." }, { "code": "# import zlib and compressimport zlibs = b'This is GFG author, and final year student.'print(len(s)) # using zlib.compress(s) methodt = zlib.compress(s)print(len(t))", "e": 530, "s": 363, "text": null }, { "code": null, "e": 539, "s": 530, "text": "Output :" }, { "code": null, "e": 544, "s": 539, "text": "4349" }, { "code": null, "e": 557, "s": 544, "text": "Example #2 :" }, { "code": "# import zlib and compressimport zlibs = b'GeeksForGeeks@12345678'print(len(s)) # using zlib.compress(s) methodt = zlib.compress(s)print(len(t))", "e": 703, "s": 557, "text": null }, { "code": null, "e": 712, "s": 703, "text": "Output :" }, { "code": null, "e": 717, "s": 712, "text": "2227" }, { "code": null, "e": 738, "s": 717, "text": "Python-Miscellaneous" }, { "code": null, "e": 750, "s": 738, "text": "python-zlib" }, { "code": null, "e": 757, "s": 750, "text": "Python" } ]
Count unique subsequences of length K
13 Sep, 2021 Given an array of N numbers and an integer K. The task is to print the number of unique subsequences possible of length K. Examples: Input : a[] = {1, 2, 3, 4}, k = 3 Output : 4. Unique Subsequences are: {1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4} Input: a[] = {1, 1, 1, 2, 2, 2 }, k = 3 Output : 4 Unique Subsequences are {1, 1, 1}, {1, 1, 2}, {1, 2, 2}, {2, 2, 2} Approach: There is a well-known formula how many subsequences of fixed length K can be chosen from N unique objects. But the problem here has several differences. One among them is the order in subsequences is important and must be preserved as in the original sequence. For such a problem there can be no ready combinatorics formula because the results depend on the order of the original array. The main idea is to deal recurrently by the length of the subsequence. On each recurrent step, move from the end to the beginning and count the unique combinations using the count of shorter unique combinations from the previous step. More strictly on every step j we keep an array of length N and every element in the place p means how many unique subsequences with length j we found to the right of the element in place i, including i itself. Below is the implementation of the above approach. C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; // Function which returns the numbe of// unique subsequences of length Kint solution(vector<int>& A, int k){ // seiz of the vector // which does is constant const int N = A.size(); // bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion vector<int> v1(N, 0); vector<int> v2(N, 0); vector<int> v3(N, 0); // initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // initiate all other elements of k = 1 for (int i = N - 2; i >= 0; i--) { // initialize the front element // to vector v2 v2[i] = v2[i + 1]; // if element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // iterate for all possible values of K for (int j = 1; j < k; j++) { // fill the vectors with 0 fill(v3.begin(), v3.end(), 0); // fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last no unique // subarray can be formed v1[N - 1] = 0; // Iterate for all index from which unique // subsequences can be formed for (int i = N - 2; i >= 0; i--) { // add the number of subsequence formed // from the next index v1[i] = v1[i + 1]; // start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } // prepare the next iteration // by filling v2 in v1 v2 = v1; } // last answer is stored in v2 return v2[0];} // Function to push the vector into an array// and print all the unique subarraysvoid solve(int a[], int n, int k){ vector<int> v; // fill the vector with a[] v.assign(a, a + n); // Function call to print the count // of unique subsequences of size K cout << solution(v, k);} // Driver Codeint main(){ int a[] = { 1, 2, 3, 4 }; int n = sizeof(a) / sizeof(a[0]); int k = 3; solve(a, n, k); return 0;} import java.util.*; class GFG{ // Function which returns the numbe of// unique subsequences of length Kstatic int solution(int[] A, int N, int k){ // Bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion int[] v1 = new int[N]; int[] v2 = new int[N]; int[] v3 = new int[N]; // Initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // Initiate all other elements of k = 1 for(int i = N - 2; i >= 0; i--) { // Initialize the front element // to vector v2 v2[i] = v2[i + 1]; // If element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // Iterate for all possible values of K for(int j = 1; j < k; j++) { // Fill the vectors with 0 Arrays.fill(v3, 0); // Fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last // no unique subarray can be formed v1[N - 1] = 0; // Iterate for all index from which // unique subsequences can be formed for(int i = N - 2; i >= 0; i--) { // Add the number of subsequence // formed from the next index v1[i] = v1[i + 1]; // Start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } } // Last answer is stored in v2 return v2[0];} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 2, 3, 4 }; int n = a.length; int k = 3; System.out.print(solution(a, n, k));}} // This code is contributed by amal kumar choubey # Function which returns the numbe of# unique subsequences of length Kdef solution( A, k): # seiz of the vector # which does is constant N = len(A) # bases cases if (N < k or N < 1 or k < 1): return 0 if (N == k): return 1 # Prepare arrays for recursion v1 = [0]*(N) v2 = [0]*N v3 = [0]*N # initiate separately for k = 1 # initiate the last element v2[N - 1] = 1 v3[A[N - 1] - 1] = 1 # initiate all other elements of k = 1 for i in range(N - 2,-1,-1): # initialize the front element # to vector v2 v2[i] = v2[i + 1] # if element v[a[i]-1] is 0 # then increment it in vector v2 if (v3[A[i] - 1] == 0): v2[i] += 1 v3[A[i] - 1] = 1 # iterate for all possible values of K for j in range( 1, k) : # fill the vectors with 0 v3 = [0]*N # fill(v1.begin(), v1.end(), 0) # the last must be 0 as from last no unique # subarray can be formed v1[N - 1] = 0 # Iterate for all index from which unique # subsequences can be formed for i in range( N - 2, -1, -1) : # add the number of subsequence formed # from the next index v1[i] = v1[i + 1] # start with combinations on the # next index v1[i] = v1[i] + v2[i + 1] # Remove the elements which have # already been counted v1[i] = v1[i] - v3[A[i] - 1] # Update the number used v3[A[i] - 1] = v2[i + 1] # prepare the next iteration # by filling v2 in v1 for i in range(len(v1)): v2[i] = v1[i] # last answer is stored in v2 return v2[0] # Function to push the vector into an array# and print all the unique subarraysdef solve(a, n, k): # fill the vector with a[] v = a # Function call to print the count # of unique subsequences of size K print( solution(v, k)) # Driver Codeif __name__ == "__main__": a = [ 1, 2, 3, 4 ] n = len(a) k = 3 solve(a, n, k) # This code is contributed by chitranayal using System;class GFG{ // Function which returns the numbe of// unique subsequences of length Kstatic int solution(int[] A, int N, int k){ // Bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion int[] v1 = new int[N]; int[] v2 = new int[N]; int[] v3 = new int[N]; // Initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // Initiate all other elements of k = 1 for(int i = N - 2; i >= 0; i--) { // Initialize the front element // to vector v2 v2[i] = v2[i + 1]; // If element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // Iterate for all possible values of K for(int j = 1; j < k; j++) { // Fill the vectors with 0 for(int i = 0; i < v3.GetLength(0); i++) v3[i] = 0; // Fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last // no unique subarray can be formed v1[N - 1] = 0; // Iterate for all index from which // unique subsequences can be formed for(int i = N - 2; i >= 0; i--) { // Add the number of subsequence // formed from the next index v1[i] = v1[i + 1]; // Start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } } // Last answer is stored in v2 return v2[0];} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 2, 3, 4 }; int n = a.Length; int k = 3; Console.Write(solution(a, n, k));}} // This code is contributed by Rohit_ranjan <script> // Function which returns the numbe of// unique subsequences of length Kfunction solution(A, N, K){ // Bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion let v1 = new Array(N); let v2 = new Array(N); let v3 = new Array(N); for(let i = 0; i < N; i++) { v1[i] = 0; v2[i] = 0; v3[i] = 0; } // Initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // Initiate all other elements of k = 1 for(let i = N - 2; i >= 0; i--) { // Initialize the front element // to vector v2 v2[i] = v2[i + 1]; // If element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // Iterate for all possible values of K for(let j = 1; j < k; j++) { // Fill the vectors with 0 for(let i = 0; i < v3.length; i++) { v3[i] = 0; } // Fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last // no unique subarray can be formed v1[N - 1] = 0; // Iterate for all index from which // unique subsequences can be formed for(let i = N - 2; i >= 0; i--) { // Add the number of subsequence // formed from the next index v1[i] = v1[i + 1]; // Start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } } // Last answer is stored in v2 return v2[0];} // Driver Codelet a = [ 1, 2, 3, 4 ];let n = a.length;let k = 3; document.write(solution(a, n, k)); // This code is contributed by avanitrachhadiya2155 </script> 4 Time Complexity: O(N * K)Auxiliary Space: O(N) raghavsangarcse17 ukasp Amal Kumar Choubey Rohit_ranjan avanitrachhadiya2155 pankajsharmagfg kk9826225 as5853535 cpp-vector Permutation and Combination Algorithms Arrays Combinatorial Competitive Programming Arrays Combinatorial Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation What is Hashing | A Complete Tutorial CPU Scheduling in Operating Systems Understanding Time Complexity with Simple Examples Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Largest Sum Contiguous Subarray Arrays in C/C++
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Sep, 2021" }, { "code": null, "e": 178, "s": 54, "text": "Given an array of N numbers and an integer K. The task is to print the number of unique subsequences possible of length K. " }, { "code": null, "e": 188, "s": 178, "text": "Examples:" }, { "code": null, "e": 427, "s": 188, "text": "Input : a[] = {1, 2, 3, 4}, k = 3 \nOutput : 4. \nUnique Subsequences are: \n{1, 2, 3}, {1, 2, 4}, {1, 3, 4}, {2, 3, 4}\n\nInput: a[] = {1, 1, 1, 2, 2, 2 }, k = 3\nOutput : 4 \nUnique Subsequences are \n{1, 1, 1}, {1, 1, 2}, {1, 2, 2}, {2, 2, 2} " }, { "code": null, "e": 825, "s": 427, "text": "Approach: There is a well-known formula how many subsequences of fixed length K can be chosen from N unique objects. But the problem here has several differences. One among them is the order in subsequences is important and must be preserved as in the original sequence. For such a problem there can be no ready combinatorics formula because the results depend on the order of the original array. " }, { "code": null, "e": 1270, "s": 825, "text": "The main idea is to deal recurrently by the length of the subsequence. On each recurrent step, move from the end to the beginning and count the unique combinations using the count of shorter unique combinations from the previous step. More strictly on every step j we keep an array of length N and every element in the place p means how many unique subsequences with length j we found to the right of the element in place i, including i itself." }, { "code": null, "e": 1321, "s": 1270, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 1325, "s": 1321, "text": "C++" }, { "code": null, "e": 1330, "s": 1325, "text": "Java" }, { "code": null, "e": 1338, "s": 1330, "text": "Python3" }, { "code": null, "e": 1341, "s": 1338, "text": "C#" }, { "code": null, "e": 1352, "s": 1341, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; // Function which returns the numbe of// unique subsequences of length Kint solution(vector<int>& A, int k){ // seiz of the vector // which does is constant const int N = A.size(); // bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion vector<int> v1(N, 0); vector<int> v2(N, 0); vector<int> v3(N, 0); // initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // initiate all other elements of k = 1 for (int i = N - 2; i >= 0; i--) { // initialize the front element // to vector v2 v2[i] = v2[i + 1]; // if element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // iterate for all possible values of K for (int j = 1; j < k; j++) { // fill the vectors with 0 fill(v3.begin(), v3.end(), 0); // fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last no unique // subarray can be formed v1[N - 1] = 0; // Iterate for all index from which unique // subsequences can be formed for (int i = N - 2; i >= 0; i--) { // add the number of subsequence formed // from the next index v1[i] = v1[i + 1]; // start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } // prepare the next iteration // by filling v2 in v1 v2 = v1; } // last answer is stored in v2 return v2[0];} // Function to push the vector into an array// and print all the unique subarraysvoid solve(int a[], int n, int k){ vector<int> v; // fill the vector with a[] v.assign(a, a + n); // Function call to print the count // of unique subsequences of size K cout << solution(v, k);} // Driver Codeint main(){ int a[] = { 1, 2, 3, 4 }; int n = sizeof(a) / sizeof(a[0]); int k = 3; solve(a, n, k); return 0;}", "e": 3691, "s": 1352, "text": null }, { "code": "import java.util.*; class GFG{ // Function which returns the numbe of// unique subsequences of length Kstatic int solution(int[] A, int N, int k){ // Bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion int[] v1 = new int[N]; int[] v2 = new int[N]; int[] v3 = new int[N]; // Initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // Initiate all other elements of k = 1 for(int i = N - 2; i >= 0; i--) { // Initialize the front element // to vector v2 v2[i] = v2[i + 1]; // If element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // Iterate for all possible values of K for(int j = 1; j < k; j++) { // Fill the vectors with 0 Arrays.fill(v3, 0); // Fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last // no unique subarray can be formed v1[N - 1] = 0; // Iterate for all index from which // unique subsequences can be formed for(int i = N - 2; i >= 0; i--) { // Add the number of subsequence // formed from the next index v1[i] = v1[i + 1]; // Start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } } // Last answer is stored in v2 return v2[0];} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 2, 3, 4 }; int n = a.length; int k = 3; System.out.print(solution(a, n, k));}} // This code is contributed by amal kumar choubey", "e": 5646, "s": 3691, "text": null }, { "code": "# Function which returns the numbe of# unique subsequences of length Kdef solution( A, k): # seiz of the vector # which does is constant N = len(A) # bases cases if (N < k or N < 1 or k < 1): return 0 if (N == k): return 1 # Prepare arrays for recursion v1 = [0]*(N) v2 = [0]*N v3 = [0]*N # initiate separately for k = 1 # initiate the last element v2[N - 1] = 1 v3[A[N - 1] - 1] = 1 # initiate all other elements of k = 1 for i in range(N - 2,-1,-1): # initialize the front element # to vector v2 v2[i] = v2[i + 1] # if element v[a[i]-1] is 0 # then increment it in vector v2 if (v3[A[i] - 1] == 0): v2[i] += 1 v3[A[i] - 1] = 1 # iterate for all possible values of K for j in range( 1, k) : # fill the vectors with 0 v3 = [0]*N # fill(v1.begin(), v1.end(), 0) # the last must be 0 as from last no unique # subarray can be formed v1[N - 1] = 0 # Iterate for all index from which unique # subsequences can be formed for i in range( N - 2, -1, -1) : # add the number of subsequence formed # from the next index v1[i] = v1[i + 1] # start with combinations on the # next index v1[i] = v1[i] + v2[i + 1] # Remove the elements which have # already been counted v1[i] = v1[i] - v3[A[i] - 1] # Update the number used v3[A[i] - 1] = v2[i + 1] # prepare the next iteration # by filling v2 in v1 for i in range(len(v1)): v2[i] = v1[i] # last answer is stored in v2 return v2[0] # Function to push the vector into an array# and print all the unique subarraysdef solve(a, n, k): # fill the vector with a[] v = a # Function call to print the count # of unique subsequences of size K print( solution(v, k)) # Driver Codeif __name__ == \"__main__\": a = [ 1, 2, 3, 4 ] n = len(a) k = 3 solve(a, n, k) # This code is contributed by chitranayal", "e": 7788, "s": 5646, "text": null }, { "code": "using System;class GFG{ // Function which returns the numbe of// unique subsequences of length Kstatic int solution(int[] A, int N, int k){ // Bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion int[] v1 = new int[N]; int[] v2 = new int[N]; int[] v3 = new int[N]; // Initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // Initiate all other elements of k = 1 for(int i = N - 2; i >= 0; i--) { // Initialize the front element // to vector v2 v2[i] = v2[i + 1]; // If element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // Iterate for all possible values of K for(int j = 1; j < k; j++) { // Fill the vectors with 0 for(int i = 0; i < v3.GetLength(0); i++) v3[i] = 0; // Fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last // no unique subarray can be formed v1[N - 1] = 0; // Iterate for all index from which // unique subsequences can be formed for(int i = N - 2; i >= 0; i--) { // Add the number of subsequence // formed from the next index v1[i] = v1[i + 1]; // Start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } } // Last answer is stored in v2 return v2[0];} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 2, 3, 4 }; int n = a.Length; int k = 3; Console.Write(solution(a, n, k));}} // This code is contributed by Rohit_ranjan", "e": 9770, "s": 7788, "text": null }, { "code": "<script> // Function which returns the numbe of// unique subsequences of length Kfunction solution(A, N, K){ // Bases cases if (N < k || N < 1 || k < 1) return 0; if (N == k) return 1; // Prepare arrays for recursion let v1 = new Array(N); let v2 = new Array(N); let v3 = new Array(N); for(let i = 0; i < N; i++) { v1[i] = 0; v2[i] = 0; v3[i] = 0; } // Initiate separately for k = 1 // initiate the last element v2[N - 1] = 1; v3[A[N - 1] - 1] = 1; // Initiate all other elements of k = 1 for(let i = N - 2; i >= 0; i--) { // Initialize the front element // to vector v2 v2[i] = v2[i + 1]; // If element v[a[i]-1] is 0 // then increment it in vector v2 if (v3[A[i] - 1] == 0) { v2[i]++; v3[A[i] - 1] = 1; } } // Iterate for all possible values of K for(let j = 1; j < k; j++) { // Fill the vectors with 0 for(let i = 0; i < v3.length; i++) { v3[i] = 0; } // Fill(v1.begin(), v1.end(), 0) // the last must be 0 as from last // no unique subarray can be formed v1[N - 1] = 0; // Iterate for all index from which // unique subsequences can be formed for(let i = N - 2; i >= 0; i--) { // Add the number of subsequence // formed from the next index v1[i] = v1[i + 1]; // Start with combinations on the // next index v1[i] = v1[i] + v2[i + 1]; // Remove the elements which have // already been counted v1[i] = v1[i] - v3[A[i] - 1]; // Update the number used v3[A[i] - 1] = v2[i + 1]; } } // Last answer is stored in v2 return v2[0];} // Driver Codelet a = [ 1, 2, 3, 4 ];let n = a.length;let k = 3; document.write(solution(a, n, k)); // This code is contributed by avanitrachhadiya2155 </script>", "e": 11856, "s": 9770, "text": null }, { "code": null, "e": 11858, "s": 11856, "text": "4" }, { "code": null, "e": 11908, "s": 11860, "text": "Time Complexity: O(N * K)Auxiliary Space: O(N) " }, { "code": null, "e": 11926, "s": 11908, "text": "raghavsangarcse17" }, { "code": null, "e": 11932, "s": 11926, "text": "ukasp" }, { "code": null, "e": 11951, "s": 11932, "text": "Amal Kumar Choubey" }, { "code": null, "e": 11964, "s": 11951, "text": "Rohit_ranjan" }, { "code": null, "e": 11985, "s": 11964, "text": "avanitrachhadiya2155" }, { "code": null, "e": 12001, "s": 11985, "text": "pankajsharmagfg" }, { "code": null, "e": 12011, "s": 12001, "text": "kk9826225" }, { "code": null, "e": 12021, "s": 12011, "text": "as5853535" }, { "code": null, "e": 12032, "s": 12021, "text": "cpp-vector" }, { "code": null, "e": 12060, "s": 12032, "text": "Permutation and Combination" }, { "code": null, "e": 12071, "s": 12060, "text": "Algorithms" }, { "code": null, "e": 12078, "s": 12071, "text": "Arrays" }, { "code": null, "e": 12092, "s": 12078, "text": "Combinatorial" }, { "code": null, "e": 12116, "s": 12092, "text": "Competitive Programming" }, { "code": null, "e": 12123, "s": 12116, "text": "Arrays" }, { "code": null, "e": 12137, "s": 12123, "text": "Combinatorial" }, { "code": null, "e": 12148, "s": 12137, "text": "Algorithms" }, { "code": null, "e": 12246, "s": 12148, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12271, "s": 12246, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 12320, "s": 12271, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 12358, "s": 12320, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 12394, "s": 12358, "text": "CPU Scheduling in Operating Systems" }, { "code": null, "e": 12445, "s": 12394, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 12460, "s": 12445, "text": "Arrays in Java" }, { "code": null, "e": 12506, "s": 12460, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 12574, "s": 12506, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 12606, "s": 12574, "text": "Largest Sum Contiguous Subarray" } ]
How to create Tables using Plotly in Python?
05 Sep, 2020 Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. A table helps in organizing the data into columns and rows. The use of tables is prevalent throughout all communication, research, and data analysis. They privilege rapid entrance and proportionately elementary comparison of information. It can be created using the Table() method of graph_objects class. Syntax: plotly.graph_objects.Table(arg=None, cells=None, columnorder=None, columnwidth=None, header=None, **kwargs) Parameters: arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Table cells: plotly.graph_objects.table.Cells instance or dict with compatible properties columnorder: Specifies the rendered order of the data columns; for example, a value 2 at position 0 means that column index 0 in the data will be rendered as the third column, as columns have an index base of zero. columnwidth: The width of columns expressed as a ratio. Columns fill the available width in proportion of their specified column widths. header: plotly.graph_objects.table.Header instance or dict with compatible properties Example: Python3 import plotly.graph_objects as go fig = go.Figure(data=[go.Table( header=dict(values=['A', 'B']), cells=dict(values=[[10, 20, 30, 40], [40, 20, 10, 50]]))])fig.show() Output: Adding colors in alternative rows will make it easier to understand the data more efficiently. It distinguish the data from each other and the values can be separately seen easily in the data format. Example: Python3 import plotly.graph_objects as go color1 = 'lightgreen'color2 = 'lightblue' fig = go.Figure(data=[go.Table( header=dict(values=['A', 'B']), cells=dict(values=[[10, 20, 30, 40], [40, 20, 10, 50]], fill_color=[[color1, color2, color1, color2, color1]*2],))])fig.show() Output: It is possible to change the row and column size by using the columnwidth parameter. The width of columns is expressed as a ratio. Columns fill the available width in the proportion of their specified column widths. Example: Python3 import plotly.graph_objects as go color1 = 'lightgreen'color2 = 'lightblue' fig = go.Figure(data=[go.Table( # Ratio for column width columnwidth=[1, 5], header=dict(values=['A', 'B']), cells=dict(values=[[10, 20, 30, 40], [40, 20, 10, 50]], fill_color=[[color1, color2, color1, color2, color1]*2],))])fig.show() Output: Python-Plotly Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Sep, 2020" }, { "code": null, "e": 330, "s": 28, "text": "Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library." }, { "code": null, "e": 636, "s": 330, "text": "A table helps in organizing the data into columns and rows. The use of tables is prevalent throughout all communication, research, and data analysis. They privilege rapid entrance and proportionately elementary comparison of information. It can be created using the Table() method of graph_objects class." }, { "code": null, "e": 752, "s": 636, "text": "Syntax: plotly.graph_objects.Table(arg=None, cells=None, columnorder=None, columnwidth=None, header=None, **kwargs)" }, { "code": null, "e": 764, "s": 752, "text": "Parameters:" }, { "code": null, "e": 867, "s": 764, "text": "arg: dict of properties compatible with this constructor or an instance of plotly.graph_objects.Table" }, { "code": null, "e": 951, "s": 867, "text": "cells: plotly.graph_objects.table.Cells instance or dict with compatible properties" }, { "code": null, "e": 1166, "s": 951, "text": "columnorder: Specifies the rendered order of the data columns; for example, a value 2 at position 0 means that column index 0 in the data will be rendered as the third column, as columns have an index base of zero." }, { "code": null, "e": 1303, "s": 1166, "text": "columnwidth: The width of columns expressed as a ratio. Columns fill the available width in proportion of their specified column widths." }, { "code": null, "e": 1389, "s": 1303, "text": "header: plotly.graph_objects.table.Header instance or dict with compatible properties" }, { "code": null, "e": 1398, "s": 1389, "text": "Example:" }, { "code": null, "e": 1406, "s": 1398, "text": "Python3" }, { "code": "import plotly.graph_objects as go fig = go.Figure(data=[go.Table( header=dict(values=['A', 'B']), cells=dict(values=[[10, 20, 30, 40], [40, 20, 10, 50]]))])fig.show()", "e": 1602, "s": 1406, "text": null }, { "code": null, "e": 1610, "s": 1602, "text": "Output:" }, { "code": null, "e": 1810, "s": 1610, "text": "Adding colors in alternative rows will make it easier to understand the data more efficiently. It distinguish the data from each other and the values can be separately seen easily in the data format." }, { "code": null, "e": 1819, "s": 1810, "text": "Example:" }, { "code": null, "e": 1827, "s": 1819, "text": "Python3" }, { "code": "import plotly.graph_objects as go color1 = 'lightgreen'color2 = 'lightblue' fig = go.Figure(data=[go.Table( header=dict(values=['A', 'B']), cells=dict(values=[[10, 20, 30, 40], [40, 20, 10, 50]], fill_color=[[color1, color2, color1, color2, color1]*2],))])fig.show()", "e": 2165, "s": 1827, "text": null }, { "code": null, "e": 2173, "s": 2165, "text": "Output:" }, { "code": null, "e": 2389, "s": 2173, "text": "It is possible to change the row and column size by using the columnwidth parameter. The width of columns is expressed as a ratio. Columns fill the available width in the proportion of their specified column widths." }, { "code": null, "e": 2398, "s": 2389, "text": "Example:" }, { "code": null, "e": 2406, "s": 2398, "text": "Python3" }, { "code": "import plotly.graph_objects as go color1 = 'lightgreen'color2 = 'lightblue' fig = go.Figure(data=[go.Table( # Ratio for column width columnwidth=[1, 5], header=dict(values=['A', 'B']), cells=dict(values=[[10, 20, 30, 40], [40, 20, 10, 50]], fill_color=[[color1, color2, color1, color2, color1]*2],))])fig.show()", "e": 2795, "s": 2406, "text": null }, { "code": null, "e": 2803, "s": 2795, "text": "Output:" }, { "code": null, "e": 2817, "s": 2803, "text": "Python-Plotly" }, { "code": null, "e": 2824, "s": 2817, "text": "Python" } ]
Ruby - Operators
Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument. For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (+= -= etc.). Assume variable a holds 10 and variable b holds 20, then − Assume variable a holds 10 and variable b holds 20, then − Assume variable a holds 10 and variable b holds 20, then − Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example − a = 10 b = 20 c = 30 This may be more quickly declared using parallel assignment − a, b, c = 10, 20, 30 Parallel assignment is also useful for swapping the values held in two variables − a, b = b, c Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; now in binary format they will be as follows − a = 0011 1100 b = 0000 1101 ------------------ a&b = 0000 1100 a|b = 0011 1101 a^b = 0011 0001 ~a = 1100 0011 The following Bitwise operators are supported by Ruby language. The following logical operators are supported by Ruby language Assume variable a holds 10 and variable b holds 20, then − There is one more operator called Ternary Operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax − Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value, and a range of values in between. In Ruby, these sequences are created using the ".." and "..." range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value. defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined. It returns a description string of the expression, or nil if the expression isn't defined. There are various usage of defined? Operator defined? variable # True if variable is initialized For Example foo = 42 defined? foo # => "local-variable" defined? $_ # => "global-variable" defined? bar # => nil (undefined) defined? method_call # True if a method is defined For Example defined? puts # => "method" defined? puts(bar) # => nil (bar is not defined here) defined? unpack # => nil (not defined here) # True if a method exists that can be called with super user defined? super For Example defined? super # => "super" (if it can be called) defined? super # => nil (if it cannot be) defined? yield # True if a code block has been passed For Example defined? yield # => "yield" (if there is a block passed) defined? yield # => nil (if there is no block) You call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons. The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too. You need to just prefix the :: Const_name with an expression that returns the appropriate class or module object. If no prefix expression is used, the main Object class is used by default. Here are two examples − MR_COUNT = 0 # constant defined on main Object class module Foo MR_COUNT = 0 ::MR_COUNT = 1 # set global count to 1 MR_COUNT = 2 # set local count to 2 end puts MR_COUNT # this is the global constant puts Foo::MR_COUNT # this is the local "Foo" constant Second Example CONST = ' out there' class Inside_one CONST = proc {' in there'} def where_is_my_CONST ::CONST + ' inside one' end end class Inside_two CONST = ' inside two' def where_is_my_CONST CONST end end puts Inside_one.new.where_is_my_CONST puts Inside_two.new.where_is_my_CONST puts Object::CONST + Inside_two::CONST puts Inside_two::CONST + CONST puts Inside_one::CONST puts Inside_one::CONST.call + Inside_two::CONST The following table lists all operators from highest precedence to lowest. NOTE − Operators with a Yes in the method column are actually methods, and as such may be overridden. 46 Lectures 9.5 hours Eduonix Learning Solutions 97 Lectures 7.5 hours Skillbakerystudios 227 Lectures 40 hours YouAccel 19 Lectures 10 hours Programming Line 51 Lectures 5 hours Stone River ELearning 39 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2553, "s": 2294, "text": "Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument." }, { "code": null, "e": 2684, "s": 2553, "text": "For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding form of abbreviated assignment operator (+= -= etc.)." }, { "code": null, "e": 2743, "s": 2684, "text": "Assume variable a holds 10 and variable b holds 20, then −" }, { "code": null, "e": 2802, "s": 2743, "text": "Assume variable a holds 10 and variable b holds 20, then −" }, { "code": null, "e": 2861, "s": 2802, "text": "Assume variable a holds 10 and variable b holds 20, then −" }, { "code": null, "e": 3015, "s": 2861, "text": "Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example −" }, { "code": null, "e": 3037, "s": 3015, "text": "a = 10\nb = 20\nc = 30\n" }, { "code": null, "e": 3099, "s": 3037, "text": "This may be more quickly declared using parallel assignment −" }, { "code": null, "e": 3121, "s": 3099, "text": "a, b, c = 10, 20, 30\n" }, { "code": null, "e": 3204, "s": 3121, "text": "Parallel assignment is also useful for swapping the values held in two variables −" }, { "code": null, "e": 3217, "s": 3204, "text": "a, b = b, c\n" }, { "code": null, "e": 3283, "s": 3217, "text": "Bitwise operator works on bits and performs bit by bit operation." }, { "code": null, "e": 3360, "s": 3283, "text": "Assume if a = 60; and b = 13; now in binary format they will be as follows −" }, { "code": null, "e": 3495, "s": 3360, "text": " a = 0011 1100\n b = 0000 1101\n ------------------\n a&b = 0000 1100\n a|b = 0011 1101\n a^b = 0011 0001\n ~a = 1100 0011\n" }, { "code": null, "e": 3559, "s": 3495, "text": "The following Bitwise operators are supported by Ruby language." }, { "code": null, "e": 3622, "s": 3559, "text": "The following logical operators are supported by Ruby language" }, { "code": null, "e": 3681, "s": 3622, "text": "Assume variable a holds 10 and variable b holds 20, then −" }, { "code": null, "e": 3930, "s": 3681, "text": "There is one more operator called Ternary Operator. It first evaluates an expression for a true or false value and then executes one of the two given statements depending upon the result of the evaluation. The conditional operator has this syntax −" }, { "code": null, "e": 4081, "s": 3930, "text": "Sequence ranges in Ruby are used to create a range of successive values - consisting of a start value, an end value, and a range of values in between." }, { "code": null, "e": 4286, "s": 4081, "text": "In Ruby, these sequences are created using the \"..\" and \"...\" range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value." }, { "code": null, "e": 4507, "s": 4286, "text": "defined? is a special operator that takes the form of a method call to determine whether or not the passed expression is defined. It returns a description string of the expression, or nil if the expression isn't defined." }, { "code": null, "e": 4552, "s": 4507, "text": "There are various usage of defined? Operator" }, { "code": null, "e": 4604, "s": 4552, "text": "defined? variable # True if variable is initialized" }, { "code": null, "e": 4616, "s": 4604, "text": "For Example" }, { "code": null, "e": 4739, "s": 4616, "text": "foo = 42\ndefined? foo # => \"local-variable\"\ndefined? $_ # => \"global-variable\"\ndefined? bar # => nil (undefined)" }, { "code": null, "e": 4790, "s": 4739, "text": "defined? method_call # True if a method is defined" }, { "code": null, "e": 4802, "s": 4790, "text": "For Example" }, { "code": null, "e": 4942, "s": 4802, "text": "defined? puts # => \"method\"\ndefined? puts(bar) # => nil (bar is not defined here)\ndefined? unpack # => nil (not defined here)" }, { "code": null, "e": 5018, "s": 4942, "text": "# True if a method exists that can be called with super user\ndefined? super" }, { "code": null, "e": 5030, "s": 5018, "text": "For Example" }, { "code": null, "e": 5130, "s": 5030, "text": "defined? super # => \"super\" (if it can be called)\ndefined? super # => nil (if it cannot be)" }, { "code": null, "e": 5186, "s": 5130, "text": "defined? yield # True if a code block has been passed" }, { "code": null, "e": 5198, "s": 5186, "text": "For Example" }, { "code": null, "e": 5308, "s": 5198, "text": "defined? yield # => \"yield\" (if there is a block passed)\ndefined? yield # => nil (if there is no block)" }, { "code": null, "e": 5459, "s": 5308, "text": "You call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons." }, { "code": null, "e": 5637, "s": 5459, "text": "The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module." }, { "code": null, "e": 5708, "s": 5637, "text": "Remember in Ruby, classes and methods may be considered constants too." }, { "code": null, "e": 5822, "s": 5708, "text": "You need to just prefix the :: Const_name with an expression that returns the appropriate class or module object." }, { "code": null, "e": 5897, "s": 5822, "text": "If no prefix expression is used, the main Object class is used by default." }, { "code": null, "e": 5921, "s": 5897, "text": "Here are two examples −" }, { "code": null, "e": 6209, "s": 5921, "text": "MR_COUNT = 0 # constant defined on main Object class\nmodule Foo\n MR_COUNT = 0\n ::MR_COUNT = 1 # set global count to 1\n MR_COUNT = 2 # set local count to 2\nend\nputs MR_COUNT # this is the global constant\nputs Foo::MR_COUNT # this is the local \"Foo\" constant" }, { "code": null, "e": 6224, "s": 6209, "text": "Second Example" }, { "code": null, "e": 6665, "s": 6224, "text": "CONST = ' out there'\nclass Inside_one\n CONST = proc {' in there'}\n def where_is_my_CONST\n ::CONST + ' inside one'\n end\nend\nclass Inside_two\n CONST = ' inside two'\n def where_is_my_CONST\n CONST\n end\nend\nputs Inside_one.new.where_is_my_CONST\nputs Inside_two.new.where_is_my_CONST\nputs Object::CONST + Inside_two::CONST\nputs Inside_two::CONST + CONST\nputs Inside_one::CONST\nputs Inside_one::CONST.call + Inside_two::CONST" }, { "code": null, "e": 6740, "s": 6665, "text": "The following table lists all operators from highest precedence to lowest." }, { "code": null, "e": 6842, "s": 6740, "text": "NOTE − Operators with a Yes in the method column are actually methods, and as such may be overridden." }, { "code": null, "e": 6877, "s": 6842, "text": "\n 46 Lectures \n 9.5 hours \n" }, { "code": null, "e": 6905, "s": 6877, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6940, "s": 6905, "text": "\n 97 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6960, "s": 6940, "text": " Skillbakerystudios" }, { "code": null, "e": 6995, "s": 6960, "text": "\n 227 Lectures \n 40 hours \n" }, { "code": null, "e": 7005, "s": 6995, "text": " YouAccel" }, { "code": null, "e": 7039, "s": 7005, "text": "\n 19 Lectures \n 10 hours \n" }, { "code": null, "e": 7057, "s": 7039, "text": " Programming Line" }, { "code": null, "e": 7090, "s": 7057, "text": "\n 51 Lectures \n 5 hours \n" }, { "code": null, "e": 7113, "s": 7090, "text": " Stone River ELearning" }, { "code": null, "e": 7148, "s": 7113, "text": "\n 39 Lectures \n 4.5 hours \n" }, { "code": null, "e": 7171, "s": 7148, "text": " Stone River ELearning" }, { "code": null, "e": 7178, "s": 7171, "text": " Print" }, { "code": null, "e": 7189, "s": 7178, "text": " Add Notes" } ]
Horizontal Navigation
In this chapter, we will learn how to add horizontal navigation or menu items to the website. Step 1 − To create menu items or horizontal navigation, let’s add the following code in <div id = “top-nav”> in the index.html file, which contains the list of menu items. <div id = "top-nav"> <ul> <li></li> <li></li> <li></li> <li></li> </ul> </div> Step 2 − It is a simple bulleted list for the top menu. To create a hyperlink, go to the design view or code view. Step 3 − Select the item that you want to use as the hyperlink and press Ctrl + K. Step 4 − Click on the ScreenTip... button. Step 5 − Enter the text you want as the screen tip and click OK. Step 6 − In the Text to display field, enter Home and select the index.html file and then click OK. Step 7 − Similarly, add hyperlinks for other menu items, as shown in the following code. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <meta content = "text/html; charset=utf-8" http-equiv = "Content-Type" /> <style type = "text/css"></style> <link href = "sample.css" rel="stylesheet" type = "text/css" /> </head> <body> <div id = "container"> <div id = "header"></div> <div id = "top-nav"> <ul> <li><a href = "index.html" title = "Site Home Page">Home</a></li> <li><a href = "index.html" title = "Menu Item 1.">Menu Item 1</a></li> <li><a href = "index.html" title = "Menu Item 2.">Menu Item 2</a></li> <li><a href = "index.html" title = "Menu Item 3.">Menu Item 3</a></li> </ul> </div> <div id = "left-nav"> </div> <div id = "main-content"> </div> <div id = "footer"> </div> </div> </body> </html> Step 8 − To set the style for top navigation, go to the Manage Styles panel. Step 9 − Right-click on “#top-nav” and select Modify Style. Select the 'Border' Category and change the width to thin. Step 10 − Select the Box category and uncheck padding ‘Same for all’ and enter 10 in the top and bottom fields. Step 11 − Go to the Position category. Step 12 − Remove the 50 from the height field and click OK. From the Apply Styles panel, click New Style... Step 13 − Enter #top-nav ul in the Selector field and select the Existing style sheet from the “Define in” dropdown. In the Block category, select center from the test-align field and go to the List category. Step 14 − Select none from the list-style-type field and click OK. Step 15 − Again, from the Apply Styles panel, click New Style... Enter #top-nav ul li in the Selector field. Then select the Existing style-sheet from the “Define in” dropdown and go to the Layout category. Step 16 − Select inline from the display field and click OK. Step 17 − Go to Apply Styles panel, click New Style... Enter #top-nav ul li a in the Selector field and select the Existing style sheet from the “Define in” dropdown and select white as the font color. Step 18 − Go to the Background category. Step 19 − Select green as the background color and go to the Box category. Step 20 − Set the padding values and click OK. Step 21 − Now let’s go to the Apply Styles panel again and click New Style. Enter #topnav ul li a:hover in the Selector field and select the Existing style sheet from the “Define in” dropdown and select black as the font color. Step 22 − Now go to the Background category. Step 23 − Select the background color for your menu option when the mouse is hovering on the menu item and go to the Border category. Step 24 − Select the border style, width, and color, and click OK. To check how it is looks, go to the File menu and select Preview in Browser. When you hover the mouse on any menu item, it will change the background and font color. 16 Lectures 11.5 hours SHIVPRASAD KOIRALA 33 Lectures 3 hours Abhishek And Pukhraj 33 Lectures 5.5 hours Abhishek And Pukhraj 40 Lectures 6.5 hours Syed Raza 15 Lectures 2 hours Harshit Srivastava, Pranjal Srivastava 18 Lectures 1.5 hours Pranjal Srivastava, Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2290, "s": 2196, "text": "In this chapter, we will learn how to add horizontal navigation or menu items to the website." }, { "code": null, "e": 2462, "s": 2290, "text": "Step 1 − To create menu items or horizontal navigation, let’s add the following code in <div id = “top-nav”> in the index.html file, which contains the list of menu items." }, { "code": null, "e": 2578, "s": 2462, "text": "<div id = \"top-nav\"> \n <ul> \n <li></li> \n <li></li> \n <li></li> \n <li></li> \n </ul> \n</div>" }, { "code": null, "e": 2693, "s": 2578, "text": "Step 2 − It is a simple bulleted list for the top menu. To create a hyperlink, go to the design view or code view." }, { "code": null, "e": 2776, "s": 2693, "text": "Step 3 − Select the item that you want to use as the hyperlink and press Ctrl + K." }, { "code": null, "e": 2819, "s": 2776, "text": "Step 4 − Click on the ScreenTip... button." }, { "code": null, "e": 2884, "s": 2819, "text": "Step 5 − Enter the text you want as the screen tip and click OK." }, { "code": null, "e": 2984, "s": 2884, "text": "Step 6 − In the Text to display field, enter Home and select the index.html file and then click OK." }, { "code": null, "e": 3073, "s": 2984, "text": "Step 7 − Similarly, add hyperlinks for other menu items, as shown in the following code." }, { "code": null, "e": 4126, "s": 3073, "text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n<html xmlns = \"http://www.w3.org/1999/xhtml\"> \n <head> \n <meta content = \"text/html; charset=utf-8\" http-equiv = \"Content-Type\" /> \n <style type = \"text/css\"></style> \n <link href = \"sample.css\" rel=\"stylesheet\" type = \"text/css\" /> \n </head> \n\n <body> \n <div id = \"container\"> \n <div id = \"header\"></div> \n <div id = \"top-nav\"> \n <ul> \n <li><a href = \"index.html\" title = \"Site Home Page\">Home</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 1.\">Menu Item 1</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 2.\">Menu Item 2</a></li> \n <li><a href = \"index.html\" title = \"Menu Item 3.\">Menu Item 3</a></li> \n </ul> \n </div> \n <div id = \"left-nav\"> </div> \n <div id = \"main-content\"> </div> \n <div id = \"footer\"> </div> \n </div> \n </body> \n</html>" }, { "code": null, "e": 4203, "s": 4126, "text": "Step 8 − To set the style for top navigation, go to the Manage Styles panel." }, { "code": null, "e": 4322, "s": 4203, "text": "Step 9 − Right-click on “#top-nav” and select Modify Style. Select the 'Border' Category and change the width to thin." }, { "code": null, "e": 4434, "s": 4322, "text": "Step 10 − Select the Box category and uncheck padding ‘Same for all’ and enter 10 in the top and bottom fields." }, { "code": null, "e": 4473, "s": 4434, "text": "Step 11 − Go to the Position category." }, { "code": null, "e": 4581, "s": 4473, "text": "Step 12 − Remove the 50 from the height field and click OK. From the Apply Styles panel, click New Style..." }, { "code": null, "e": 4790, "s": 4581, "text": "Step 13 − Enter #top-nav ul in the Selector field and select the Existing style sheet from the “Define in” dropdown. In the Block category, select center from the test-align field and go to the List category." }, { "code": null, "e": 4857, "s": 4790, "text": "Step 14 − Select none from the list-style-type field and click OK." }, { "code": null, "e": 5064, "s": 4857, "text": "Step 15 − Again, from the Apply Styles panel, click New Style... Enter #top-nav ul li in the Selector field. Then select the Existing style-sheet from the “Define in” dropdown and go to the Layout category." }, { "code": null, "e": 5125, "s": 5064, "text": "Step 16 − Select inline from the display field and click OK." }, { "code": null, "e": 5327, "s": 5125, "text": "Step 17 − Go to Apply Styles panel, click New Style... Enter #top-nav ul li a in the Selector field and select the Existing style sheet from the “Define in” dropdown and select white as the font color." }, { "code": null, "e": 5368, "s": 5327, "text": "Step 18 − Go to the Background category." }, { "code": null, "e": 5443, "s": 5368, "text": "Step 19 − Select green as the background color and go to the Box category." }, { "code": null, "e": 5490, "s": 5443, "text": "Step 20 − Set the padding values and click OK." }, { "code": null, "e": 5718, "s": 5490, "text": "Step 21 − Now let’s go to the Apply Styles panel again and click New Style. Enter #topnav ul li a:hover in the Selector field and select the Existing style sheet from the “Define in” dropdown and select black as the font color." }, { "code": null, "e": 5763, "s": 5718, "text": "Step 22 − Now go to the Background category." }, { "code": null, "e": 5897, "s": 5763, "text": "Step 23 − Select the background color for your menu option when the mouse is hovering on the menu item and go to the Border category." }, { "code": null, "e": 6041, "s": 5897, "text": "Step 24 − Select the border style, width, and color, and click OK. To check how it is looks, go to the File menu and select Preview in Browser." }, { "code": null, "e": 6130, "s": 6041, "text": "When you hover the mouse on any menu item, it will change the background and font color." }, { "code": null, "e": 6166, "s": 6130, "text": "\n 16 Lectures \n 11.5 hours \n" }, { "code": null, "e": 6186, "s": 6166, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 6219, "s": 6186, "text": "\n 33 Lectures \n 3 hours \n" }, { "code": null, "e": 6241, "s": 6219, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6276, "s": 6241, "text": "\n 33 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6298, "s": 6276, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6333, "s": 6298, "text": "\n 40 Lectures \n 6.5 hours \n" }, { "code": null, "e": 6344, "s": 6333, "text": " Syed Raza" }, { "code": null, "e": 6377, "s": 6344, "text": "\n 15 Lectures \n 2 hours \n" }, { "code": null, "e": 6417, "s": 6377, "text": " Harshit Srivastava, Pranjal Srivastava" }, { "code": null, "e": 6452, "s": 6417, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6492, "s": 6452, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 6499, "s": 6492, "text": " Print" }, { "code": null, "e": 6510, "s": 6499, "text": " Add Notes" } ]
How to Create Python Web Apps for your Data Science Projects | Towards Data Science
Web development isn’t a data scientist’s core competency. Most data scientists don’t bother to learn different technologies to do it. It’s just not their cup of coffee. Yet, most data science projects also have a software development component. Developers sometimes have a different understanding of the problem, and they use discrete technologies. It often causes problems and drains the precious time of both teams unproductively. Also, visualization tools such as Tableau and Power BI focus more on data exploration. Yet, it’s only part of a complete data science project. If you need to integrate a machine learning model, they are far from perfect. Streamlit allows you to develop web apps for your data science projects. This open-source library’s API is entirely in python. Hence you don’t have to learn any other web technology to use it. Also, it’s straightforward to learn and flexible for modifications. This article is an introduction to Streamlit. We’ll build an interactive web app that takes user inputs, runs a K-means algorithm, and instantly plots the results in a web interface. By the end of the short article, we’d have covered installing Streamlit and testing the water; Building an interactive web app; running K-means algorithm with user inputs; using cache to improve performance, and; deploying it on the cloud; Here is the link to the deployed version. Check it out if you want a sneak peek. This extraordinary tool has an embarrassingly simple setup, and almost all Python users are familiar with it. Use PyPI. pip install streamlit You can also use conda and other popular python package managers. Once completed, you can test it with a hello world app that comes with the installation. Execute the below command in a terminal window to start the development server. streamlit hello The hello world app is a set of excellent visualization you can do with Streamlit. The above command will start a local development server and open the link in your default browser. You can also find the source codes on the same page. In addition, this sample app also has links to lots of advanced tutorials to educate yourself. Now that the setup is complete, let’s create an app to interact with our machine learning model. The app below uses Pandas, Scikit-Learn, Matplotlib, Seaborn, and Streamlit. Before starting, make sure you have installed all the required packages. If not, the below command will do it for you. pip install pandas scikit-learn matplotlib seaborn streamlit Create a file named ‘quickstart.py’ with the below content. The above file is straightforward. For illustration purposes, I’ve added sections to the file. In the main app section, we have three lines. We added a title and a description to the page. Then we display the data frame on the page. The “st.write” function is an all-in-one solution. You could pass almost anything into this function, and Streamlit is smart enough to display the correct widget in the UI. To learn about different Streamlit functions, here is a cheat sheet. Let’s run our initial app with the below command. streamlilt run quickstart.py Like the hello app, this command will start a new development server. On your browser, you’ll see the below. Congratulations, you just created your first web app; without HTML, CSS, and absolutely no JavaScript. But this is rudimentary. A web app could do lots of cool stuff. It could interact with the user in real-time and update its content. Let’s see how we can do it. Bringing interactions in the Streamlit web app is effortless. The Streamlit API contains several widgets. You can use them to get the user input and store its value in a variable. The rest is like any other python program. Let’s add a checkbox to toggle the dataset display. After all, no one develops a web app to see the raw data. Replace the data frame display (line 30) with the below content. If you refresh your browser, now you can see a checkbox to toggle the data frame display. But a toggle button in the middle of the app is not pleasing. Let’s move it to a sidebar. Again, another effortless action. The Streamlit API has the sidebar property. All the widgets you created in the main app are also available in this sidebar property. Create a sidebar variable by using the ‘st.sidebar’ property. Then move the checkbox assignment we added in the main app section to the sidebar section. Notice we now use ‘st.sidebar.checkbox’ instead of ‘st.checkbox.’ In the above code, we’ve also added a slider to the sidebar. This widget will capture the user-selected number of clusters. Here is how the output will look. Next stop, we’ll run the K means algorithm with the user-selected number of clusters. Extend the imports, helper functions, and main app sections with the below code. In the above code, we’ve created a function to run the K-Means algorithm. It takes the data frame and the number of clusters as arguments and returns a Matplotlib figure. The illustration of K-Means clustering is beyond the scope of this project. It’s a machine learning algorithm, and that’s what we care about. But you can refer to my previous post that describes it. We use the n_clusters variable that captures the slider value in the previous section as the second argument to the run_forecast function. If you refresh the page, you’ll see a dashboard that takes user input, runs a machine learning algorithm, and instantly updates the UI. Even if you are an experienced developer, this level of interaction and integration with back-end ML is a difficult task. Especially if you are a data scientist who doesn’t know how to develop web apps, it might take weeks of your time. Some tasks in a data science pipeline are time-consuming. Yet, such tasks rarely produce different results for the same inputs. You can use Streamlit’s inbuilt caching functions to store their values for future use. Although it might sound complicated, doing it with streamlit is simple. Your time-consuming task should be a function, and you wrap it with the @ts.cache decorator. As long as the input parameters are the same and the function’s body is untouched, Streamline will fetch it from the cache. In the app we built, we call the external URL to download data. If it’s a live API, you may not want to cache it. But in our case, it’s not. Therefore let’s cache it by replacing the line with the below code. On your first reload, you may see a message “Processing load_data” on your browser. But subsequent reloads won’t have that note. This is because requests are fetched from the cache instead of downloading from the external URL. If you’ve noticed the Streamlit console, you’ll also see a network URL. It means, if your firewall allows, your app can be accessible over the intranet. But if you want to share it outside your network, we have many options. As the documentation says, Streamlit apps work anywhere a Python app works. Streamlit Recommends the “Streamlit Sharing” option.You can put your code on a GitHub repository and configure Streamlit Sharing to serve your app.Streamlit sharing is free, but it’s currently invitation only. You can request an invitation for yourself.You can deploy it on cloud platforms. Here is an article that shows how to do it with AWS EC2 free instance.You can configure a reverse proxy. Proxy servers like Nginx and Apache can be configured to serve the app and restrict access for specific users. Streamlit Recommends the “Streamlit Sharing” option.You can put your code on a GitHub repository and configure Streamlit Sharing to serve your app.Streamlit sharing is free, but it’s currently invitation only. You can request an invitation for yourself. You can deploy it on cloud platforms. Here is an article that shows how to do it with AWS EC2 free instance. You can configure a reverse proxy. Proxy servers like Nginx and Apache can be configured to serve the app and restrict access for specific users. Be sure to read Streamlit’s community guide about deployment to explore numerous options available to you. Here is how I deployed this tutorial app on Streamlit Share. Once again, Streamlit didn’t fail to surprise me with its convenience. Step I: Put your code into a GitHub public repository.I’ve added my code to this GitHub repo. We need to make sure that it contains a requirement.txt file with all the dependencies. Step II: Log into Streamlit using your GitHub account. Step III: Create a new app on the Streamlit console.Choose your git hub repo from the dropdown or past in the URL. Select the branch that you want to use for the deployment. Finally, pick the main filename and click deploy. In about a minute, my app is live on Streamlit Share. But time to deployment may vary depending on the project requirements. Notice that streamlit share is currently an invitation-only thing. But I didn’t wait too long to get it. Streamlit’s deployment documentation contains a lot more helpful information on this. Needless to say, Streamlit solves a critical problem in data science projects. It gives data scientists the power to build web apps to interact with their machine learning models. In this introductory article, we’ve explored how we can use Streamlit with K-Means clustering. Although it’s a trivial application, it illustrates the core concepts of this technology. Besides development, we’ve also seen how effortless managing cache for performance in Streamlit. Lastly, we talked about the deployment options. Streamlit is much more than this. Please check their official documentation, which is filled with excellent tutorials. Also, their API cheat sheet is helpful for rapid development. A web app is a wonderful solution. But in some cases, you might have to think of other ways to interact with your ML models. Perhaps, building a command-line interface to your model could help. towardsdatascience.com Thanks for the read, friend. It seems you and I have lots of common interests. Do check out my personal blog too. Say Hi to me on LinkedIn, Twitter, and Medium. I’ll break the ice for you. Not a Medium member yet? Please use this link to become a member. You can enjoy thousands of insightful articles and support me as I earn a small commission for referring you.
[ { "code": null, "e": 341, "s": 172, "text": "Web development isn’t a data scientist’s core competency. Most data scientists don’t bother to learn different technologies to do it. It’s just not their cup of coffee." }, { "code": null, "e": 605, "s": 341, "text": "Yet, most data science projects also have a software development component. Developers sometimes have a different understanding of the problem, and they use discrete technologies. It often causes problems and drains the precious time of both teams unproductively." }, { "code": null, "e": 826, "s": 605, "text": "Also, visualization tools such as Tableau and Power BI focus more on data exploration. Yet, it’s only part of a complete data science project. If you need to integrate a machine learning model, they are far from perfect." }, { "code": null, "e": 1087, "s": 826, "text": "Streamlit allows you to develop web apps for your data science projects. This open-source library’s API is entirely in python. Hence you don’t have to learn any other web technology to use it. Also, it’s straightforward to learn and flexible for modifications." }, { "code": null, "e": 1270, "s": 1087, "text": "This article is an introduction to Streamlit. We’ll build an interactive web app that takes user inputs, runs a K-means algorithm, and instantly plots the results in a web interface." }, { "code": null, "e": 1321, "s": 1270, "text": "By the end of the short article, we’d have covered" }, { "code": null, "e": 1365, "s": 1321, "text": "installing Streamlit and testing the water;" }, { "code": null, "e": 1398, "s": 1365, "text": "Building an interactive web app;" }, { "code": null, "e": 1442, "s": 1398, "text": "running K-means algorithm with user inputs;" }, { "code": null, "e": 1483, "s": 1442, "text": "using cache to improve performance, and;" }, { "code": null, "e": 1510, "s": 1483, "text": "deploying it on the cloud;" }, { "code": null, "e": 1591, "s": 1510, "text": "Here is the link to the deployed version. Check it out if you want a sneak peek." }, { "code": null, "e": 1711, "s": 1591, "text": "This extraordinary tool has an embarrassingly simple setup, and almost all Python users are familiar with it. Use PyPI." }, { "code": null, "e": 1733, "s": 1711, "text": "pip install streamlit" }, { "code": null, "e": 1799, "s": 1733, "text": "You can also use conda and other popular python package managers." }, { "code": null, "e": 1968, "s": 1799, "text": "Once completed, you can test it with a hello world app that comes with the installation. Execute the below command in a terminal window to start the development server." }, { "code": null, "e": 1984, "s": 1968, "text": "streamlit hello" }, { "code": null, "e": 2314, "s": 1984, "text": "The hello world app is a set of excellent visualization you can do with Streamlit. The above command will start a local development server and open the link in your default browser. You can also find the source codes on the same page. In addition, this sample app also has links to lots of advanced tutorials to educate yourself." }, { "code": null, "e": 2411, "s": 2314, "text": "Now that the setup is complete, let’s create an app to interact with our machine learning model." }, { "code": null, "e": 2607, "s": 2411, "text": "The app below uses Pandas, Scikit-Learn, Matplotlib, Seaborn, and Streamlit. Before starting, make sure you have installed all the required packages. If not, the below command will do it for you." }, { "code": null, "e": 2668, "s": 2607, "text": "pip install pandas scikit-learn matplotlib seaborn streamlit" }, { "code": null, "e": 2728, "s": 2668, "text": "Create a file named ‘quickstart.py’ with the below content." }, { "code": null, "e": 2823, "s": 2728, "text": "The above file is straightforward. For illustration purposes, I’ve added sections to the file." }, { "code": null, "e": 3203, "s": 2823, "text": "In the main app section, we have three lines. We added a title and a description to the page. Then we display the data frame on the page. The “st.write” function is an all-in-one solution. You could pass almost anything into this function, and Streamlit is smart enough to display the correct widget in the UI. To learn about different Streamlit functions, here is a cheat sheet." }, { "code": null, "e": 3253, "s": 3203, "text": "Let’s run our initial app with the below command." }, { "code": null, "e": 3282, "s": 3253, "text": "streamlilt run quickstart.py" }, { "code": null, "e": 3391, "s": 3282, "text": "Like the hello app, this command will start a new development server. On your browser, you’ll see the below." }, { "code": null, "e": 3494, "s": 3391, "text": "Congratulations, you just created your first web app; without HTML, CSS, and absolutely no JavaScript." }, { "code": null, "e": 3655, "s": 3494, "text": "But this is rudimentary. A web app could do lots of cool stuff. It could interact with the user in real-time and update its content. Let’s see how we can do it." }, { "code": null, "e": 3878, "s": 3655, "text": "Bringing interactions in the Streamlit web app is effortless. The Streamlit API contains several widgets. You can use them to get the user input and store its value in a variable. The rest is like any other python program." }, { "code": null, "e": 4053, "s": 3878, "text": "Let’s add a checkbox to toggle the dataset display. After all, no one develops a web app to see the raw data. Replace the data frame display (line 30) with the below content." }, { "code": null, "e": 4143, "s": 4053, "text": "If you refresh your browser, now you can see a checkbox to toggle the data frame display." }, { "code": null, "e": 4233, "s": 4143, "text": "But a toggle button in the middle of the app is not pleasing. Let’s move it to a sidebar." }, { "code": null, "e": 4400, "s": 4233, "text": "Again, another effortless action. The Streamlit API has the sidebar property. All the widgets you created in the main app are also available in this sidebar property." }, { "code": null, "e": 4619, "s": 4400, "text": "Create a sidebar variable by using the ‘st.sidebar’ property. Then move the checkbox assignment we added in the main app section to the sidebar section. Notice we now use ‘st.sidebar.checkbox’ instead of ‘st.checkbox.’" }, { "code": null, "e": 4777, "s": 4619, "text": "In the above code, we’ve also added a slider to the sidebar. This widget will capture the user-selected number of clusters. Here is how the output will look." }, { "code": null, "e": 4863, "s": 4777, "text": "Next stop, we’ll run the K means algorithm with the user-selected number of clusters." }, { "code": null, "e": 4944, "s": 4863, "text": "Extend the imports, helper functions, and main app sections with the below code." }, { "code": null, "e": 5115, "s": 4944, "text": "In the above code, we’ve created a function to run the K-Means algorithm. It takes the data frame and the number of clusters as arguments and returns a Matplotlib figure." }, { "code": null, "e": 5314, "s": 5115, "text": "The illustration of K-Means clustering is beyond the scope of this project. It’s a machine learning algorithm, and that’s what we care about. But you can refer to my previous post that describes it." }, { "code": null, "e": 5453, "s": 5314, "text": "We use the n_clusters variable that captures the slider value in the previous section as the second argument to the run_forecast function." }, { "code": null, "e": 5589, "s": 5453, "text": "If you refresh the page, you’ll see a dashboard that takes user input, runs a machine learning algorithm, and instantly updates the UI." }, { "code": null, "e": 5826, "s": 5589, "text": "Even if you are an experienced developer, this level of interaction and integration with back-end ML is a difficult task. Especially if you are a data scientist who doesn’t know how to develop web apps, it might take weeks of your time." }, { "code": null, "e": 6042, "s": 5826, "text": "Some tasks in a data science pipeline are time-consuming. Yet, such tasks rarely produce different results for the same inputs. You can use Streamlit’s inbuilt caching functions to store their values for future use." }, { "code": null, "e": 6331, "s": 6042, "text": "Although it might sound complicated, doing it with streamlit is simple. Your time-consuming task should be a function, and you wrap it with the @ts.cache decorator. As long as the input parameters are the same and the function’s body is untouched, Streamline will fetch it from the cache." }, { "code": null, "e": 6540, "s": 6331, "text": "In the app we built, we call the external URL to download data. If it’s a live API, you may not want to cache it. But in our case, it’s not. Therefore let’s cache it by replacing the line with the below code." }, { "code": null, "e": 6767, "s": 6540, "text": "On your first reload, you may see a message “Processing load_data” on your browser. But subsequent reloads won’t have that note. This is because requests are fetched from the cache instead of downloading from the external URL." }, { "code": null, "e": 6920, "s": 6767, "text": "If you’ve noticed the Streamlit console, you’ll also see a network URL. It means, if your firewall allows, your app can be accessible over the intranet." }, { "code": null, "e": 7068, "s": 6920, "text": "But if you want to share it outside your network, we have many options. As the documentation says, Streamlit apps work anywhere a Python app works." }, { "code": null, "e": 7575, "s": 7068, "text": "Streamlit Recommends the “Streamlit Sharing” option.You can put your code on a GitHub repository and configure Streamlit Sharing to serve your app.Streamlit sharing is free, but it’s currently invitation only. You can request an invitation for yourself.You can deploy it on cloud platforms. Here is an article that shows how to do it with AWS EC2 free instance.You can configure a reverse proxy. Proxy servers like Nginx and Apache can be configured to serve the app and restrict access for specific users." }, { "code": null, "e": 7829, "s": 7575, "text": "Streamlit Recommends the “Streamlit Sharing” option.You can put your code on a GitHub repository and configure Streamlit Sharing to serve your app.Streamlit sharing is free, but it’s currently invitation only. You can request an invitation for yourself." }, { "code": null, "e": 7938, "s": 7829, "text": "You can deploy it on cloud platforms. Here is an article that shows how to do it with AWS EC2 free instance." }, { "code": null, "e": 8084, "s": 7938, "text": "You can configure a reverse proxy. Proxy servers like Nginx and Apache can be configured to serve the app and restrict access for specific users." }, { "code": null, "e": 8191, "s": 8084, "text": "Be sure to read Streamlit’s community guide about deployment to explore numerous options available to you." }, { "code": null, "e": 8323, "s": 8191, "text": "Here is how I deployed this tutorial app on Streamlit Share. Once again, Streamlit didn’t fail to surprise me with its convenience." }, { "code": null, "e": 8505, "s": 8323, "text": "Step I: Put your code into a GitHub public repository.I’ve added my code to this GitHub repo. We need to make sure that it contains a requirement.txt file with all the dependencies." }, { "code": null, "e": 8560, "s": 8505, "text": "Step II: Log into Streamlit using your GitHub account." }, { "code": null, "e": 8784, "s": 8560, "text": "Step III: Create a new app on the Streamlit console.Choose your git hub repo from the dropdown or past in the URL. Select the branch that you want to use for the deployment. Finally, pick the main filename and click deploy." }, { "code": null, "e": 8909, "s": 8784, "text": "In about a minute, my app is live on Streamlit Share. But time to deployment may vary depending on the project requirements." }, { "code": null, "e": 9100, "s": 8909, "text": "Notice that streamlit share is currently an invitation-only thing. But I didn’t wait too long to get it. Streamlit’s deployment documentation contains a lot more helpful information on this." }, { "code": null, "e": 9280, "s": 9100, "text": "Needless to say, Streamlit solves a critical problem in data science projects. It gives data scientists the power to build web apps to interact with their machine learning models." }, { "code": null, "e": 9610, "s": 9280, "text": "In this introductory article, we’ve explored how we can use Streamlit with K-Means clustering. Although it’s a trivial application, it illustrates the core concepts of this technology. Besides development, we’ve also seen how effortless managing cache for performance in Streamlit. Lastly, we talked about the deployment options." }, { "code": null, "e": 9791, "s": 9610, "text": "Streamlit is much more than this. Please check their official documentation, which is filled with excellent tutorials. Also, their API cheat sheet is helpful for rapid development." }, { "code": null, "e": 9985, "s": 9791, "text": "A web app is a wonderful solution. But in some cases, you might have to think of other ways to interact with your ML models. Perhaps, building a command-line interface to your model could help." }, { "code": null, "e": 10008, "s": 9985, "text": "towardsdatascience.com" }, { "code": null, "e": 10122, "s": 10008, "text": "Thanks for the read, friend. It seems you and I have lots of common interests. Do check out my personal blog too." }, { "code": null, "e": 10197, "s": 10122, "text": "Say Hi to me on LinkedIn, Twitter, and Medium. I’ll break the ice for you." } ]
Program to check if all the values in a list that are greater than a given value in Python
In this tutorial, we will check whether all the elements in a list are greater than a number or not. For example, we have a list [1, 2, 3, 4, 5] and a number 0. If every value in the list is greater than the given value then, we return True else False. It's a simple program. We write it in less than 3 minutes. Try it yourself first. If you are not able to find the solution, then, follow the below steps to write the program. Initialise a list and any number Loop through the list. If yes, return **False** Return True. ## initializing the list values = [1, 2, 3, 4, 5] ## number num = 0 num_one = 1 ## function to check whether all the values of the list are greater than num or not def check(values, num): ## loop for value in values: ## if value less than num returns False if value <= num: return False ## if the following statement executes i.e., list contains values which are greater than given num return True print(check(values, num)) print(check(values, num_one)) If you run the above program, True False Another way to find it is using the all() inbuilt method. all() method returns True if every element from the iterable is True else it returns False. Let's see the program using all() method. ## initializing the list values = [1, 2, 3, 4, 5] ## number num = 0 num_one = 1 ## function to check whether all the values of the list are greater than num or not def check(values, num): ## all() method if all(value > num for value in values): return True else: return False print(check(values, num)) print(check(values, num_one)) If you run the above program, True False If you have any doubts regarding the program, please do mention them in the comment section.
[ { "code": null, "e": 1315, "s": 1062, "text": "In this tutorial, we will check whether all the elements in a list are greater than a number or not. For example, we have a list [1, 2, 3, 4, 5] and a number 0. If every value in the list is greater than the given value then, we return True else False." }, { "code": null, "e": 1490, "s": 1315, "text": "It's a simple program. We write it in less than 3 minutes. Try it yourself first. If you are not able to find the solution, then, follow the below steps to write the program." }, { "code": null, "e": 1523, "s": 1490, "text": "Initialise a list and any number" }, { "code": null, "e": 1546, "s": 1523, "text": "Loop through the list." }, { "code": null, "e": 1571, "s": 1546, "text": "If yes, return **False**" }, { "code": null, "e": 1584, "s": 1571, "text": "Return True." }, { "code": null, "e": 2098, "s": 1584, "text": "## initializing the list\n values = [1, 2, 3, 4, 5]\n## number num = 0\n num_one = 1\n## function to check whether all the values of the list are greater than num or not\n def check(values, num):\n ## loop\n for value in values:\n ## if value less than num returns False\n if value <= num:\n return False\n ## if the following statement executes i.e., list contains values which are greater than given num\n return True\n print(check(values, num))\n print(check(values, num_one))" }, { "code": null, "e": 2128, "s": 2098, "text": "If you run the above program," }, { "code": null, "e": 2139, "s": 2128, "text": "True False" }, { "code": null, "e": 2331, "s": 2139, "text": "Another way to find it is using the all() inbuilt method. all() method returns True if every element from the iterable is True else it returns False. Let's see the program using all() method." }, { "code": null, "e": 2684, "s": 2331, "text": "## initializing the list\nvalues = [1, 2, 3, 4, 5]\n## number\nnum = 0\nnum_one = 1\n## function to check whether all the values of the list are greater than num or not def check(values, num):\n ## all() method\n if all(value > num for value in values):\n return True\n else:\n return False\nprint(check(values, num))\nprint(check(values, num_one))" }, { "code": null, "e": 2714, "s": 2684, "text": "If you run the above program," }, { "code": null, "e": 2726, "s": 2714, "text": "True \nFalse" }, { "code": null, "e": 2819, "s": 2726, "text": "If you have any doubts regarding the program, please do mention them in the comment section." } ]
How to create a Modal Box with CSS and JavaScript?
To create a modal box with CSS and JavaScript, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: Arial, Helvetica, sans-serif; } .modal { text-align: center; display: none; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.4); } .modalContent { font-size: 20px; font-weight: bold; background-color: #fefefe; margin: auto; padding: 20px; border: 1px solid #888; width: 80%; } .close { color: rgb(255, 65, 65); float: right; font-size: 40px; font-weight: bold; } .close:hover, .close:focus { color: #ff1010; cursor: pointer; } </style> </head> <body> <h1>Modal Example</h1> <button class="openModal">Open Modal</button> <h2>Click on the above button to open modal</h2> <div class="modal"> <div class="modalContent"> <span class="close">×</span> <p>Sample text inside modal</p> </div> </div> <script> var modal = document.querySelector(".modal"); var btn = document.querySelector(".openModal"); var span = document.querySelector(".close"); btn.addEventListener("click", () => { modal.style.display = "block"; }); span.addEventListener("click", () => { modal.style.display = "none"; }); window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }; </script> </body> </html> The above code will produce the following output − On clicking the Open Modal button −
[ { "code": null, "e": 1134, "s": 1062, "text": "To create a modal box with CSS and JavaScript, the code is as follows −" }, { "code": null, "e": 1145, "s": 1134, "text": " Live Demo" }, { "code": null, "e": 2696, "s": 1145, "text": "<!DOCTYPE html>\n<html>\n<head>\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n<style>\n body {\n font-family: Arial, Helvetica, sans-serif;\n }\n .modal {\n text-align: center;\n display: none;\n position: fixed;\n z-index: 1;\n padding-top: 100px;\n left: 0;\n top: 0;\n width: 100%;\n height: 100%;\n background-color: rgba(0, 0, 0, 0.4);\n }\n .modalContent {\n font-size: 20px;\n font-weight: bold;\n background-color: #fefefe;\n margin: auto;\n padding: 20px;\n border: 1px solid #888;\n width: 80%;\n }\n .close {\n color: rgb(255, 65, 65);\n float: right;\n font-size: 40px;\n font-weight: bold;\n }\n .close:hover, .close:focus {\n color: #ff1010;\n cursor: pointer;\n }\n</style>\n</head>\n<body>\n<h1>Modal Example</h1>\n<button class=\"openModal\">Open Modal</button>\n<h2>Click on the above button to open modal</h2>\n<div class=\"modal\">\n<div class=\"modalContent\">\n<span class=\"close\">×</span>\n<p>Sample text inside modal</p>\n</div>\n</div>\n<script>\n var modal = document.querySelector(\".modal\");\n var btn = document.querySelector(\".openModal\");\n var span = document.querySelector(\".close\");\n btn.addEventListener(\"click\", () => {\n modal.style.display = \"block\";\n });\n span.addEventListener(\"click\", () => {\n modal.style.display = \"none\";\n });\n window.onclick = function(event) {\n if (event.target == modal) {\n modal.style.display = \"none\";\n }\n };\n</script>\n</body>\n</html>" }, { "code": null, "e": 2747, "s": 2696, "text": "The above code will produce the following output −" }, { "code": null, "e": 2783, "s": 2747, "text": "On clicking the Open Modal button −" } ]
Find the transition point in a binary array - GeeksforGeeks
20 Apr, 2022 Given a sorted array containing only numbers 0 and 1, the task is to find the transition point efficiently. The transition point is the point where “0” ends and “1” begins. Examples : Input: 0 0 0 1 1 Output: 3 Explanation: Index of first 1 is 3 Input: 0 0 0 0 1 1 1 1 Output: 4 Explanation: Index of first 1 is 4 Naive Approach: Traverse the array and print the index of the first 1. Traverse the array from the start to the end of the array.If the current element is 1, print the index and terminate the program. Traverse the array from the start to the end of the array. If the current element is 1, print the index and terminate the program. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find// the transition point#include<iostream>using namespace std; // Function to find the transition pointint findTransitionPoint(int arr[], int n){ //perform a linear search and // return the index of //first 1 for(int i=0; i<n ;i++) if(arr[i]==1) return i; //if no element is 1 return -1;} // Driver codeint main(){ int arr[] = {0, 0, 0, 0, 1, 1}; int n = sizeof(arr) / sizeof(arr[0]); int point = findTransitionPoint(arr, n); point >= 0 ? cout << "Transition point is " << point : cout<<"There is no transition point"; return 0;} // Java implementation to find the transition pointimport java.util.*; class GFG{ // Function to find the transition pointstatic int findTransitionPoint(int arr[], int n){ // perform a linear search and return the index of // first 1 for(int i = 0; i < n ; i++) if(arr[i] == 1) return i; // if no element is 1 return -1;} // Driver codepublic static void main (String[] args){ int arr[] = {0, 0, 0, 0, 1, 1}; int n = arr.length; int point = findTransitionPoint(arr, n); if (point >= 0) System.out.print("Transition point is " + point); else System.out.print("There is no transition point");}} // This code is contributed by shivanisinghss2110 # Python3 implementation to find the transition point # Function to find the transition pointdef findTransitionPoint(arr, n): # perform a linear search and return the index of # first 1 for i in range(n): if(arr[i] == 1): return i # if no element is 1 return -1 # Driver codearr = [0, 0, 0, 0, 1, 1]n = len(arr) point = findTransitionPoint(arr, n) if point >= 0: print("Transition point is", point)else: print("There is no transition point") # This code is contributed by shubhamsingh10 // C# implementation to find the transition pointusing System; class GFG{ // Function to find the transition pointstatic int findTransitionPoint(int []arr ,int n){ // perform a linear search and return the index of // first 1 for(int i = 0; i < n ; i++) if(arr[i] == 1) return i; // if no element is 1 return -1;} // Driver method public static void Main() { int []arr = {0, 0, 0, 0, 1, 1}; int point = findTransitionPoint(arr, arr.Length); Console.Write(point >= 0 ? "Transition point is " + point : "There is no transition point"); }} // This code is contributed by shivanisinghss2110 <script> // Javascript implementation to // find the transition point // Function to find the transition point function findTransitionPoint(arr, n) { // perform a linear search and // return the index of // first 1 for(let i = 0; i < n ; i++) if(arr[i] == 1) return i; // if no element is 1 return -1; } let arr = [0, 0, 0, 0, 1, 1]; let point = findTransitionPoint(arr, arr.length); document.write(point >= 0 ? "Transition point is " + point : "There is no transition point"); </script> Transition point is 4 Complexity Analysis: Time Complexity: O(n), Only one traversal is needed, so the time complexity is O(n) Auxiliary Space: O(1), No extra space is required. Efficient Approach: The idea is to use Binary Search, and find the smallest index of 1 in the array. As the array is sorted, binary search can be performed. Create two variables, l and r, initialize l = 0 and r = n-1 and a variable ans = -1 to store the answer.Iterate the steps below till l <= r, the lower-bound is less than the upper-bound.Check if the element at middle index mid = (l+r)/2, is one or not.If the element is one, then check for the least index of 1 element on the left side of the middle element, i.e. update r = mid – 1 and update ans = mid.If the element is zero, then check for the least index of 1 element on the right side of the middle element, i.e. update l = mid + 1. Create two variables, l and r, initialize l = 0 and r = n-1 and a variable ans = -1 to store the answer. Iterate the steps below till l <= r, the lower-bound is less than the upper-bound. Check if the element at middle index mid = (l+r)/2, is one or not. If the element is one, then check for the least index of 1 element on the left side of the middle element, i.e. update r = mid – 1 and update ans = mid. If the element is zero, then check for the least index of 1 element on the right side of the middle element, i.e. update l = mid + 1. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ implementation to find the transition point#include<iostream>using namespace std; // Function to find the transition pointint findTransitionPoint(int arr[], int n){ // Initialise lower and upper bounds int lb = 0, ub = n-1; // Perform Binary search while (lb <= ub) { // Find mid int mid = (lb+ub)/2; // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid+1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid-1; } } return -1;} // Driver Codeint main(){ int arr[] = {0, 0, 0, 0, 1, 1}; int n = sizeof(arr) / sizeof(arr[0]); int point = findTransitionPoint(arr, n); point >= 0 ? cout<<"Transition point is " << point : cout<<"There is no transition point"; return 0;} // Java implementation to find the transition point class Test { // Method to find the transition point static int findTransitionPoint(int arr[], int n) { // Initialise lower and upper bounds int lb = 0, ub = n - 1; // Perform Binary search while (lb <= ub) { // Find mid int mid = (lb + ub) / 2; // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid + 1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid - 1; } } return -1; } // Driver method public static void main(String args[]) { int arr[] = { 0, 0, 0, 0, 1, 1 }; int point = findTransitionPoint(arr, arr.length); System.out.println( point >= 0 ? "Transition point is " + point : "There is no transition point"); }} # python implementation to find the# transition point # Function to find the transition# pointdef findTransitionPoint(arr, n): # Initialise lower and upper # bounds lb = 0 ub = n - 1 # Perform Binary search while (lb <= ub): # Find mid mid = (int)((lb + ub) / 2) # update lower_bound if # mid contains 0 if (arr[mid] == 0): lb = mid + 1 # If mid contains 1 else if (arr[mid] == 1): # Check if it is the # left most 1 Return # mid, if yes if (mid == 0 \ or (mid > 0 and\ arr[mid - 1] == 0)): return mid # Else update # upper_bound ub = mid-1 return -1 # Driver codearr = [0, 0, 0, 0, 1, 1]n = len(arr)point = findTransitionPoint(arr, n);if(point >= 0): print("Transition point is ", point)else: print("There is no transition point") # This code is contributed by Sam007 // C# implementation to find the transition pointusing System; class GFG{ // Method to find the transition point static int findTransitionPoint(int []arr, int n) { // Initialise lower and upper bounds int lb = 0, ub = n-1; // Perform Binary search while (lb <= ub) { // Find mid int mid = (lb+ub)/2; // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid+1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid-1; } } return -1; } // Driver method public static void Main() { int []arr = {0, 0, 0, 0, 1, 1}; int point = findTransitionPoint(arr, arr.Length); Console.Write(point >= 0 ? "Transition point is " + point : "There is no transition point"); }} // This code is contributed by Sam007 <?php// PHP implementation to find// the transition point // Function to find the// transition pointfunction findTransitionPoint($arr, $n){ // Initialise lower and // upper bounds $lb = 0; $ub = $n-1; // Perform Binary search while ($lb <= $ub) { // Find mid $mid = floor(($lb + $ub) / 2); // update lower_bound // if mid contains 0 if ($arr[$mid] == 0) $lb = $mid + 1; // If mid contains 1 else if ($arr[$mid] == 1) { // Check if it is the // left most 1 // Return mid, if yes if ($mid == 0 or ($mid > 0 and $arr[$mid - 1] == 0)) return $mid; // Else update upper_bound $ub = $mid - 1; } } return -1;} // Driver Code $arr = array(0, 0, 0, 0, 1, 1); $n = sizeof($arr); $point = findTransitionPoint($arr, $n); if($point >= 0) echo "Transition point is " , $point; else echo"There is no transition point"; return 0; // This code is contributed by nitin mittal.?> <script> // Javascript implementation to find the transition point // Method to find the transition point function findTransitionPoint(arr, n) { // Initialise lower and upper bounds let lb = 0, ub = n-1; // Perform Binary search while (lb <= ub) { // Find mid let mid = parseInt((lb+ub)/2, 10); // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid+1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid-1; } } return -1; } let arr = [0, 0, 0, 0, 1, 1]; let point = findTransitionPoint(arr, arr.length); document.write(point >= 0 ? "Transition point is " + point : "There is no transition point"); </script> Transition point is 4 Complexity Analysis: Time Complexity: O(log n). The time complexity for binary search is O(log n). Auxiliary Space: O(1). No extra space is required. 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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 nitin mittal andrew1234 SHUBHAMSINGH10 shivanisinghss2110 yugi2000 divyeshrabadiya07 decode2207 surinderdawra388 simmytarika5 sweetyty Amazon Binary Search binary-string Arrays Amazon Arrays Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array Array of Strings in C++ (5 Different Ways to Create)
[ { "code": null, "e": 26373, "s": 26345, "text": "\n20 Apr, 2022" }, { "code": null, "e": 26546, "s": 26373, "text": "Given a sorted array containing only numbers 0 and 1, the task is to find the transition point efficiently. The transition point is the point where “0” ends and “1” begins." }, { "code": null, "e": 26558, "s": 26546, "text": "Examples : " }, { "code": null, "e": 26689, "s": 26558, "text": "Input: 0 0 0 1 1\nOutput: 3\nExplanation: Index of first 1 is 3\n\nInput: 0 0 0 0 1 1 1 1\nOutput: 4\nExplanation: Index of first 1 is 4" }, { "code": null, "e": 26762, "s": 26689, "text": "Naive Approach: Traverse the array and print the index of the first 1. " }, { "code": null, "e": 26892, "s": 26762, "text": "Traverse the array from the start to the end of the array.If the current element is 1, print the index and terminate the program." }, { "code": null, "e": 26951, "s": 26892, "text": "Traverse the array from the start to the end of the array." }, { "code": null, "e": 27023, "s": 26951, "text": "If the current element is 1, print the index and terminate the program." }, { "code": null, "e": 27074, "s": 27023, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27078, "s": 27074, "text": "C++" }, { "code": null, "e": 27083, "s": 27078, "text": "Java" }, { "code": null, "e": 27091, "s": 27083, "text": "Python3" }, { "code": null, "e": 27094, "s": 27091, "text": "C#" }, { "code": null, "e": 27105, "s": 27094, "text": "Javascript" }, { "code": "// C++ implementation to find// the transition point#include<iostream>using namespace std; // Function to find the transition pointint findTransitionPoint(int arr[], int n){ //perform a linear search and // return the index of //first 1 for(int i=0; i<n ;i++) if(arr[i]==1) return i; //if no element is 1 return -1;} // Driver codeint main(){ int arr[] = {0, 0, 0, 0, 1, 1}; int n = sizeof(arr) / sizeof(arr[0]); int point = findTransitionPoint(arr, n); point >= 0 ? cout << \"Transition point is \" << point : cout<<\"There is no transition point\"; return 0;}", "e": 27739, "s": 27105, "text": null }, { "code": "// Java implementation to find the transition pointimport java.util.*; class GFG{ // Function to find the transition pointstatic int findTransitionPoint(int arr[], int n){ // perform a linear search and return the index of // first 1 for(int i = 0; i < n ; i++) if(arr[i] == 1) return i; // if no element is 1 return -1;} // Driver codepublic static void main (String[] args){ int arr[] = {0, 0, 0, 0, 1, 1}; int n = arr.length; int point = findTransitionPoint(arr, n); if (point >= 0) System.out.print(\"Transition point is \" + point); else System.out.print(\"There is no transition point\");}} // This code is contributed by shivanisinghss2110", "e": 28447, "s": 27739, "text": null }, { "code": "# Python3 implementation to find the transition point # Function to find the transition pointdef findTransitionPoint(arr, n): # perform a linear search and return the index of # first 1 for i in range(n): if(arr[i] == 1): return i # if no element is 1 return -1 # Driver codearr = [0, 0, 0, 0, 1, 1]n = len(arr) point = findTransitionPoint(arr, n) if point >= 0: print(\"Transition point is\", point)else: print(\"There is no transition point\") # This code is contributed by shubhamsingh10", "e": 28987, "s": 28447, "text": null }, { "code": "// C# implementation to find the transition pointusing System; class GFG{ // Function to find the transition pointstatic int findTransitionPoint(int []arr ,int n){ // perform a linear search and return the index of // first 1 for(int i = 0; i < n ; i++) if(arr[i] == 1) return i; // if no element is 1 return -1;} // Driver method public static void Main() { int []arr = {0, 0, 0, 0, 1, 1}; int point = findTransitionPoint(arr, arr.Length); Console.Write(point >= 0 ? \"Transition point is \" + point : \"There is no transition point\"); }} // This code is contributed by shivanisinghss2110", "e": 29657, "s": 28987, "text": null }, { "code": "<script> // Javascript implementation to // find the transition point // Function to find the transition point function findTransitionPoint(arr, n) { // perform a linear search and // return the index of // first 1 for(let i = 0; i < n ; i++) if(arr[i] == 1) return i; // if no element is 1 return -1; } let arr = [0, 0, 0, 0, 1, 1]; let point = findTransitionPoint(arr, arr.length); document.write(point >= 0 ? \"Transition point is \" + point : \"There is no transition point\"); </script>", "e": 30274, "s": 29657, "text": null }, { "code": null, "e": 30296, "s": 30274, "text": "Transition point is 4" }, { "code": null, "e": 30318, "s": 30296, "text": "Complexity Analysis: " }, { "code": null, "e": 30402, "s": 30318, "text": "Time Complexity: O(n), Only one traversal is needed, so the time complexity is O(n)" }, { "code": null, "e": 30453, "s": 30402, "text": "Auxiliary Space: O(1), No extra space is required." }, { "code": null, "e": 30610, "s": 30453, "text": "Efficient Approach: The idea is to use Binary Search, and find the smallest index of 1 in the array. As the array is sorted, binary search can be performed." }, { "code": null, "e": 31148, "s": 30610, "text": "Create two variables, l and r, initialize l = 0 and r = n-1 and a variable ans = -1 to store the answer.Iterate the steps below till l <= r, the lower-bound is less than the upper-bound.Check if the element at middle index mid = (l+r)/2, is one or not.If the element is one, then check for the least index of 1 element on the left side of the middle element, i.e. update r = mid – 1 and update ans = mid.If the element is zero, then check for the least index of 1 element on the right side of the middle element, i.e. update l = mid + 1." }, { "code": null, "e": 31253, "s": 31148, "text": "Create two variables, l and r, initialize l = 0 and r = n-1 and a variable ans = -1 to store the answer." }, { "code": null, "e": 31336, "s": 31253, "text": "Iterate the steps below till l <= r, the lower-bound is less than the upper-bound." }, { "code": null, "e": 31403, "s": 31336, "text": "Check if the element at middle index mid = (l+r)/2, is one or not." }, { "code": null, "e": 31556, "s": 31403, "text": "If the element is one, then check for the least index of 1 element on the left side of the middle element, i.e. update r = mid – 1 and update ans = mid." }, { "code": null, "e": 31690, "s": 31556, "text": "If the element is zero, then check for the least index of 1 element on the right side of the middle element, i.e. update l = mid + 1." }, { "code": null, "e": 31741, "s": 31690, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 31745, "s": 31741, "text": "C++" }, { "code": null, "e": 31750, "s": 31745, "text": "Java" }, { "code": null, "e": 31758, "s": 31750, "text": "Python3" }, { "code": null, "e": 31761, "s": 31758, "text": "C#" }, { "code": null, "e": 31765, "s": 31761, "text": "PHP" }, { "code": null, "e": 31776, "s": 31765, "text": "Javascript" }, { "code": "// C++ implementation to find the transition point#include<iostream>using namespace std; // Function to find the transition pointint findTransitionPoint(int arr[], int n){ // Initialise lower and upper bounds int lb = 0, ub = n-1; // Perform Binary search while (lb <= ub) { // Find mid int mid = (lb+ub)/2; // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid+1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid-1; } } return -1;} // Driver Codeint main(){ int arr[] = {0, 0, 0, 0, 1, 1}; int n = sizeof(arr) / sizeof(arr[0]); int point = findTransitionPoint(arr, n); point >= 0 ? cout<<\"Transition point is \" << point : cout<<\"There is no transition point\"; return 0;}", "e": 32846, "s": 31776, "text": null }, { "code": "// Java implementation to find the transition point class Test { // Method to find the transition point static int findTransitionPoint(int arr[], int n) { // Initialise lower and upper bounds int lb = 0, ub = n - 1; // Perform Binary search while (lb <= ub) { // Find mid int mid = (lb + ub) / 2; // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid + 1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid - 1; } } return -1; } // Driver method public static void main(String args[]) { int arr[] = { 0, 0, 0, 0, 1, 1 }; int point = findTransitionPoint(arr, arr.length); System.out.println( point >= 0 ? \"Transition point is \" + point : \"There is no transition point\"); }}", "e": 34033, "s": 32846, "text": null }, { "code": "# python implementation to find the# transition point # Function to find the transition# pointdef findTransitionPoint(arr, n): # Initialise lower and upper # bounds lb = 0 ub = n - 1 # Perform Binary search while (lb <= ub): # Find mid mid = (int)((lb + ub) / 2) # update lower_bound if # mid contains 0 if (arr[mid] == 0): lb = mid + 1 # If mid contains 1 else if (arr[mid] == 1): # Check if it is the # left most 1 Return # mid, if yes if (mid == 0 \\ or (mid > 0 and\\ arr[mid - 1] == 0)): return mid # Else update # upper_bound ub = mid-1 return -1 # Driver codearr = [0, 0, 0, 0, 1, 1]n = len(arr)point = findTransitionPoint(arr, n);if(point >= 0): print(\"Transition point is \", point)else: print(\"There is no transition point\") # This code is contributed by Sam007", "e": 35033, "s": 34033, "text": null }, { "code": "// C# implementation to find the transition pointusing System; class GFG{ // Method to find the transition point static int findTransitionPoint(int []arr, int n) { // Initialise lower and upper bounds int lb = 0, ub = n-1; // Perform Binary search while (lb <= ub) { // Find mid int mid = (lb+ub)/2; // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid+1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid-1; } } return -1; } // Driver method public static void Main() { int []arr = {0, 0, 0, 0, 1, 1}; int point = findTransitionPoint(arr, arr.Length); Console.Write(point >= 0 ? \"Transition point is \" + point : \"There is no transition point\"); }} // This code is contributed by Sam007", "e": 36277, "s": 35033, "text": null }, { "code": "<?php// PHP implementation to find// the transition point // Function to find the// transition pointfunction findTransitionPoint($arr, $n){ // Initialise lower and // upper bounds $lb = 0; $ub = $n-1; // Perform Binary search while ($lb <= $ub) { // Find mid $mid = floor(($lb + $ub) / 2); // update lower_bound // if mid contains 0 if ($arr[$mid] == 0) $lb = $mid + 1; // If mid contains 1 else if ($arr[$mid] == 1) { // Check if it is the // left most 1 // Return mid, if yes if ($mid == 0 or ($mid > 0 and $arr[$mid - 1] == 0)) return $mid; // Else update upper_bound $ub = $mid - 1; } } return -1;} // Driver Code $arr = array(0, 0, 0, 0, 1, 1); $n = sizeof($arr); $point = findTransitionPoint($arr, $n); if($point >= 0) echo \"Transition point is \" , $point; else echo\"There is no transition point\"; return 0; // This code is contributed by nitin mittal.?>", "e": 37416, "s": 36277, "text": null }, { "code": "<script> // Javascript implementation to find the transition point // Method to find the transition point function findTransitionPoint(arr, n) { // Initialise lower and upper bounds let lb = 0, ub = n-1; // Perform Binary search while (lb <= ub) { // Find mid let mid = parseInt((lb+ub)/2, 10); // update lower_bound if mid contains 0 if (arr[mid] == 0) lb = mid+1; // If mid contains 1 else if (arr[mid] == 1) { // Check if it is the left most 1 // Return mid, if yes if (mid == 0 || (mid > 0 && arr[mid - 1] == 0)) return mid; // Else update upper_bound ub = mid-1; } } return -1; } let arr = [0, 0, 0, 0, 1, 1]; let point = findTransitionPoint(arr, arr.length); document.write(point >= 0 ? \"Transition point is \" + point : \"There is no transition point\"); </script>", "e": 38554, "s": 37416, "text": null }, { "code": null, "e": 38576, "s": 38554, "text": "Transition point is 4" }, { "code": null, "e": 38598, "s": 38576, "text": "Complexity Analysis: " }, { "code": null, "e": 38676, "s": 38598, "text": "Time Complexity: O(log n). The time complexity for binary search is O(log n)." }, { "code": null, "e": 38727, "s": 38676, "text": "Auxiliary Space: O(1). No extra space is required." }, { "code": null, "e": 39148, "s": 38727, "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 review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 39155, "s": 39148, "text": "Sam007" }, { "code": null, "e": 39168, "s": 39155, "text": "nitin mittal" }, { "code": null, "e": 39179, "s": 39168, "text": "andrew1234" }, { "code": null, "e": 39194, "s": 39179, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 39213, "s": 39194, "text": "shivanisinghss2110" }, { "code": null, "e": 39222, "s": 39213, "text": "yugi2000" }, { "code": null, "e": 39240, "s": 39222, "text": "divyeshrabadiya07" }, { "code": null, "e": 39251, "s": 39240, "text": "decode2207" }, { "code": null, "e": 39268, "s": 39251, "text": "surinderdawra388" }, { "code": null, "e": 39281, "s": 39268, "text": "simmytarika5" }, { "code": null, "e": 39290, "s": 39281, "text": "sweetyty" }, { "code": null, "e": 39297, "s": 39290, "text": "Amazon" }, { "code": null, "e": 39311, "s": 39297, "text": "Binary Search" }, { "code": null, "e": 39325, "s": 39311, "text": "binary-string" }, { "code": null, "e": 39332, "s": 39325, "text": "Arrays" }, { "code": null, "e": 39339, "s": 39332, "text": "Amazon" }, { "code": null, "e": 39346, "s": 39339, "text": "Arrays" }, { "code": null, "e": 39360, "s": 39346, "text": "Binary Search" }, { "code": null, "e": 39458, "s": 39360, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39526, "s": 39458, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 39570, "s": 39526, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 39618, "s": 39570, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 39641, "s": 39618, "text": "Introduction to Arrays" }, { "code": null, "e": 39673, "s": 39641, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 39687, "s": 39673, "text": "Linear Search" }, { "code": null, "e": 39708, "s": 39687, "text": "Linked List vs Array" }, { "code": null, "e": 39753, "s": 39708, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 39801, "s": 39753, "text": "Search an element in a sorted and rotated array" } ]
Program to convert a Map to a Stream in Java - GeeksforGeeks
11 Dec, 2018 A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. Below are various method to convert Map to Stream in Java: Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.entrySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<Map.Entry<K, V> > convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set .entrySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<Map.Entry<Integer, String> > stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [1=Geeks, 2=forGeeks, 3=A computer Portal] Converting only the Keyset of the Map<Key, Value> into Stream: This can be done with the help of Map.keySet() method which returns a Set view of the keys contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.keySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<K> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Key> .keySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<Integer> stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [1, 2, 3] Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map.values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Value> using Map.values() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<V> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Value> .values() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<String> stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [Geeks, forGeeks, A computer Portal] Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.entrySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<Map.Entry<K, V> > convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set .entrySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<Map.Entry<Integer, String> > stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [1=Geeks, 2=forGeeks, 3=A computer Portal] Algorithm: Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.entrySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map. Get the Map<Key, Value>. Convert Map<Key, Value> into Set<Key> using Map.entrySet() method. Convert the obtained Set into Stream using Set.stream() Return/Print the Stream of Map. Program: // Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<Map.Entry<K, V> > convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set .entrySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<Map.Entry<Integer, String> > stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }} Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [1=Geeks, 2=forGeeks, 3=A computer Portal] Converting only the Keyset of the Map<Key, Value> into Stream: This can be done with the help of Map.keySet() method which returns a Set view of the keys contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.keySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<K> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Key> .keySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<Integer> stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [1, 2, 3] Algorithm: Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.keySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map. Get the Map<Key, Value>. Convert Map<Key, Value> into Set<Key> using Map.keySet() method. Convert the obtained Set into Stream using Set.stream() Return/Print the Stream of Map. Program: // Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<K> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Key> .keySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<Integer> stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }} Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [1, 2, 3] Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map.values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Value> using Map.values() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<V> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Value> .values() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<String> stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [Geeks, forGeeks, A computer Portal] Algorithm: Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Value> using Map.values() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map. Get the Map<Key, Value>. Convert Map<Key, Value> into Set<Value> using Map.values() method. Convert the obtained Set into Stream using Set.stream() Return/Print the Stream of Map. Program: // Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<V> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Value> .values() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, "Geeks"); map.put(2, "forGeeks"); map.put(3, "A computer Portal"); // Print the Map System.out.println("Map: " + map); // Convert the Map to Stream Stream<String> stream = convertMapToStream(map); // Print the TreeMap System.out.println("Stream: " + Arrays.toString(stream.toArray())); }} Map: {1=Geeks, 2=forGeeks, 3=A computer Portal} Stream: [Geeks, forGeeks, A computer Portal] Java - util package java-map java-stream Java-Stream-programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25483, "s": 25455, "text": "\n11 Dec, 2018" }, { "code": null, "e": 25601, "s": 25483, "text": "A Stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result." }, { "code": null, "e": 25660, "s": 25601, "text": "Below are various method to convert Map to Stream in Java:" }, { "code": null, "e": 30487, "s": 25660, "text": "Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.entrySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<Map.Entry<K, V> > convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set .entrySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<Map.Entry<Integer, String> > stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [1=Geeks, 2=forGeeks, 3=A computer Portal]\nConverting only the Keyset of the Map<Key, Value> into Stream: This can be done with the help of Map.keySet() method which returns a Set view of the keys contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.keySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<K> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Key> .keySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<Integer> stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [1, 2, 3]\nConverting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map.values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Value> using Map.values() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<V> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Value> .values() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<String> stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [Geeks, forGeeks, A computer Portal]\n" }, { "code": null, "e": 32150, "s": 30487, "text": "Converting complete Map<Key, Value> into Stream: This can be done with the help of Map.entrySet() method which returns a Set view of the mappings contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.entrySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<Map.Entry<K, V> > convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set .entrySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<Map.Entry<Integer, String> > stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [1=Geeks, 2=forGeeks, 3=A computer Portal]\n" }, { "code": null, "e": 32161, "s": 32150, "text": "Algorithm:" }, { "code": null, "e": 32338, "s": 32161, "text": "Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.entrySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map." }, { "code": null, "e": 32363, "s": 32338, "text": "Get the Map<Key, Value>." }, { "code": null, "e": 32430, "s": 32363, "text": "Convert Map<Key, Value> into Set<Key> using Map.entrySet() method." }, { "code": null, "e": 32486, "s": 32430, "text": "Convert the obtained Set into Stream using Set.stream()" }, { "code": null, "e": 32518, "s": 32486, "text": "Return/Print the Stream of Map." }, { "code": null, "e": 32527, "s": 32518, "text": "Program:" }, { "code": "// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<Map.Entry<K, V> > convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set .entrySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<Map.Entry<Integer, String> > stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}", "e": 33609, "s": 32527, "text": null }, { "code": null, "e": 33709, "s": 33609, "text": "Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [1=Geeks, 2=forGeeks, 3=A computer Portal]\n" }, { "code": null, "e": 35276, "s": 33709, "text": "Converting only the Keyset of the Map<Key, Value> into Stream: This can be done with the help of Map.keySet() method which returns a Set view of the keys contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.keySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<K> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Key> .keySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<Integer> stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [1, 2, 3]\n" }, { "code": null, "e": 35287, "s": 35276, "text": "Algorithm:" }, { "code": null, "e": 35462, "s": 35287, "text": "Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Key> using Map.keySet() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map." }, { "code": null, "e": 35487, "s": 35462, "text": "Get the Map<Key, Value>." }, { "code": null, "e": 35552, "s": 35487, "text": "Convert Map<Key, Value> into Set<Key> using Map.keySet() method." }, { "code": null, "e": 35608, "s": 35552, "text": "Convert the obtained Set into Stream using Set.stream()" }, { "code": null, "e": 35640, "s": 35608, "text": "Return/Print the Stream of Map." }, { "code": null, "e": 35649, "s": 35640, "text": "Program:" }, { "code": "// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<K> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Key> .keySet() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<Integer> stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}", "e": 36662, "s": 35649, "text": null }, { "code": null, "e": 36729, "s": 36662, "text": "Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [1, 2, 3]\n" }, { "code": null, "e": 38328, "s": 36729, "text": "Converting only the Value of the Map<Key, Value> into Stream: This can be done with the help of Map.values() method which returns a Set view of the values contained in this map. In Java 8, this returned set can be easily converted into a Stream of key-value pairs using Set.stream() method.Algorithm:Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Value> using Map.values() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map.Program:// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<V> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Value> .values() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<String> stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}Output:Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [Geeks, forGeeks, A computer Portal]\n" }, { "code": null, "e": 38339, "s": 38328, "text": "Algorithm:" }, { "code": null, "e": 38516, "s": 38339, "text": "Get the Map<Key, Value>.Convert Map<Key, Value> into Set<Value> using Map.values() method.Convert the obtained Set into Stream using Set.stream()Return/Print the Stream of Map." }, { "code": null, "e": 38541, "s": 38516, "text": "Get the Map<Key, Value>." }, { "code": null, "e": 38608, "s": 38541, "text": "Convert Map<Key, Value> into Set<Value> using Map.values() method." }, { "code": null, "e": 38664, "s": 38608, "text": "Convert the obtained Set into Stream using Set.stream()" }, { "code": null, "e": 38696, "s": 38664, "text": "Return/Print the Stream of Map." }, { "code": null, "e": 38705, "s": 38696, "text": "Program:" }, { "code": "// Java Program to convert// Map<Key, Value> into Stream import java.util.*;import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of Integer public static <K, V> Stream<V> convertMapToStream(Map<K, V> map) { // Return the obtained Stream return map // Convert the Map to Set<Value> .values() // Convert the Set to Stream .stream(); } public static void main(String args[]) { // Create a Map Map<Integer, String> map = new HashMap<>(); // Add entries to the Map map.put(1, \"Geeks\"); map.put(2, \"forGeeks\"); map.put(3, \"A computer Portal\"); // Print the Map System.out.println(\"Map: \" + map); // Convert the Map to Stream Stream<String> stream = convertMapToStream(map); // Print the TreeMap System.out.println(\"Stream: \" + Arrays.toString(stream.toArray())); }}", "e": 39720, "s": 38705, "text": null }, { "code": null, "e": 39814, "s": 39720, "text": "Map: {1=Geeks, 2=forGeeks, 3=A computer Portal}\nStream: [Geeks, forGeeks, A computer Portal]\n" }, { "code": null, "e": 39834, "s": 39814, "text": "Java - util package" }, { "code": null, "e": 39843, "s": 39834, "text": "java-map" }, { "code": null, "e": 39855, "s": 39843, "text": "java-stream" }, { "code": null, "e": 39876, "s": 39855, "text": "Java-Stream-programs" }, { "code": null, "e": 39881, "s": 39876, "text": "Java" }, { "code": null, "e": 39895, "s": 39881, "text": "Java Programs" }, { "code": null, "e": 39900, "s": 39895, "text": "Java" }, { "code": null, "e": 39998, "s": 39900, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40049, "s": 39998, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 40079, "s": 40049, "text": "HashMap in Java with Examples" }, { "code": null, "e": 40098, "s": 40079, "text": "Interfaces in Java" }, { "code": null, "e": 40129, "s": 40098, "text": "How to iterate any Map in Java" }, { "code": null, "e": 40147, "s": 40129, "text": "ArrayList in Java" }, { "code": null, "e": 40175, "s": 40147, "text": "Initializing a List in Java" }, { "code": null, "e": 40219, "s": 40175, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 40245, "s": 40219, "text": "Java Programming Examples" }, { "code": null, "e": 40279, "s": 40245, "text": "Convert Double to Integer in Java" } ]
Program to build DFA that starts and end with 'a' from input (a, b) - GeeksforGeeks
10 Jul, 2021 DFA (Deterministic Finite Automaton or Acceptor) is a finite state machine that accepts or rejects strings of symbols. DFA accepts the string if it reaches the final state and rejects otherwise. Now the problem is, provided a string as input character by character and we have to check whether the string starts and ends with ‘a’. We can only store the current character, since there is no concept of memory and hence the DFA cannot store the string provided. Otherwise, we could have just checked the first and last character for this problem. The input set for this problem is (a, b).We cannot store anything accept the current character, which make this program a little different and tough than other string related problems. Examples: Input : a b a b a Output : Yes Explanation : (a b a b a) starts and end with 'a' Input : a b a b b Output : No Explanation : (a b a b b) starts with 'a' but doesn't end with 'a' We first build a DFA for this problem. Making DFA is like making a flowchart for this program and then implement it in any language. You should have the knowledge of DFA and Finite Automata. The DFA for given problem is: C++ Java C# Javascript // C++ Program to DFA that accept strings// which starts and end with 'a' over input(a, b)#include <iostream>#include <time.h>using namespace std; int main(){ // for producing different random // numbers every time. srand(time(0)); // random length of string from 1 - 16 // we are taking input from input stream, // we can take delimiter to end the string int max = 1 + rand() % 15; // generating random string and processing it int i = 0; while (i < max) { // producing random character over // input alphabet (a, b) char c = 'a' + rand() % 2; cout << c << " "; i++; // first character is 'a' if (c == 'a') { // if there is only 1 character // i.e. 'a' if (i == max) cout << "YES\n"; while (i < max) { c = 'a' + rand() % 2; cout << c << " "; i++; // if character is 'a' and it // is the last character if (c == 'a' && i == max) { cout << "\nYES\n"; } // if character is 'b' and it // is the last character else if (i == max) { cout << "\nNO\n"; } } } // first character is 'b' so no matter // what the string is, it is not going // to be accepted else { while (i < max) { c = 'a' + rand() % 2; cout << c << " "; i++; } cout << "\nNO\n"; } } return 0;} // JAVA Program to DFA that accept Strings// which starts and end with 'a' over input(a, b)import java.util.*; class GFG{ public static void main(String[] args){ // for producing different random // numbers every time. Random r = new Random(); // random length of String from 1 - 16 // we are taking input from input stream, // we can take delimiter to end the String int max = 1 + r.nextInt()*10 % 15; // generating random String and processing it int i = 0; while (i < max) { // producing random character over // input alphabet (a, b) char c = (char) ('a' + r.nextInt()*10 % 2); System.out.print(c+ " "); i++; // first character is 'a' if (c == 'a') { // if there is only 1 character // i.e. 'a' if (i == max) System.out.print("YES\n"); while (i < max) { c = (char) ('a' + r.nextInt()*10 % 2); System.out.print(c+ " "); i++; // if character is 'a' and it // is the last character if (c == 'a' && i == max) { System.out.print("\nYES\n"); } // if character is 'b' and it // is the last character else if (i == max) { System.out.print("\nNO\n"); } } } // first character is 'b' so no matter // what the String is, it is not going // to be accepted else { while (i < max) { c = (char) ('a' + r.nextInt()*10 % 2); System.out.print(c+ " "); i++; } System.out.print("\nNO\n"); } }}} // This code is contributed by PrinciRaj1992 // C# Program to DFA that accept Strings// which starts and end with 'a' over i.Add(a, b)using System; class GFG{ static void Main(String[] args){ // random length of String from 1 - 16 // we are taking input from input stream, // we can take delimiter to end the String int max = 1 + new Random().Next()*10 % 15; // generating random String and processing it int i = 0; while (i < max) { // producing random character over // input alphabet (a, b) char c = (char) ('a' + new Random().Next()*10 % 2); Console.Write(c + " "); i++; // first character is 'a' if (c == 'a') { // if there is only 1 character // i.e. 'a' if (i == max) Console.Write("YES\n"); while (i < max) { c = (char) ('a' + new Random().Next()*10 % 2); Console.Write(c + " "); i++; // if character is 'a' and it // is the last character if (c == 'a' && i == max) { Console.Write("\nYES\n"); } // if character is 'b' and it // is the last character else if (i == max) { Console.Write("\nNO\n"); } } } // first character is 'b' so no matter // what the String is, it is not going // to be accepted else { while (i < max) { c = (char) ('a' + new Random().Next()*10 % 2); Console.Write(c + " "); i++; } Console.Write("\nNO\n"); } }}} // This code is contributed by 29AjayKumar <script> // Javascript program to DFA that accept strings// which starts and end with 'a' over input(a, b) // Random length of String from 1 - 16// we are taking input from input stream,// we can take delimiter to end the Stringlet max = 1 + Math.floor(Math.random() * 10 % 15); // Generating random String and processing itlet i = 0;while (i < max){ // Producing random character over // input alphabet (a, b) let c = String.fromCharCode( 'a'.charCodeAt(0) + Math.floor(Math.random() * 10) % 2); document.write(c + " "); i++; // First character is 'a' if (c == 'a') { // If there is only 1 character // i.e. 'a' if (i == max) document.write("YES<br>"); while (i < max) { c = String.fromCharCode( 'a'.charCodeAt(0) + Math.floor(Math.random() * 10) % 2); document.write(c + " "); i++; // If character is 'a' and it // is the last character if (c == 'a' && i == max) { document.write("<br>YES<br>"); } // If character is 'b' and it // is the last character else if (i == max) { document.write("<br>NO<br>"); } } } // First character is 'b' so no matter // what the String is, it is not going // to be accepted else { while (i < max) { c = String.fromCharCode( 'a'.charCodeAt(0) + Math.floor(Math.random() * 10) % 2); document.write(c + " "); i++; } document.write("<br>NO<br>"); }} // This code is contributed by rag2127 </script> Output: a a b a a YES princiraj1992 29AjayKumar rag2127 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Print all the duplicates in the input string Vigenère Cipher String class in Java | Set 1 sprintf() in C Print all subsequences of a string Convert character array to string in C++ How to Append a Character to a String in C Program to count occurrence of a given character in a string Naive algorithm for Pattern Searching
[ { "code": null, "e": 26099, "s": 26071, "text": "\n10 Jul, 2021" }, { "code": null, "e": 26830, "s": 26099, "text": "DFA (Deterministic Finite Automaton or Acceptor) is a finite state machine that accepts or rejects strings of symbols. DFA accepts the string if it reaches the final state and rejects otherwise. Now the problem is, provided a string as input character by character and we have to check whether the string starts and ends with ‘a’. We can only store the current character, since there is no concept of memory and hence the DFA cannot store the string provided. Otherwise, we could have just checked the first and last character for this problem. The input set for this problem is (a, b).We cannot store anything accept the current character, which make this program a little different and tough than other string related problems. " }, { "code": null, "e": 26841, "s": 26830, "text": "Examples: " }, { "code": null, "e": 27027, "s": 26841, "text": "Input : a b a b a\nOutput : Yes\nExplanation : (a b a b a) starts and \nend with 'a'\n\nInput : a b a b b\nOutput : No\nExplanation : (a b a b b) starts with \n'a' but doesn't end with 'a' " }, { "code": null, "e": 27218, "s": 27027, "text": "We first build a DFA for this problem. Making DFA is like making a flowchart for this program and then implement it in any language. You should have the knowledge of DFA and Finite Automata." }, { "code": null, "e": 27249, "s": 27218, "text": "The DFA for given problem is: " }, { "code": null, "e": 27253, "s": 27249, "text": "C++" }, { "code": null, "e": 27258, "s": 27253, "text": "Java" }, { "code": null, "e": 27261, "s": 27258, "text": "C#" }, { "code": null, "e": 27272, "s": 27261, "text": "Javascript" }, { "code": "// C++ Program to DFA that accept strings// which starts and end with 'a' over input(a, b)#include <iostream>#include <time.h>using namespace std; int main(){ // for producing different random // numbers every time. srand(time(0)); // random length of string from 1 - 16 // we are taking input from input stream, // we can take delimiter to end the string int max = 1 + rand() % 15; // generating random string and processing it int i = 0; while (i < max) { // producing random character over // input alphabet (a, b) char c = 'a' + rand() % 2; cout << c << \" \"; i++; // first character is 'a' if (c == 'a') { // if there is only 1 character // i.e. 'a' if (i == max) cout << \"YES\\n\"; while (i < max) { c = 'a' + rand() % 2; cout << c << \" \"; i++; // if character is 'a' and it // is the last character if (c == 'a' && i == max) { cout << \"\\nYES\\n\"; } // if character is 'b' and it // is the last character else if (i == max) { cout << \"\\nNO\\n\"; } } } // first character is 'b' so no matter // what the string is, it is not going // to be accepted else { while (i < max) { c = 'a' + rand() % 2; cout << c << \" \"; i++; } cout << \"\\nNO\\n\"; } } return 0;}", "e": 28913, "s": 27272, "text": null }, { "code": "// JAVA Program to DFA that accept Strings// which starts and end with 'a' over input(a, b)import java.util.*; class GFG{ public static void main(String[] args){ // for producing different random // numbers every time. Random r = new Random(); // random length of String from 1 - 16 // we are taking input from input stream, // we can take delimiter to end the String int max = 1 + r.nextInt()*10 % 15; // generating random String and processing it int i = 0; while (i < max) { // producing random character over // input alphabet (a, b) char c = (char) ('a' + r.nextInt()*10 % 2); System.out.print(c+ \" \"); i++; // first character is 'a' if (c == 'a') { // if there is only 1 character // i.e. 'a' if (i == max) System.out.print(\"YES\\n\"); while (i < max) { c = (char) ('a' + r.nextInt()*10 % 2); System.out.print(c+ \" \"); i++; // if character is 'a' and it // is the last character if (c == 'a' && i == max) { System.out.print(\"\\nYES\\n\"); } // if character is 'b' and it // is the last character else if (i == max) { System.out.print(\"\\nNO\\n\"); } } } // first character is 'b' so no matter // what the String is, it is not going // to be accepted else { while (i < max) { c = (char) ('a' + r.nextInt()*10 % 2); System.out.print(c+ \" \"); i++; } System.out.print(\"\\nNO\\n\"); } }}} // This code is contributed by PrinciRaj1992", "e": 30790, "s": 28913, "text": null }, { "code": "// C# Program to DFA that accept Strings// which starts and end with 'a' over i.Add(a, b)using System; class GFG{ static void Main(String[] args){ // random length of String from 1 - 16 // we are taking input from input stream, // we can take delimiter to end the String int max = 1 + new Random().Next()*10 % 15; // generating random String and processing it int i = 0; while (i < max) { // producing random character over // input alphabet (a, b) char c = (char) ('a' + new Random().Next()*10 % 2); Console.Write(c + \" \"); i++; // first character is 'a' if (c == 'a') { // if there is only 1 character // i.e. 'a' if (i == max) Console.Write(\"YES\\n\"); while (i < max) { c = (char) ('a' + new Random().Next()*10 % 2); Console.Write(c + \" \"); i++; // if character is 'a' and it // is the last character if (c == 'a' && i == max) { Console.Write(\"\\nYES\\n\"); } // if character is 'b' and it // is the last character else if (i == max) { Console.Write(\"\\nNO\\n\"); } } } // first character is 'b' so no matter // what the String is, it is not going // to be accepted else { while (i < max) { c = (char) ('a' + new Random().Next()*10 % 2); Console.Write(c + \" \"); i++; } Console.Write(\"\\nNO\\n\"); } }}} // This code is contributed by 29AjayKumar", "e": 32573, "s": 30790, "text": null }, { "code": "<script> // Javascript program to DFA that accept strings// which starts and end with 'a' over input(a, b) // Random length of String from 1 - 16// we are taking input from input stream,// we can take delimiter to end the Stringlet max = 1 + Math.floor(Math.random() * 10 % 15); // Generating random String and processing itlet i = 0;while (i < max){ // Producing random character over // input alphabet (a, b) let c = String.fromCharCode( 'a'.charCodeAt(0) + Math.floor(Math.random() * 10) % 2); document.write(c + \" \"); i++; // First character is 'a' if (c == 'a') { // If there is only 1 character // i.e. 'a' if (i == max) document.write(\"YES<br>\"); while (i < max) { c = String.fromCharCode( 'a'.charCodeAt(0) + Math.floor(Math.random() * 10) % 2); document.write(c + \" \"); i++; // If character is 'a' and it // is the last character if (c == 'a' && i == max) { document.write(\"<br>YES<br>\"); } // If character is 'b' and it // is the last character else if (i == max) { document.write(\"<br>NO<br>\"); } } } // First character is 'b' so no matter // what the String is, it is not going // to be accepted else { while (i < max) { c = String.fromCharCode( 'a'.charCodeAt(0) + Math.floor(Math.random() * 10) % 2); document.write(c + \" \"); i++; } document.write(\"<br>NO<br>\"); }} // This code is contributed by rag2127 </script>", "e": 34372, "s": 32573, "text": null }, { "code": null, "e": 34381, "s": 34372, "text": "Output: " }, { "code": null, "e": 34396, "s": 34381, "text": "a a b a a \nYES" }, { "code": null, "e": 34412, "s": 34398, "text": "princiraj1992" }, { "code": null, "e": 34424, "s": 34412, "text": "29AjayKumar" }, { "code": null, "e": 34432, "s": 34424, "text": "rag2127" }, { "code": null, "e": 34440, "s": 34432, "text": "Strings" }, { "code": null, "e": 34448, "s": 34440, "text": "Strings" }, { "code": null, "e": 34546, "s": 34448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34591, "s": 34546, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 34636, "s": 34591, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 34653, "s": 34636, "text": "Vigenère Cipher" }, { "code": null, "e": 34682, "s": 34653, "text": "String class in Java | Set 1" }, { "code": null, "e": 34697, "s": 34682, "text": "sprintf() in C" }, { "code": null, "e": 34732, "s": 34697, "text": "Print all subsequences of a string" }, { "code": null, "e": 34773, "s": 34732, "text": "Convert character array to string in C++" }, { "code": null, "e": 34816, "s": 34773, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 34877, "s": 34816, "text": "Program to count occurrence of a given character in a string" } ]
Variable Length Argument in C - GeeksforGeeks
12 Nov, 2017 Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.1) Sum of given numbers.2) Minimum of given numbers.and many more. Variable number of arguments are represented by three dotes (...) Below is an example, to find minimum of given set of integers. // C program to demonstrate use of variable// number of arguments.#include <stdarg.h>#include <stdio.h> // this function returns minimum of integer// numbers passed. First argument is count// of numbers.int min(int arg_count, ...){ int i; int min, a; // va_list is a type to hold information about // variable arguments va_list ap; // va_start must be called before accessing // variable argument list va_start(ap, arg_count); // Now arguments can be accessed one by one // using va_arg macro. Initialize min as first // argument in list min = va_arg(ap, int); // traverse rest of the arguments to find out minimum for (i = 2; i <= arg_count; i++) if ((a = va_arg(ap, int)) < min) min = a; // va_end should be executed before the function // returns whenever va_start has been previously // used in that function va_end(ap); return min;} // Driver codeint main(){ int count = 5; printf("Minimum value is %d", min(count, 12, 67, 6, 7, 100)); return 0;} Here we use macros to implement the functionality of variable arguments. Use va_list type variable in the function definition.int a_function(int x, ...) { va_list a_list; va_start( a_list, x ); } int a_function(int x, ...) { va_list a_list; va_start( a_list, x ); } Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file. Use va_arg macro and va_list variable to access each item in argument list. macro va_end to clean up the memory assigned to va_list variable. Another Example : // C program to demonstrate working of // variable arguments to find average// of multiple numbers.#include <stdarg.h>#include <stdio.h> int average(int num, ...){ va_list valist; int sum = 0, i; va_start(valist, num); for (i = 0; i < num; i++) sum += va_arg(valist, int); va_end(valist); return sum / num;} // Driver codeint main(){ printf("Average of {2, 3, 4} = %d\n", average(2, 3, 4)); printf("Average of {3, 5, 10, 15} = %d\n", average(3, 5, 10, 15)); return 0;} Output: Average of {2, 3, 4} = 3 Average of {3, 5, 10, 15} = 10 C-Functions C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ Arrow operator -> in C/C++ with Examples Ways to copy a vector in C++ Smart Pointers in C++ and How to Use Them Multiple Inheritance in C++ Understanding "extern" keyword in C How to split a string in C/C++, Python and Java?
[ { "code": null, "e": 25477, "s": 25449, "text": "\n12 Nov, 2017" }, { "code": null, "e": 25751, "s": 25477, "text": "Variable length argument is a feature that allows a function to receive any number of arguments. There are situations where we want a function to handle variable number of arguments according to requirement.1) Sum of given numbers.2) Minimum of given numbers.and many more." }, { "code": null, "e": 25817, "s": 25751, "text": "Variable number of arguments are represented by three dotes (...)" }, { "code": null, "e": 25880, "s": 25817, "text": "Below is an example, to find minimum of given set of integers." }, { "code": "// C program to demonstrate use of variable// number of arguments.#include <stdarg.h>#include <stdio.h> // this function returns minimum of integer// numbers passed. First argument is count// of numbers.int min(int arg_count, ...){ int i; int min, a; // va_list is a type to hold information about // variable arguments va_list ap; // va_start must be called before accessing // variable argument list va_start(ap, arg_count); // Now arguments can be accessed one by one // using va_arg macro. Initialize min as first // argument in list min = va_arg(ap, int); // traverse rest of the arguments to find out minimum for (i = 2; i <= arg_count; i++) if ((a = va_arg(ap, int)) < min) min = a; // va_end should be executed before the function // returns whenever va_start has been previously // used in that function va_end(ap); return min;} // Driver codeint main(){ int count = 5; printf(\"Minimum value is %d\", min(count, 12, 67, 6, 7, 100)); return 0;}", "e": 26931, "s": 25880, "text": null }, { "code": null, "e": 27004, "s": 26931, "text": "Here we use macros to implement the functionality of variable arguments." }, { "code": null, "e": 27135, "s": 27004, "text": "Use va_list type variable in the function definition.int a_function(int x, ...)\n{\n va_list a_list;\n va_start( a_list, x );\n}" }, { "code": null, "e": 27213, "s": 27135, "text": "int a_function(int x, ...)\n{\n va_list a_list;\n va_start( a_list, x );\n}" }, { "code": null, "e": 27361, "s": 27213, "text": "Use int parameter and va_start macro to initialize the va_list variable to an argument list. The macro va_start is defined in stdarg.h header file." }, { "code": null, "e": 27437, "s": 27361, "text": "Use va_arg macro and va_list variable to access each item in argument list." }, { "code": null, "e": 27503, "s": 27437, "text": "macro va_end to clean up the memory assigned to va_list variable." }, { "code": null, "e": 27521, "s": 27503, "text": "Another Example :" }, { "code": "// C program to demonstrate working of // variable arguments to find average// of multiple numbers.#include <stdarg.h>#include <stdio.h> int average(int num, ...){ va_list valist; int sum = 0, i; va_start(valist, num); for (i = 0; i < num; i++) sum += va_arg(valist, int); va_end(valist); return sum / num;} // Driver codeint main(){ printf(\"Average of {2, 3, 4} = %d\\n\", average(2, 3, 4)); printf(\"Average of {3, 5, 10, 15} = %d\\n\", average(3, 5, 10, 15)); return 0;}", "e": 28080, "s": 27521, "text": null }, { "code": null, "e": 28088, "s": 28080, "text": "Output:" }, { "code": null, "e": 28145, "s": 28088, "text": "Average of {2, 3, 4} = 3\nAverage of {3, 5, 10, 15} = 10\n" }, { "code": null, "e": 28157, "s": 28145, "text": "C-Functions" }, { "code": null, "e": 28168, "s": 28157, "text": "C Language" }, { "code": null, "e": 28266, "s": 28168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28304, "s": 28266, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 28330, "s": 28304, "text": "Exception Handling in C++" }, { "code": null, "e": 28350, "s": 28330, "text": "Multithreading in C" }, { "code": null, "e": 28372, "s": 28350, "text": "'this' pointer in C++" }, { "code": null, "e": 28413, "s": 28372, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 28442, "s": 28413, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 28484, "s": 28442, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 28512, "s": 28484, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 28548, "s": 28512, "text": "Understanding \"extern\" keyword in C" } ]
Replace each node in binary tree with the sum of its inorder predecessor and successor - GeeksforGeeks
25 Apr, 2022 Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor. Examples: Input : 1 / \ 2 3 / \ / \ 4 5 6 7 Output : 11 / \ 9 13 / \ / \ 2 3 4 3 For 1: Inorder predecessor = 5 Inorder successor = 6 Sum = 11 For 4: Inorder predecessor = 0 (as inorder predecessor is not present) Inorder successor = 2 Sum = 2 For 7: Inorder predecessor = 3 Inorder successor = 0 (as inorder successor is not present) Sum = 3 Approach: Create an array arr. Store 0 at index 0. Now, store the inorder traversal of tree in the array arr. Then, store 0 at last index. 0’s are stored as inorder predecessor of leftmost leaf and inorder successor of rightmost leaf is not present. Now, perform inorder traversal and while traversing node replace node’s value with arr[i-1] + arr[i+1] and then increment i. In the beginning initialize i = 1. For an element arr[i], the values arr[i-1] and arr[i+1] are its inorder predecessor and inorder successor respectively. C++ Java Python3 C# Javascript // C++ implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successor#include <bits/stdc++.h> using namespace std; // node of a binary treestruct Node { int data; struct Node* left, *right;}; // function to get a new node of a binary treestruct Node* getNode(int data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} // function to store the inorder traversal// of the binary tree in 'arr'void storeInorderTraversal(struct Node* root, vector<int>& arr){ // if root is NULL if (!root) return; // first recur on left child storeInorderTraversal(root->left, arr); // then store the root's data in 'arr' arr.push_back(root->data); // now recur on right child storeInorderTraversal(root->right, arr);} // function to replace each node with the sum of its// inorder predecessor and successorvoid replaceNodeWithSum(struct Node* root, vector<int> arr, int* i){ // if root is NULL if (!root) return; // first recur on left child replaceNodeWithSum(root->left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root->data = arr[*i - 1] + arr[*i + 1]; // move 'i' to point to the next 'arr' element ++*i; // now recur on right child replaceNodeWithSum(root->right, arr, i);} // Utility function to replace each node in binary// tree with the sum of its inorder predecessor// and successorvoid replaceNodeWithSumUtil(struct Node* root){ // if tree is empty if (!root) return; vector<int> arr; // store the value of inorder predecessor // for the leftmost leaf arr.push_back(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.push_back(0); // replace each node with the required sum int i = 1; replaceNodeWithSum(root, arr, &i);} // function to print the preorder traversal// of a binary treevoid preorderTraversal(struct Node* root){ // if root is NULL if (!root) return; // first print the data of node cout << root->data << " "; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right);} // Driver program to test aboveint main(){ // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << "Preorder Traversal before tree modification:n"; preorderTraversal(root); replaceNodeWithSumUtil(root); cout << "\nPreorder Traversal after tree modification:n"; preorderTraversal(root); return 0;} // Java implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successorimport java.util.*;class Solution{ // node of a binary treestatic class Node { int data; Node left, right;} //INT classstatic class INT{ int data;} // function to get a new node of a binary treestatic Node getNode(int data){ // allocate node Node new_node =new Node(); // put in the data; new_node.data = data; new_node.left = new_node.right = null; return new_node;} // function to store the inorder traversal// of the binary tree in 'arr'static void storeInorderTraversal( Node root, Vector<Integer> arr){ // if root is null if (root==null) return; // first recur on left child storeInorderTraversal(root.left, arr); // then store the root's data in 'arr' arr.add(root.data); // now recur on right child storeInorderTraversal(root.right, arr);} // function to replace each node with the sum of its// inorder predecessor and successorstatic void replaceNodeWithSum( Node root, Vector<Integer> arr, INT i){ // if root is null if (root==null) return; // first recur on left child replaceNodeWithSum(root.left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root.data = arr.get(i.data - 1) + arr.get(i.data + 1); // move 'i' to point to the next 'arr' element i.data++; // now recur on right child replaceNodeWithSum(root.right, arr, i);} // Utility function to replace each node in binary// tree with the sum of its inorder predecessor// and successorstatic void replaceNodeWithSumUtil( Node root){ // if tree is empty if (root==null) return; Vector<Integer> arr= new Vector<Integer>(); // store the value of inorder predecessor // for the leftmost leaf arr.add(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.add(0); // replace each node with the required sum INT i = new INT(); i.data=1; replaceNodeWithSum(root, arr, i);} // function to print the preorder traversal// of a binary treestatic void preorderTraversal( Node root){ // if root is null if (root==null) return; // first print the data of node System.out.print( root.data + " "); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right);} // Driver program to test abovepublic static void main(String args[]){ // binary tree formation Node root = getNode(1); // 1 root.left = getNode(2); // / \ root.right = getNode(3); // 2 3 root.left.left = getNode(4); // / \ / \ root.left.right = getNode(5); // 4 5 6 7 root.right.left = getNode(6); root.right.right = getNode(7); System.out.println( "Preorder Traversal before tree modification:"); preorderTraversal(root); replaceNodeWithSumUtil(root); System.out.println("\nPreorder Traversal after tree modification:"); preorderTraversal(root); }}//contributed by Arnab Kundu # Python3 implementation to replace each# node in binary tree with the sum of its# inorder predecessor and successor # class to get a new node of a# binary treeclass getNode: def __init__(self, data): # put in the data self.data = data self.left = self.right = None # function to store the inorder traversal# of the binary tree in 'arr'def storeInorderTraversal(root, arr): # if root is None if (not root): return # first recur on left child storeInorderTraversal(root.left, arr) # then store the root's data in 'arr' arr.append(root.data) # now recur on right child storeInorderTraversal(root.right, arr) # function to replace each node with the# sum of its inorder predecessor and successordef replaceNodeWithSum(root, arr, i): # if root is None if (not root): return # first recur on left child replaceNodeWithSum(root.left, arr, i) # replace node's data with the sum of its # inorder predecessor and successor root.data = arr[i[0] - 1] + arr[i[0] + 1] # move 'i' to point to the next 'arr' element i[0] += 1 # now recur on right child replaceNodeWithSum(root.right, arr, i) # Utility function to replace each node in# binary tree with the sum of its inorder # predecessor and successordef replaceNodeWithSumUtil(root): # if tree is empty if (not root): return arr = [] # store the value of inorder predecessor # for the leftmost leaf arr.append(0) # store the inorder traversal of the # tree in 'arr' storeInorderTraversal(root, arr) # store the value of inorder successor # for the rightmost leaf arr.append(0) # replace each node with the required sum i = [1] replaceNodeWithSum(root, arr, i) # function to print the preorder traversal# of a binary treedef preorderTraversal(root): # if root is None if (not root): return # first print the data of node print(root.data, end = " ") # then recur on left subtree preorderTraversal(root.left) # now recur on right subtree preorderTraversal(root.right) # Driver Codeif __name__ == '__main__': # binary tree formation root = getNode(1) # 1 root.left = getNode(2) # / \ root.right = getNode(3) # 2 3 root.left.left = getNode(4) # / \ / \ root.left.right = getNode(5) # 4 5 6 7 root.right.left = getNode(6) root.right.right = getNode(7) print("Preorder Traversal before", "tree modification:") preorderTraversal(root) replaceNodeWithSumUtil(root) print() print("Preorder Traversal after", "tree modification:") preorderTraversal(root) # This code is contributed by PranchalK // C# implementation to replace each// node in binary tree with the sum// of its inorder predecessor and successorusing System;using System.Collections.Generic; class GFG{ // node of a binary treepublic class Node{ public int data; public Node left, right;} // INT classpublic class INT{ public int data;} // function to get a new node// of a binary treepublic static Node getNode(int data){ // allocate node Node new_node = new Node(); // put in the data; new_node.data = data; new_node.left = new_node.right = null; return new_node;} // function to store the inorder traversal// of the binary tree in 'arr'public static void storeInorderTraversal(Node root, List<int> arr){ // if root is null if (root == null) { return; } // first recur on left child storeInorderTraversal(root.left, arr); // then store the root's data in 'arr' arr.Add(root.data); // now recur on right child storeInorderTraversal(root.right, arr);} // function to replace each node with// the sum of its inorder predecessor// and successorpublic static void replaceNodeWithSum(Node root, List<int> arr, INT i){ // if root is null if (root == null) { return; } // first recur on left child replaceNodeWithSum(root.left, arr, i); // replace node's data with the // sum of its inorder predecessor // and successor root.data = arr[i.data - 1] + arr[i.data + 1]; // move 'i' to point to the // next 'arr' element i.data++; // now recur on right child replaceNodeWithSum(root.right, arr, i);} // Utility function to replace each// node in binary tree with the sum// of its inorder predecessor and successorpublic static void replaceNodeWithSumUtil(Node root){ // if tree is empty if (root == null) { return; } List<int> arr = new List<int>(); // store the value of inorder // predecessor for the leftmost leaf arr.Add(0); // store the inorder traversal // of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.Add(0); // replace each node with // the required sum INT i = new INT(); i.data = 1; replaceNodeWithSum(root, arr, i);} // function to print the preorder// traversal of a binary treepublic static void preorderTraversal(Node root){ // if root is null if (root == null) { return; } // first print the data of node Console.Write(root.data + " "); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right);} // Driver Codepublic static void Main(string[] args){ // binary tree formation Node root = getNode(1); // 1 root.left = getNode(2); // / \ root.right = getNode(3); // 2 3 root.left.left = getNode(4); // / \ / \ root.left.right = getNode(5); // 4 5 6 7 root.right.left = getNode(6); root.right.right = getNode(7); Console.WriteLine("Preorder Traversal " + "before tree modification:"); preorderTraversal(root); replaceNodeWithSumUtil(root); Console.WriteLine("\nPreorder Traversal after " + "tree modification:"); preorderTraversal(root);}} // This code is contributed by Shrikant13 <script> // Javascript implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successorclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Function to get a new node of a// binary treefunction getNode(data){ // Allocate node let new_node = new Node(data); return new_node;} // Function to store the inorder traversal// of the binary tree in 'arr'function storeInorderTraversal(root, arr){ // If root is null if (root == null) return; // First recur on left child storeInorderTraversal(root.left, arr); // then store the root's data in 'arr' arr.push(root.data); // Now recur on right child storeInorderTraversal(root.right, arr);} // Function to replace each node with the// sum of its inorder predecessor and successorfunction replaceNodeWithSum(root, arr){ // If root is null if (root == null) return; // First recur on left child replaceNodeWithSum(root.left, arr); // Replace node's data with the sum of its // inorder predecessor and successor root.data = arr[data - 1] + arr[data + 1]; // Move 'i' to point to the next 'arr' element data++; // Now recur on right child replaceNodeWithSum(root.right, arr);} // Utility function to replace each node in binary// tree with the sum of its inorder predecessor// and successorfunction replaceNodeWithSumUtil(root){ // If tree is empty if (root == null) return; let arr = []; // Store the value of inorder predecessor // for the leftmost leaf arr.push(0); // Store the inorder traversal of // the tree in 'arr' storeInorderTraversal(root, arr); // Store the value of inorder successor // for the rightmost leaf arr.push(0); // Replace each node with the required sum data = 1; replaceNodeWithSum(root, arr);} // Function to print the preorder traversal// of a binary treefunction preorderTraversal(root){ // If root is null if (root == null) return; // First print the data of node document.write(root.data + " "); // Then recur on left subtree preorderTraversal(root.left); // Now recur on right subtree preorderTraversal(root.right);} // Driver code // Binary tree formationlet root = getNode(1); // 1 root.left = getNode(2); // / \ root.right = getNode(3); // 2 3 root.left.left = getNode(4); // / \ / \ root.left.right = getNode(5); // 4 5 6 7 root.right.left = getNode(6);root.right.right = getNode(7); document.write("Preorder Traversal before " + "tree modification:" + "</br>");preorderTraversal(root); replaceNodeWithSumUtil(root); document.write("</br>" + "Preorder Traversal after " + "tree modification:" + "</br>");preorderTraversal(root); // This code is contributed by divyeshrabadiya07 </script> Preorder Traversal before tree modification:n1 2 4 5 3 6 7 Preorder Traversal after tree modification:n11 9 2 3 13 4 3 Output: Preorder Traversal before tree modification: 1 2 4 5 3 6 7 Preorder Traversal after tree modification: 11 9 2 3 13 4 3 Time Complexity: O(n) Auxiliary Space: O(n) This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Use inorder traversal and keep previous node and value of previous node’s previous. Update previous node with current node + previous’s previous value C++ // C++ implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successor#include <bits/stdc++.h> using namespace std; // node of a binary treestruct Node { int data; struct Node* left, *right;}; // function to get a new node of a binary treestruct Node* getNode(int data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} // function to print the preorder traversal// of a binary treevoid preorderTraversal(struct Node* root){ // if root is NULL if (!root) return; // first print the data of node cout << root->data << " "; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right);} void inOrderTraverse(struct Node* root, struct Node* &prev, int &prevVal) { if(root == NULL) return; inOrderTraverse(root->left, prev, prevVal); if(prev == NULL) { prev = root; prevVal = 0; } else { int temp = prev->data; prev->data = prevVal + root->data; prev = root; prevVal = temp; } inOrderTraverse(root->right, prev, prevVal); }// Driver program to test aboveint main(){ // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \ / \ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << "Preorder Traversal before tree modification:\n"; preorderTraversal(root); struct Node* prev = NULL; int prevVal = -1; inOrderTraverse(root, prev, prevVal); // update righmost node. prev->data = prevVal; cout << "\nPreorder Traversal after tree modification:\n"; preorderTraversal(root); return 0;} Preorder Traversal before tree modification: 1 2 4 5 3 6 7 Preorder Traversal after tree modification: 11 9 2 3 13 4 3 Time Complexity: O(n) Auxiliary Space: O(n) due to recursive stack space andrew1234 shrikanth13 PranchalKatiyar nidhi_biet divyeshrabadiya07 saurabh1990aror surinderdawra388 rupendra Arrays Tree Arrays Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) AVL Tree | Set 1 (Insertion) Level Order Binary Tree Traversal Binary Tree | Set 3 (Types of Binary Tree)
[ { "code": null, "e": 37093, "s": 37065, "text": "\n25 Apr, 2022" }, { "code": null, "e": 37251, "s": 37093, "text": "Given a binary tree containing n nodes. The problem is to replace each node in the binary tree with the sum of its inorder predecessor and inorder successor." }, { "code": null, "e": 37262, "s": 37251, "text": "Examples: " }, { "code": null, "e": 37770, "s": 37262, "text": "Input : 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n\nOutput : 11\n / \\\n 9 13\n / \\ / \\\n 2 3 4 3\n \nFor 1:\nInorder predecessor = 5\nInorder successor = 6\nSum = 11\n\nFor 4:\nInorder predecessor = 0\n(as inorder predecessor is not present)\nInorder successor = 2\nSum = 2\n\nFor 7:\nInorder predecessor = 3\nInorder successor = 0\n(as inorder successor is not present)\nSum = 3" }, { "code": null, "e": 38300, "s": 37770, "text": "Approach: Create an array arr. Store 0 at index 0. Now, store the inorder traversal of tree in the array arr. Then, store 0 at last index. 0’s are stored as inorder predecessor of leftmost leaf and inorder successor of rightmost leaf is not present. Now, perform inorder traversal and while traversing node replace node’s value with arr[i-1] + arr[i+1] and then increment i. In the beginning initialize i = 1. For an element arr[i], the values arr[i-1] and arr[i+1] are its inorder predecessor and inorder successor respectively." }, { "code": null, "e": 38304, "s": 38300, "text": "C++" }, { "code": null, "e": 38309, "s": 38304, "text": "Java" }, { "code": null, "e": 38317, "s": 38309, "text": "Python3" }, { "code": null, "e": 38320, "s": 38317, "text": "C#" }, { "code": null, "e": 38331, "s": 38320, "text": "Javascript" }, { "code": "// C++ implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successor#include <bits/stdc++.h> using namespace std; // node of a binary treestruct Node { int data; struct Node* left, *right;}; // function to get a new node of a binary treestruct Node* getNode(int data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} // function to store the inorder traversal// of the binary tree in 'arr'void storeInorderTraversal(struct Node* root, vector<int>& arr){ // if root is NULL if (!root) return; // first recur on left child storeInorderTraversal(root->left, arr); // then store the root's data in 'arr' arr.push_back(root->data); // now recur on right child storeInorderTraversal(root->right, arr);} // function to replace each node with the sum of its// inorder predecessor and successorvoid replaceNodeWithSum(struct Node* root, vector<int> arr, int* i){ // if root is NULL if (!root) return; // first recur on left child replaceNodeWithSum(root->left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root->data = arr[*i - 1] + arr[*i + 1]; // move 'i' to point to the next 'arr' element ++*i; // now recur on right child replaceNodeWithSum(root->right, arr, i);} // Utility function to replace each node in binary// tree with the sum of its inorder predecessor// and successorvoid replaceNodeWithSumUtil(struct Node* root){ // if tree is empty if (!root) return; vector<int> arr; // store the value of inorder predecessor // for the leftmost leaf arr.push_back(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.push_back(0); // replace each node with the required sum int i = 1; replaceNodeWithSum(root, arr, &i);} // function to print the preorder traversal// of a binary treevoid preorderTraversal(struct Node* root){ // if root is NULL if (!root) return; // first print the data of node cout << root->data << \" \"; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right);} // Driver program to test aboveint main(){ // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \\ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \\ / \\ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << \"Preorder Traversal before tree modification:n\"; preorderTraversal(root); replaceNodeWithSumUtil(root); cout << \"\\nPreorder Traversal after tree modification:n\"; preorderTraversal(root); return 0;}", "e": 41521, "s": 38331, "text": null }, { "code": "// Java implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successorimport java.util.*;class Solution{ // node of a binary treestatic class Node { int data; Node left, right;} //INT classstatic class INT{ int data;} // function to get a new node of a binary treestatic Node getNode(int data){ // allocate node Node new_node =new Node(); // put in the data; new_node.data = data; new_node.left = new_node.right = null; return new_node;} // function to store the inorder traversal// of the binary tree in 'arr'static void storeInorderTraversal( Node root, Vector<Integer> arr){ // if root is null if (root==null) return; // first recur on left child storeInorderTraversal(root.left, arr); // then store the root's data in 'arr' arr.add(root.data); // now recur on right child storeInorderTraversal(root.right, arr);} // function to replace each node with the sum of its// inorder predecessor and successorstatic void replaceNodeWithSum( Node root, Vector<Integer> arr, INT i){ // if root is null if (root==null) return; // first recur on left child replaceNodeWithSum(root.left, arr, i); // replace node's data with the sum of its // inorder predecessor and successor root.data = arr.get(i.data - 1) + arr.get(i.data + 1); // move 'i' to point to the next 'arr' element i.data++; // now recur on right child replaceNodeWithSum(root.right, arr, i);} // Utility function to replace each node in binary// tree with the sum of its inorder predecessor// and successorstatic void replaceNodeWithSumUtil( Node root){ // if tree is empty if (root==null) return; Vector<Integer> arr= new Vector<Integer>(); // store the value of inorder predecessor // for the leftmost leaf arr.add(0); // store the inorder traversal of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.add(0); // replace each node with the required sum INT i = new INT(); i.data=1; replaceNodeWithSum(root, arr, i);} // function to print the preorder traversal// of a binary treestatic void preorderTraversal( Node root){ // if root is null if (root==null) return; // first print the data of node System.out.print( root.data + \" \"); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right);} // Driver program to test abovepublic static void main(String args[]){ // binary tree formation Node root = getNode(1); // 1 root.left = getNode(2); // / \\ root.right = getNode(3); // 2 3 root.left.left = getNode(4); // / \\ / \\ root.left.right = getNode(5); // 4 5 6 7 root.right.left = getNode(6); root.right.right = getNode(7); System.out.println( \"Preorder Traversal before tree modification:\"); preorderTraversal(root); replaceNodeWithSumUtil(root); System.out.println(\"\\nPreorder Traversal after tree modification:\"); preorderTraversal(root); }}//contributed by Arnab Kundu", "e": 44851, "s": 41521, "text": null }, { "code": "# Python3 implementation to replace each# node in binary tree with the sum of its# inorder predecessor and successor # class to get a new node of a# binary treeclass getNode: def __init__(self, data): # put in the data self.data = data self.left = self.right = None # function to store the inorder traversal# of the binary tree in 'arr'def storeInorderTraversal(root, arr): # if root is None if (not root): return # first recur on left child storeInorderTraversal(root.left, arr) # then store the root's data in 'arr' arr.append(root.data) # now recur on right child storeInorderTraversal(root.right, arr) # function to replace each node with the# sum of its inorder predecessor and successordef replaceNodeWithSum(root, arr, i): # if root is None if (not root): return # first recur on left child replaceNodeWithSum(root.left, arr, i) # replace node's data with the sum of its # inorder predecessor and successor root.data = arr[i[0] - 1] + arr[i[0] + 1] # move 'i' to point to the next 'arr' element i[0] += 1 # now recur on right child replaceNodeWithSum(root.right, arr, i) # Utility function to replace each node in# binary tree with the sum of its inorder # predecessor and successordef replaceNodeWithSumUtil(root): # if tree is empty if (not root): return arr = [] # store the value of inorder predecessor # for the leftmost leaf arr.append(0) # store the inorder traversal of the # tree in 'arr' storeInorderTraversal(root, arr) # store the value of inorder successor # for the rightmost leaf arr.append(0) # replace each node with the required sum i = [1] replaceNodeWithSum(root, arr, i) # function to print the preorder traversal# of a binary treedef preorderTraversal(root): # if root is None if (not root): return # first print the data of node print(root.data, end = \" \") # then recur on left subtree preorderTraversal(root.left) # now recur on right subtree preorderTraversal(root.right) # Driver Codeif __name__ == '__main__': # binary tree formation root = getNode(1) # 1 root.left = getNode(2) # / \\ root.right = getNode(3) # 2 3 root.left.left = getNode(4) # / \\ / \\ root.left.right = getNode(5) # 4 5 6 7 root.right.left = getNode(6) root.right.right = getNode(7) print(\"Preorder Traversal before\", \"tree modification:\") preorderTraversal(root) replaceNodeWithSumUtil(root) print() print(\"Preorder Traversal after\", \"tree modification:\") preorderTraversal(root) # This code is contributed by PranchalK", "e": 47620, "s": 44851, "text": null }, { "code": "// C# implementation to replace each// node in binary tree with the sum// of its inorder predecessor and successorusing System;using System.Collections.Generic; class GFG{ // node of a binary treepublic class Node{ public int data; public Node left, right;} // INT classpublic class INT{ public int data;} // function to get a new node// of a binary treepublic static Node getNode(int data){ // allocate node Node new_node = new Node(); // put in the data; new_node.data = data; new_node.left = new_node.right = null; return new_node;} // function to store the inorder traversal// of the binary tree in 'arr'public static void storeInorderTraversal(Node root, List<int> arr){ // if root is null if (root == null) { return; } // first recur on left child storeInorderTraversal(root.left, arr); // then store the root's data in 'arr' arr.Add(root.data); // now recur on right child storeInorderTraversal(root.right, arr);} // function to replace each node with// the sum of its inorder predecessor// and successorpublic static void replaceNodeWithSum(Node root, List<int> arr, INT i){ // if root is null if (root == null) { return; } // first recur on left child replaceNodeWithSum(root.left, arr, i); // replace node's data with the // sum of its inorder predecessor // and successor root.data = arr[i.data - 1] + arr[i.data + 1]; // move 'i' to point to the // next 'arr' element i.data++; // now recur on right child replaceNodeWithSum(root.right, arr, i);} // Utility function to replace each// node in binary tree with the sum// of its inorder predecessor and successorpublic static void replaceNodeWithSumUtil(Node root){ // if tree is empty if (root == null) { return; } List<int> arr = new List<int>(); // store the value of inorder // predecessor for the leftmost leaf arr.Add(0); // store the inorder traversal // of the tree in 'arr' storeInorderTraversal(root, arr); // store the value of inorder successor // for the rightmost leaf arr.Add(0); // replace each node with // the required sum INT i = new INT(); i.data = 1; replaceNodeWithSum(root, arr, i);} // function to print the preorder// traversal of a binary treepublic static void preorderTraversal(Node root){ // if root is null if (root == null) { return; } // first print the data of node Console.Write(root.data + \" \"); // then recur on left subtree preorderTraversal(root.left); // now recur on right subtree preorderTraversal(root.right);} // Driver Codepublic static void Main(string[] args){ // binary tree formation Node root = getNode(1); // 1 root.left = getNode(2); // / \\ root.right = getNode(3); // 2 3 root.left.left = getNode(4); // / \\ / \\ root.left.right = getNode(5); // 4 5 6 7 root.right.left = getNode(6); root.right.right = getNode(7); Console.WriteLine(\"Preorder Traversal \" + \"before tree modification:\"); preorderTraversal(root); replaceNodeWithSumUtil(root); Console.WriteLine(\"\\nPreorder Traversal after \" + \"tree modification:\"); preorderTraversal(root);}} // This code is contributed by Shrikant13", "e": 51035, "s": 47620, "text": null }, { "code": "<script> // Javascript implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successorclass Node{ constructor(data) { this.left = null; this.right = null; this.data = data; }} // Function to get a new node of a// binary treefunction getNode(data){ // Allocate node let new_node = new Node(data); return new_node;} // Function to store the inorder traversal// of the binary tree in 'arr'function storeInorderTraversal(root, arr){ // If root is null if (root == null) return; // First recur on left child storeInorderTraversal(root.left, arr); // then store the root's data in 'arr' arr.push(root.data); // Now recur on right child storeInorderTraversal(root.right, arr);} // Function to replace each node with the// sum of its inorder predecessor and successorfunction replaceNodeWithSum(root, arr){ // If root is null if (root == null) return; // First recur on left child replaceNodeWithSum(root.left, arr); // Replace node's data with the sum of its // inorder predecessor and successor root.data = arr[data - 1] + arr[data + 1]; // Move 'i' to point to the next 'arr' element data++; // Now recur on right child replaceNodeWithSum(root.right, arr);} // Utility function to replace each node in binary// tree with the sum of its inorder predecessor// and successorfunction replaceNodeWithSumUtil(root){ // If tree is empty if (root == null) return; let arr = []; // Store the value of inorder predecessor // for the leftmost leaf arr.push(0); // Store the inorder traversal of // the tree in 'arr' storeInorderTraversal(root, arr); // Store the value of inorder successor // for the rightmost leaf arr.push(0); // Replace each node with the required sum data = 1; replaceNodeWithSum(root, arr);} // Function to print the preorder traversal// of a binary treefunction preorderTraversal(root){ // If root is null if (root == null) return; // First print the data of node document.write(root.data + \" \"); // Then recur on left subtree preorderTraversal(root.left); // Now recur on right subtree preorderTraversal(root.right);} // Driver code // Binary tree formationlet root = getNode(1); // 1 root.left = getNode(2); // / \\ root.right = getNode(3); // 2 3 root.left.left = getNode(4); // / \\ / \\ root.left.right = getNode(5); // 4 5 6 7 root.right.left = getNode(6);root.right.right = getNode(7); document.write(\"Preorder Traversal before \" + \"tree modification:\" + \"</br>\");preorderTraversal(root); replaceNodeWithSumUtil(root); document.write(\"</br>\" + \"Preorder Traversal after \" + \"tree modification:\" + \"</br>\");preorderTraversal(root); // This code is contributed by divyeshrabadiya07 </script>", "e": 54020, "s": 51035, "text": null }, { "code": null, "e": 54141, "s": 54020, "text": "Preorder Traversal before tree modification:n1 2 4 5 3 6 7 \nPreorder Traversal after tree modification:n11 9 2 3 13 4 3 " }, { "code": null, "e": 54150, "s": 54141, "text": "Output: " }, { "code": null, "e": 54269, "s": 54150, "text": "Preorder Traversal before tree modification:\n1 2 4 5 3 6 7\nPreorder Traversal after tree modification:\n11 9 2 3 13 4 3" }, { "code": null, "e": 54313, "s": 54269, "text": "Time Complexity: O(n) Auxiliary Space: O(n)" }, { "code": null, "e": 54734, "s": 54313, "text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 54820, "s": 54734, "text": "Use inorder traversal and keep previous node and value of previous node’s previous. " }, { "code": null, "e": 54889, "s": 54820, "text": "Update previous node with current node + previous’s previous value " }, { "code": null, "e": 54893, "s": 54889, "text": "C++" }, { "code": "// C++ implementation to replace each node// in binary tree with the sum of its inorder// predecessor and successor#include <bits/stdc++.h> using namespace std; // node of a binary treestruct Node { int data; struct Node* left, *right;}; // function to get a new node of a binary treestruct Node* getNode(int data){ // allocate node struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); // put in the data; new_node->data = data; new_node->left = new_node->right = NULL; return new_node;} // function to print the preorder traversal// of a binary treevoid preorderTraversal(struct Node* root){ // if root is NULL if (!root) return; // first print the data of node cout << root->data << \" \"; // then recur on left subtree preorderTraversal(root->left); // now recur on right subtree preorderTraversal(root->right);} void inOrderTraverse(struct Node* root, struct Node* &prev, int &prevVal) { if(root == NULL) return; inOrderTraverse(root->left, prev, prevVal); if(prev == NULL) { prev = root; prevVal = 0; } else { int temp = prev->data; prev->data = prevVal + root->data; prev = root; prevVal = temp; } inOrderTraverse(root->right, prev, prevVal); }// Driver program to test aboveint main(){ // binary tree formation struct Node* root = getNode(1); /* 1 */ root->left = getNode(2); /* / \\ */ root->right = getNode(3); /* 2 3 */ root->left->left = getNode(4); /* / \\ / \\ */ root->left->right = getNode(5); /* 4 5 6 7 */ root->right->left = getNode(6); root->right->right = getNode(7); cout << \"Preorder Traversal before tree modification:\\n\"; preorderTraversal(root); struct Node* prev = NULL; int prevVal = -1; inOrderTraverse(root, prev, prevVal); // update righmost node. prev->data = prevVal; cout << \"\\nPreorder Traversal after tree modification:\\n\"; preorderTraversal(root); return 0;}", "e": 56990, "s": 54893, "text": null }, { "code": null, "e": 57111, "s": 56990, "text": "Preorder Traversal before tree modification:\n1 2 4 5 3 6 7 \nPreorder Traversal after tree modification:\n11 9 2 3 13 4 3 " }, { "code": null, "e": 57186, "s": 57111, "text": "Time Complexity: O(n) Auxiliary Space: O(n) due to recursive stack space " }, { "code": null, "e": 57197, "s": 57186, "text": "andrew1234" }, { "code": null, "e": 57209, "s": 57197, "text": "shrikanth13" }, { "code": null, "e": 57225, "s": 57209, "text": "PranchalKatiyar" }, { "code": null, "e": 57236, "s": 57225, "text": "nidhi_biet" }, { "code": null, "e": 57254, "s": 57236, "text": "divyeshrabadiya07" }, { "code": null, "e": 57270, "s": 57254, "text": "saurabh1990aror" }, { "code": null, "e": 57287, "s": 57270, "text": "surinderdawra388" }, { "code": null, "e": 57296, "s": 57287, "text": "rupendra" }, { "code": null, "e": 57303, "s": 57296, "text": "Arrays" }, { "code": null, "e": 57308, "s": 57303, "text": "Tree" }, { "code": null, "e": 57315, "s": 57308, "text": "Arrays" }, { "code": null, "e": 57320, "s": 57315, "text": "Tree" }, { "code": null, "e": 57418, "s": 57320, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 57433, "s": 57418, "text": "Arrays in Java" }, { "code": null, "e": 57449, "s": 57433, "text": "Arrays in C/C++" }, { "code": null, "e": 57517, "s": 57449, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 57563, "s": 57517, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 57590, "s": 57563, "text": "Program for array rotation" }, { "code": null, "e": 57640, "s": 57590, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 57675, "s": 57640, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 57704, "s": 57675, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 57738, "s": 57704, "text": "Level Order Binary Tree Traversal" } ]
Swap three numbers in cycle - GeeksforGeeks
28 May, 2018 Given three numbers, swap them in cyclic form. First number should get the value of third, second should get the value of first and third should get value of second. Examples: Input : a = 2, b = 4, c = 7 Output : a = 7, b = 2, c = 4 Input : a = 10, b = 20, c = 30 Output : a = 30, b = 10, c = 20 Prerequisite : Pointers, Call by Reference, The idea is extend simple two variable swapping. // Before overwriting b, store its // value in temp. temp = b; // Now do required swapping starting // with b. b = a; a = c; c = temp; C++ C# // C program to perform Cyclic Swapping// using Call by Reference#include <stdio.h> void cyclicSwap(int* a, int* b, int* c){ // Before overwriting b, store its // value in temp. int temp = *b; // Now do required swapping starting // with b. *b = *a; *a = *c; *c = temp;} int main(){ int a = 2, b = 4, c = 7; printf("Value before swapping:\n"); printf("a = %d \nb = %d \nc = %d\n", a, b, c); cyclicSwap(&a, &b, &c); printf("Value after swapping:\n"); printf("a = %d \nb = %d \nc = %d", a, b, c); return 0;} // C# program to perform Cyclic Swapping// using Call by Referenceusing System;class GFG { static void cyclicSwap(ref int a, ref int b, ref int c) { // Before overwriting b, store // its value in temp. int temp = b; // Now do required swapping // starting with b. b = a; a = c; c = temp; } // Driver code public static void Main() { int a = 2, b = 4, c = 7; Console.Write("Value before swapping:\n"); Console.Write("a = " + a + "\n"+ "b = " + b + "\n" + "c = " + c + "\n"); cyclicSwap(ref a, ref b, ref c); Console.Write("Value after swapping:\n"); Console.Write("a = " + a + "\n"+ "b = " + b + "\n" + "c = " + c + "\n"); } } // This code is contributed by Sam007. Value before swapping: a = 2 b = 4 c = 7 Value after swapping: a = 7 b = 2 c = 4 Sam007 School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Data Types Inline Functions in C++ Pure Virtual Functions and Abstract Classes in C++ Difference between Abstract Class and Interface in Java Destructors in C++ Python Exception Handling Exception Handling in C++ Input and Output
[ { "code": null, "e": 25439, "s": 25411, "text": "\n28 May, 2018" }, { "code": null, "e": 25605, "s": 25439, "text": "Given three numbers, swap them in cyclic form. First number should get the value of third, second should get the value of first and third should get value of second." }, { "code": null, "e": 25615, "s": 25605, "text": "Examples:" }, { "code": null, "e": 25737, "s": 25615, "text": "Input : a = 2, b = 4, c = 7\nOutput : a = 7, b = 2, c = 4\n\nInput : a = 10, b = 20, c = 30\nOutput : a = 30, b = 10, c = 20\n" }, { "code": null, "e": 25781, "s": 25737, "text": "Prerequisite : Pointers, Call by Reference," }, { "code": null, "e": 25830, "s": 25781, "text": "The idea is extend simple two variable swapping." }, { "code": null, "e": 26000, "s": 25830, "text": " // Before overwriting b, store its \n // value in temp.\n temp = b;\n\n // Now do required swapping starting\n // with b.\n b = a;\n a = c;\n c = temp;\n" }, { "code": null, "e": 26004, "s": 26000, "text": "C++" }, { "code": null, "e": 26007, "s": 26004, "text": "C#" }, { "code": "// C program to perform Cyclic Swapping// using Call by Reference#include <stdio.h> void cyclicSwap(int* a, int* b, int* c){ // Before overwriting b, store its // value in temp. int temp = *b; // Now do required swapping starting // with b. *b = *a; *a = *c; *c = temp;} int main(){ int a = 2, b = 4, c = 7; printf(\"Value before swapping:\\n\"); printf(\"a = %d \\nb = %d \\nc = %d\\n\", a, b, c); cyclicSwap(&a, &b, &c); printf(\"Value after swapping:\\n\"); printf(\"a = %d \\nb = %d \\nc = %d\", a, b, c); return 0;}", "e": 26571, "s": 26007, "text": null }, { "code": "// C# program to perform Cyclic Swapping// using Call by Referenceusing System;class GFG { static void cyclicSwap(ref int a, ref int b, ref int c) { // Before overwriting b, store // its value in temp. int temp = b; // Now do required swapping // starting with b. b = a; a = c; c = temp; } // Driver code public static void Main() { int a = 2, b = 4, c = 7; Console.Write(\"Value before swapping:\\n\"); Console.Write(\"a = \" + a + \"\\n\"+ \"b = \" + b + \"\\n\" + \"c = \" + c + \"\\n\"); cyclicSwap(ref a, ref b, ref c); Console.Write(\"Value after swapping:\\n\"); Console.Write(\"a = \" + a + \"\\n\"+ \"b = \" + b + \"\\n\" + \"c = \" + c + \"\\n\"); } } // This code is contributed by Sam007.", "e": 27461, "s": 26571, "text": null }, { "code": null, "e": 27547, "s": 27461, "text": "Value before swapping:\na = 2 \nb = 4 \nc = 7\nValue after swapping:\na = 7 \nb = 2 \nc = 4\n" }, { "code": null, "e": 27554, "s": 27547, "text": "Sam007" }, { "code": null, "e": 27573, "s": 27554, "text": "School Programming" }, { "code": null, "e": 27671, "s": 27573, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27692, "s": 27671, "text": "Constructors in Java" }, { "code": null, "e": 27711, "s": 27692, "text": "Exceptions in Java" }, { "code": null, "e": 27722, "s": 27711, "text": "Data Types" }, { "code": null, "e": 27746, "s": 27722, "text": "Inline Functions in C++" }, { "code": null, "e": 27797, "s": 27746, "text": "Pure Virtual Functions and Abstract Classes in C++" }, { "code": null, "e": 27853, "s": 27797, "text": "Difference between Abstract Class and Interface in Java" }, { "code": null, "e": 27872, "s": 27853, "text": "Destructors in C++" }, { "code": null, "e": 27898, "s": 27872, "text": "Python Exception Handling" }, { "code": null, "e": 27924, "s": 27898, "text": "Exception Handling in C++" } ]
Minimum increment or decrement required to sort the array | Top-down Approach - GeeksforGeeks
29 Oct, 2021 Given an array arr[] of N integers, the task is to sort the array in increasing order by performing a minimum number of operations. In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.Examples: Input: arr[] = {5, 4, 3, 2, 1} Output: 6 Explanation: The sorted array of arr[] is {3, 3, 3, 3, 3} Therefore the minimum increments/decrement are: At index 0, 5 – 3 = 2 (decrement 2) At index 1, 4 – 3 = 1 (decrement 1) At index 3, 2 + 1 = 3 (increment 1) At index 4, 1 + 2 = 3 (increment 2) The total increment/decrement is 2 + 1 + 1 + 2 = 6.Input: arr[] = {1, 2, 3, 4} Output: 0 Explanation: The array is already sorted. Bottom-up Approach: This problem can be solved using Dynamic Programming. A Bottom-up Approach to this problem statement is discussed in this article. Top-Down Approach: Here we will use Top-down Dynamic Programming to solve this problem.Let 2D array (say dp[i][j]) used to store the upto index i where last element is at index j. Below are the steps: To make the array element in sorted by using the given operations, we know that an element cannot become greater than the maximum value of the array and less than the minimum value of the array(say m) by increment or decrement.Therefore, Fix an element(say X) at ith position, then (i-1)th position value(say Y) can be in the range [m, X].Keep placing the smaller element less than or equals to arr[i] at (i-1)th position for every index i of arr[] and calculate the minimum increment or decrement by adding abs(arr[i] – Y).Therefore the recurrence relation for the above mentioned approach can be written as: To make the array element in sorted by using the given operations, we know that an element cannot become greater than the maximum value of the array and less than the minimum value of the array(say m) by increment or decrement. Therefore, Fix an element(say X) at ith position, then (i-1)th position value(say Y) can be in the range [m, X]. Keep placing the smaller element less than or equals to arr[i] at (i-1)th position for every index i of arr[] and calculate the minimum increment or decrement by adding abs(arr[i] – Y). Therefore the recurrence relation for the above mentioned approach can be written as: dp[i][j] = min(dp[i][j], abs(arr[i] – Y) + recursive_function(i-1, Y)) where m ≤ Y ≤ arr[j]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Dp array to memoized// the value recursive callint dp[1000][1000]; // Function to find the minimum increment// or decrement needed to make the array// sortedint minimumIncDec(int arr[], int N, int maxE, int minE){ // If only one element is present, // then arr[] is sorted if (N == 0) { return 0; } // If dp[N][maxE] is precalculated, // then return the result if (dp[N][maxE]) return dp[N][maxE]; int ans = INT_MAX; // Iterate from minE to maxE which // placed at previous index for (int k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation int x = minimumIncDec(arr, N - 1, k, minE); ans = min(ans,x + abs(arr[N - 1] - k)); } // Memoized the value // for dp[N][maxE] dp[N][maxE] = ans; // Return the final result return dp[N][maxE];} // Driver Codeint main(){ int arr[] = { 5, 4, 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Find the minimum and maximum // element from the arr[] int minE = *min_element(arr, arr + N); int maxE = *max_element(arr, arr + N); // Function Call cout << minimumIncDec( arr, N, maxE, minE); return 0;} // Java program of the above approachimport java.util.*; class GFG{ // Dp array to memoized// the value recursive callstatic int [][]dp = new int[1000][1000]; // Function to find the minimum increment// or decrement needed to make the array// sortedstatic int minimumIncDec(int arr[], int N, int maxE, int minE){ // If only one element is present, // then arr[] is sorted if (N == 0) { return 0; } // If dp[N][maxE] is precalculated, // then return the result if (dp[N][maxE] != 0) return dp[N][maxE]; int ans = Integer.MAX_VALUE; // Iterate from minE to maxE which // placed at previous index for(int k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation int x = minimumIncDec(arr, N - 1, k, minE); ans = Math.min(ans, x + Math.abs(arr[N - 1] - k)); } // Memoized the value // for dp[N][maxE] dp[N][maxE] = ans; // Return the final result return dp[N][maxE];} // Driver Codepublic static void main(String[] args){ int arr[] = { 5, 4, 3, 2, 1 }; int N = arr.length; // Find the minimum and maximum // element from the arr[] int minE = Arrays.stream(arr).min().getAsInt(); int maxE = Arrays.stream(arr).max().getAsInt(); // Function call System.out.print(minimumIncDec( arr, N, maxE, minE));}} // This code is contributed by amal kumar choubey # Python3 program of the above approachimport sys # Dp array to memoized# the value recursive calldp = [[ 0 for x in range(1000)] for y in range(1000)] # Function to find the minimum increment# or decrement needed to make the array# sorteddef minimumIncDec(arr, N, maxE, minE): # If only one element is present, # then arr[] is sorted if (N == 0): return 0 # If dp[N][maxE] is precalculated, # then return the result if (dp[N][maxE]): return dp[N][maxE] ans = sys.maxsize # Iterate from minE to maxE which # placed at previous index for k in range(minE, maxE + 1): # Update the answer according to # recurrence relation x = minimumIncDec(arr, N - 1, k, minE) ans = min(ans, x + abs(arr[N - 1] - k)) # Memoized the value # for dp[N][maxE] dp[N][maxE] = ans # Return the final result return dp[N][maxE] # Driver Codeif __name__ == "__main__": arr = [ 5, 4, 3, 2, 1 ] N = len(arr) # Find the minimum and maximum # element from the arr[] minE = min(arr) maxE = max(arr) # Function Call print(minimumIncDec(arr, N, maxE, minE)) # This code is contributed by chitranayal // C# program of the above approachusing System;using System.Linq; class GFG{ // Dp array to memoized// the value recursive callstatic int [,]dp = new int[1000, 1000]; // Function to find the minimum increment// or decrement needed to make the array// sortedstatic int minimumIncDec(int []arr, int N, int maxE, int minE){ // If only one element is present, // then []arr is sorted if (N == 0) { return 0; } // If dp[N,maxE] is precalculated, // then return the result if (dp[N, maxE] != 0) return dp[N, maxE]; int ans = int.MaxValue; // Iterate from minE to maxE which // placed at previous index for(int k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation int x = minimumIncDec(arr, N - 1, k, minE); ans = Math.Min(ans, x + Math.Abs(arr[N - 1] - k)); } // Memoized the value // for dp[N,maxE] dp[N, maxE] = ans; // Return the readonly result return dp[N,maxE];} // Driver Codepublic static void Main(String[] args){ int []arr = { 5, 4, 3, 2, 1 }; int N = arr.Length; // Find the minimum and maximum // element from the []arr int minE = arr.Min(); int maxE = arr.Max(); // Function call Console.Write(minimumIncDec(arr, N, maxE, minE));}} // This code is contributed by Rohit_ranjan <script> // JavaScript program of the above approach // Dp array to memoized// the value recursive calllet dp = new Array(); for(let i = 0; i < 1000; i++){ let temp = []; for(let j = 0; j < 1000; j++){ temp.push([]) } dp.push(temp)} // Function to find the minimum increment// or decrement needed to make the array// sorted function minimumIncDec(arr, N, maxE, minE){ // If only one element is present, // then arr[] is sorted if (N == 0) { return 0; } // If dp[N][maxE] is precalculated, // then return the result if (!dp[N][maxE]) return dp[N][maxE]; let ans = Number.MAX_SAFE_INTEGER; // Iterate from minE to maxE which // placed at previous index for (let k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation let x = minimumIncDec(arr, N - 1, k, minE); ans = Math.min(ans,x + Math.abs(arr[N - 1] - k)); } // Memoized the value // for dp[N][maxE] dp[N][maxE] = ans; // Return the final result return dp[N][maxE];} // Driver Code let arr = [ 5, 4, 3, 2, 1 ]; let N = arr.length; // Find the minimum and maximum // element from the arr[] let minE = arr.sort((a, b) => a - b)[0]; let maxE = arr.sort((a, b) => b - a)[0]; // Function Call document.write(minimumIncDec(arr, N, maxE, minE)); // This code is contributed by _saurabh_jaiswal </script> 6 Time Complexity: O(N*maxE) Auxiliary Space: O(N2) VikasVishwakarma1 ukasp Amal Kumar Choubey Rohit_ranjan _saurabh_jaiswal sugalialnaikkece17 Algorithms Arrays Dynamic Programming Recursion Sorting Arrays Dynamic Programming Recursion Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar How to write a Pseudo Code? Understanding Time Complexity with Simple Examples Introduction to Algorithms Arrays in Java Arrays in C/C++ Maximum and minimum of an array using minimum number of comparisons Write a program to reverse an array or string Program for array rotation
[ { "code": null, "e": 26593, "s": 26565, "text": "\n29 Oct, 2021" }, { "code": null, "e": 26877, "s": 26593, "text": "Given an array arr[] of N integers, the task is to sort the array in increasing order by performing a minimum number of operations. In a single operation, an element of the array can either be incremented or decremented by 1. Print the minimum number of operations required.Examples:" }, { "code": null, "e": 27299, "s": 26877, "text": "Input: arr[] = {5, 4, 3, 2, 1} Output: 6 Explanation: The sorted array of arr[] is {3, 3, 3, 3, 3} Therefore the minimum increments/decrement are: At index 0, 5 – 3 = 2 (decrement 2) At index 1, 4 – 3 = 1 (decrement 1) At index 3, 2 + 1 = 3 (increment 1) At index 4, 1 + 2 = 3 (increment 2) The total increment/decrement is 2 + 1 + 1 + 2 = 6.Input: arr[] = {1, 2, 3, 4} Output: 0 Explanation: The array is already sorted." }, { "code": null, "e": 27653, "s": 27299, "text": "Bottom-up Approach: This problem can be solved using Dynamic Programming. A Bottom-up Approach to this problem statement is discussed in this article. Top-Down Approach: Here we will use Top-down Dynamic Programming to solve this problem.Let 2D array (say dp[i][j]) used to store the upto index i where last element is at index j. Below are the steps: " }, { "code": null, "e": 28264, "s": 27653, "text": "To make the array element in sorted by using the given operations, we know that an element cannot become greater than the maximum value of the array and less than the minimum value of the array(say m) by increment or decrement.Therefore, Fix an element(say X) at ith position, then (i-1)th position value(say Y) can be in the range [m, X].Keep placing the smaller element less than or equals to arr[i] at (i-1)th position for every index i of arr[] and calculate the minimum increment or decrement by adding abs(arr[i] – Y).Therefore the recurrence relation for the above mentioned approach can be written as: " }, { "code": null, "e": 28492, "s": 28264, "text": "To make the array element in sorted by using the given operations, we know that an element cannot become greater than the maximum value of the array and less than the minimum value of the array(say m) by increment or decrement." }, { "code": null, "e": 28605, "s": 28492, "text": "Therefore, Fix an element(say X) at ith position, then (i-1)th position value(say Y) can be in the range [m, X]." }, { "code": null, "e": 28791, "s": 28605, "text": "Keep placing the smaller element less than or equals to arr[i] at (i-1)th position for every index i of arr[] and calculate the minimum increment or decrement by adding abs(arr[i] – Y)." }, { "code": null, "e": 28878, "s": 28791, "text": "Therefore the recurrence relation for the above mentioned approach can be written as: " }, { "code": null, "e": 28974, "s": 28881, "text": "dp[i][j] = min(dp[i][j], abs(arr[i] – Y) + recursive_function(i-1, Y)) where m ≤ Y ≤ arr[j]." }, { "code": null, "e": 29028, "s": 28976, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 29032, "s": 29028, "text": "C++" }, { "code": null, "e": 29037, "s": 29032, "text": "Java" }, { "code": null, "e": 29045, "s": 29037, "text": "Python3" }, { "code": null, "e": 29048, "s": 29045, "text": "C#" }, { "code": null, "e": 29059, "s": 29048, "text": "Javascript" }, { "code": "// C++ program of the above approach #include <bits/stdc++.h>using namespace std; // Dp array to memoized// the value recursive callint dp[1000][1000]; // Function to find the minimum increment// or decrement needed to make the array// sortedint minimumIncDec(int arr[], int N, int maxE, int minE){ // If only one element is present, // then arr[] is sorted if (N == 0) { return 0; } // If dp[N][maxE] is precalculated, // then return the result if (dp[N][maxE]) return dp[N][maxE]; int ans = INT_MAX; // Iterate from minE to maxE which // placed at previous index for (int k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation int x = minimumIncDec(arr, N - 1, k, minE); ans = min(ans,x + abs(arr[N - 1] - k)); } // Memoized the value // for dp[N][maxE] dp[N][maxE] = ans; // Return the final result return dp[N][maxE];} // Driver Codeint main(){ int arr[] = { 5, 4, 3, 2, 1 }; int N = sizeof(arr) / sizeof(arr[0]); // Find the minimum and maximum // element from the arr[] int minE = *min_element(arr, arr + N); int maxE = *max_element(arr, arr + N); // Function Call cout << minimumIncDec( arr, N, maxE, minE); return 0;}", "e": 30367, "s": 29059, "text": null }, { "code": "// Java program of the above approachimport java.util.*; class GFG{ // Dp array to memoized// the value recursive callstatic int [][]dp = new int[1000][1000]; // Function to find the minimum increment// or decrement needed to make the array// sortedstatic int minimumIncDec(int arr[], int N, int maxE, int minE){ // If only one element is present, // then arr[] is sorted if (N == 0) { return 0; } // If dp[N][maxE] is precalculated, // then return the result if (dp[N][maxE] != 0) return dp[N][maxE]; int ans = Integer.MAX_VALUE; // Iterate from minE to maxE which // placed at previous index for(int k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation int x = minimumIncDec(arr, N - 1, k, minE); ans = Math.min(ans, x + Math.abs(arr[N - 1] - k)); } // Memoized the value // for dp[N][maxE] dp[N][maxE] = ans; // Return the final result return dp[N][maxE];} // Driver Codepublic static void main(String[] args){ int arr[] = { 5, 4, 3, 2, 1 }; int N = arr.length; // Find the minimum and maximum // element from the arr[] int minE = Arrays.stream(arr).min().getAsInt(); int maxE = Arrays.stream(arr).max().getAsInt(); // Function call System.out.print(minimumIncDec( arr, N, maxE, minE));}} // This code is contributed by amal kumar choubey", "e": 31834, "s": 30367, "text": null }, { "code": "# Python3 program of the above approachimport sys # Dp array to memoized# the value recursive calldp = [[ 0 for x in range(1000)] for y in range(1000)] # Function to find the minimum increment# or decrement needed to make the array# sorteddef minimumIncDec(arr, N, maxE, minE): # If only one element is present, # then arr[] is sorted if (N == 0): return 0 # If dp[N][maxE] is precalculated, # then return the result if (dp[N][maxE]): return dp[N][maxE] ans = sys.maxsize # Iterate from minE to maxE which # placed at previous index for k in range(minE, maxE + 1): # Update the answer according to # recurrence relation x = minimumIncDec(arr, N - 1, k, minE) ans = min(ans, x + abs(arr[N - 1] - k)) # Memoized the value # for dp[N][maxE] dp[N][maxE] = ans # Return the final result return dp[N][maxE] # Driver Codeif __name__ == \"__main__\": arr = [ 5, 4, 3, 2, 1 ] N = len(arr) # Find the minimum and maximum # element from the arr[] minE = min(arr) maxE = max(arr) # Function Call print(minimumIncDec(arr, N, maxE, minE)) # This code is contributed by chitranayal", "e": 33029, "s": 31834, "text": null }, { "code": "// C# program of the above approachusing System;using System.Linq; class GFG{ // Dp array to memoized// the value recursive callstatic int [,]dp = new int[1000, 1000]; // Function to find the minimum increment// or decrement needed to make the array// sortedstatic int minimumIncDec(int []arr, int N, int maxE, int minE){ // If only one element is present, // then []arr is sorted if (N == 0) { return 0; } // If dp[N,maxE] is precalculated, // then return the result if (dp[N, maxE] != 0) return dp[N, maxE]; int ans = int.MaxValue; // Iterate from minE to maxE which // placed at previous index for(int k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation int x = minimumIncDec(arr, N - 1, k, minE); ans = Math.Min(ans, x + Math.Abs(arr[N - 1] - k)); } // Memoized the value // for dp[N,maxE] dp[N, maxE] = ans; // Return the readonly result return dp[N,maxE];} // Driver Codepublic static void Main(String[] args){ int []arr = { 5, 4, 3, 2, 1 }; int N = arr.Length; // Find the minimum and maximum // element from the []arr int minE = arr.Min(); int maxE = arr.Max(); // Function call Console.Write(minimumIncDec(arr, N, maxE, minE));}} // This code is contributed by Rohit_ranjan", "e": 34462, "s": 33029, "text": null }, { "code": "<script> // JavaScript program of the above approach // Dp array to memoized// the value recursive calllet dp = new Array(); for(let i = 0; i < 1000; i++){ let temp = []; for(let j = 0; j < 1000; j++){ temp.push([]) } dp.push(temp)} // Function to find the minimum increment// or decrement needed to make the array// sorted function minimumIncDec(arr, N, maxE, minE){ // If only one element is present, // then arr[] is sorted if (N == 0) { return 0; } // If dp[N][maxE] is precalculated, // then return the result if (!dp[N][maxE]) return dp[N][maxE]; let ans = Number.MAX_SAFE_INTEGER; // Iterate from minE to maxE which // placed at previous index for (let k = minE; k <= maxE; k++) { // Update the answer according to // recurrence relation let x = minimumIncDec(arr, N - 1, k, minE); ans = Math.min(ans,x + Math.abs(arr[N - 1] - k)); } // Memoized the value // for dp[N][maxE] dp[N][maxE] = ans; // Return the final result return dp[N][maxE];} // Driver Code let arr = [ 5, 4, 3, 2, 1 ]; let N = arr.length; // Find the minimum and maximum // element from the arr[] let minE = arr.sort((a, b) => a - b)[0]; let maxE = arr.sort((a, b) => b - a)[0]; // Function Call document.write(minimumIncDec(arr, N, maxE, minE)); // This code is contributed by _saurabh_jaiswal </script>", "e": 35885, "s": 34462, "text": null }, { "code": null, "e": 35887, "s": 35885, "text": "6" }, { "code": null, "e": 35940, "s": 35889, "text": "Time Complexity: O(N*maxE) Auxiliary Space: O(N2) " }, { "code": null, "e": 35958, "s": 35940, "text": "VikasVishwakarma1" }, { "code": null, "e": 35964, "s": 35958, "text": "ukasp" }, { "code": null, "e": 35983, "s": 35964, "text": "Amal Kumar Choubey" }, { "code": null, "e": 35996, "s": 35983, "text": "Rohit_ranjan" }, { "code": null, "e": 36013, "s": 35996, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36032, "s": 36013, "text": "sugalialnaikkece17" }, { "code": null, "e": 36043, "s": 36032, "text": "Algorithms" }, { "code": null, "e": 36050, "s": 36043, "text": "Arrays" }, { "code": null, "e": 36070, "s": 36050, "text": "Dynamic Programming" }, { "code": null, "e": 36080, "s": 36070, "text": "Recursion" }, { "code": null, "e": 36088, "s": 36080, "text": "Sorting" }, { "code": null, "e": 36095, "s": 36088, "text": "Arrays" }, { "code": null, "e": 36115, "s": 36095, "text": "Dynamic Programming" }, { "code": null, "e": 36125, "s": 36115, "text": "Recursion" }, { "code": null, "e": 36133, "s": 36125, "text": "Sorting" }, { "code": null, "e": 36144, "s": 36133, "text": "Algorithms" }, { "code": null, "e": 36242, "s": 36144, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36291, "s": 36242, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 36316, "s": 36291, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 36344, "s": 36316, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 36395, "s": 36344, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 36422, "s": 36395, "text": "Introduction to Algorithms" }, { "code": null, "e": 36437, "s": 36422, "text": "Arrays in Java" }, { "code": null, "e": 36453, "s": 36437, "text": "Arrays in C/C++" }, { "code": null, "e": 36521, "s": 36453, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36567, "s": 36521, "text": "Write a program to reverse an array or string" } ]
Ruby | Array Join (*) method - GeeksforGeeks
07 Jan, 2020 Array#*() is an Array class method which performs set join operation on the arrays. And returns new array by concatenation of int copies of the self. Syntax: Array.*() Parameter: Arrays for performing the join or concatenation operation. Return: New arrays with concatenated int copies of self Example #1 : # Ruby code for *() method# showing join operation # declaring arraya = ["abc", "xyz", "dog"] # declaring arrayb = ["cow", "cat", "dog"] # declaring arrayc = ["cat", "1", "dog"] # a concatenating bputs "concatenation of a and b : #{a * "toy"}\n\n" # a concatenating cputs "concatenation of a and c : #{c * 1}\n\n" # b concatenating cputs "concatenation of b and c : #{b * "cat_rat"}\n\n" Output : concatenation of a and b : abctoyxyztoydog concatenation of a and c : ["cat", "1", "dog"] concatenation of b and c : cowcat_ratcatcat_ratdog Example #2 : # Ruby code for *() method# showing join operation # declaring arraya = ["abc", "xyz", "dog"] # declaring arrayb = ["cow", "cat", "dog"] # declaring arrayc = ["cat", "1", "dog"] # a concatenating bputs "concatenation of a and b : #{a * 2}\n\n" # a concatenating cputs "concatenation of a and c : #{a * 1}\n\n" # b concatenating cputs "concatenation of b and c : #{b * "34"}\n\n" # b concatenating cputs "concatenation of b and c : #{c * "toy"}\n\n" Output : concatenation of a and b : ["abc", "xyz", "dog", "abc", "xyz", "dog"] concatenation of a and c : ["abc", "xyz", "dog"] concatenation of b and c : cow34cat34dog concatenation of b and c : cattoy1toydog Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Global Variable in Ruby Ruby | Hash delete() function Ruby | Types of Variables Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | Array select() function Ruby | Data Types Ruby | Numeric round() function Ruby | String capitalize() Method Ruby | String gsub! Method
[ { "code": null, "e": 24833, "s": 24805, "text": "\n07 Jan, 2020" }, { "code": null, "e": 24983, "s": 24833, "text": "Array#*() is an Array class method which performs set join operation on the arrays. And returns new array by concatenation of int copies of the self." }, { "code": null, "e": 25001, "s": 24983, "text": "Syntax: Array.*()" }, { "code": null, "e": 25071, "s": 25001, "text": "Parameter: Arrays for performing the join or concatenation operation." }, { "code": null, "e": 25127, "s": 25071, "text": "Return: New arrays with concatenated int copies of self" }, { "code": null, "e": 25140, "s": 25127, "text": "Example #1 :" }, { "code": "# Ruby code for *() method# showing join operation # declaring arraya = [\"abc\", \"xyz\", \"dog\"] # declaring arrayb = [\"cow\", \"cat\", \"dog\"] # declaring arrayc = [\"cat\", \"1\", \"dog\"] # a concatenating bputs \"concatenation of a and b : #{a * \"toy\"}\\n\\n\" # a concatenating cputs \"concatenation of a and c : #{c * 1}\\n\\n\" # b concatenating cputs \"concatenation of b and c : #{b * \"cat_rat\"}\\n\\n\"", "e": 25534, "s": 25140, "text": null }, { "code": null, "e": 25543, "s": 25534, "text": "Output :" }, { "code": null, "e": 25687, "s": 25543, "text": "concatenation of a and b : abctoyxyztoydog\n\nconcatenation of a and c : [\"cat\", \"1\", \"dog\"]\n\nconcatenation of b and c : cowcat_ratcatcat_ratdog\n" }, { "code": null, "e": 25700, "s": 25687, "text": "Example #2 :" }, { "code": "# Ruby code for *() method# showing join operation # declaring arraya = [\"abc\", \"xyz\", \"dog\"] # declaring arrayb = [\"cow\", \"cat\", \"dog\"] # declaring arrayc = [\"cat\", \"1\", \"dog\"] # a concatenating bputs \"concatenation of a and b : #{a * 2}\\n\\n\" # a concatenating cputs \"concatenation of a and c : #{a * 1}\\n\\n\" # b concatenating cputs \"concatenation of b and c : #{b * \"34\"}\\n\\n\" # b concatenating cputs \"concatenation of b and c : #{c * \"toy\"}\\n\\n\"", "e": 26156, "s": 25700, "text": null }, { "code": null, "e": 26165, "s": 26156, "text": "Output :" }, { "code": null, "e": 26369, "s": 26165, "text": "concatenation of a and b : [\"abc\", \"xyz\", \"dog\", \"abc\", \"xyz\", \"dog\"]\n\nconcatenation of a and c : [\"abc\", \"xyz\", \"dog\"]\n\nconcatenation of b and c : cow34cat34dog\n\nconcatenation of b and c : cattoy1toydog" }, { "code": null, "e": 26386, "s": 26369, "text": "Ruby Array-class" }, { "code": null, "e": 26399, "s": 26386, "text": "Ruby-Methods" }, { "code": null, "e": 26404, "s": 26399, "text": "Ruby" }, { "code": null, "e": 26502, "s": 26404, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26526, "s": 26502, "text": "Global Variable in Ruby" }, { "code": null, "e": 26556, "s": 26526, "text": "Ruby | Hash delete() function" }, { "code": null, "e": 26582, "s": 26556, "text": "Ruby | Types of Variables" }, { "code": null, "e": 26625, "s": 26582, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 26647, "s": 26625, "text": "Ruby | Case Statement" }, { "code": null, "e": 26678, "s": 26647, "text": "Ruby | Array select() function" }, { "code": null, "e": 26696, "s": 26678, "text": "Ruby | Data Types" }, { "code": null, "e": 26728, "s": 26696, "text": "Ruby | Numeric round() function" }, { "code": null, "e": 26762, "s": 26728, "text": "Ruby | String capitalize() Method" } ]
How to change the color of ttk button in Tkinter?
Tkinter widgets have a consistent look and style across all the platforms and operating systems. Ttk works like CSS in an HTML script. It has many inbuilt functions, modules and methods that add style to a regular tkinter widget. Tkinter ttk buttons generally have a default color scheme, thus we can change the background color of these buttons by configuration method. In this example, we will create a button which when pressed will change its style. #Import the necessary library import itertools from tkinter import * from tkinter import ttk #Create an instance of tkinter window win = Tk() #Set the geometry of tkinter window win.geometry("750x250") #Define the style style_1 = {'fg': 'black', 'bg': 'RoyalBlue3', 'activebackground': 'gray71', 'activeforeground': 'gray71'} style_2 = {'fg': 'white', 'bg': 'OliveDrab2', 'activebackground': 'gray71', 'activeforeground': 'gray71'} style_3 = {'fg': 'black', 'bg': 'purple1', 'activebackground': 'gray71', 'activeforeground': 'gray71'} style_4 = {'fg': 'white', 'bg': 'coral2', 'activebackground': 'gray71', 'activeforeground': 'gray71'} style_cycle = itertools.cycle([style_1, style_2, style_3, style_4 ]) #Define a function to update the button style def update_style(): style = next(style_cycle) button.configure(**style) #Create a tk button button = Button(win,width=40,font=('Helvetica 18 bold'), text="Change Style", command=update_style) button.pack(padx=50, pady=50) win.mainloop() Running the above code will display a window with a button. When you click the button, it will switch the style of background color and text color. Now, click the button to change the color of the Button.
[ { "code": null, "e": 1433, "s": 1062, "text": "Tkinter widgets have a consistent look and style across all the platforms and operating systems. Ttk works like CSS in an HTML script. It has many inbuilt functions, modules and methods that add style to a regular tkinter widget. Tkinter ttk buttons generally have a default color scheme, thus we can change the background color of these buttons by configuration method." }, { "code": null, "e": 1516, "s": 1433, "text": "In this example, we will create a button which when pressed will change its style." }, { "code": null, "e": 2505, "s": 1516, "text": "#Import the necessary library\nimport itertools\nfrom tkinter import *\nfrom tkinter import ttk\n#Create an instance of tkinter window\nwin = Tk()\n#Set the geometry of tkinter window\nwin.geometry(\"750x250\")\n#Define the style\nstyle_1 = {'fg': 'black', 'bg': 'RoyalBlue3', 'activebackground':\n'gray71', 'activeforeground': 'gray71'}\nstyle_2 = {'fg': 'white', 'bg': 'OliveDrab2', 'activebackground':\n'gray71', 'activeforeground': 'gray71'}\nstyle_3 = {'fg': 'black', 'bg': 'purple1', 'activebackground':\n'gray71', 'activeforeground': 'gray71'}\nstyle_4 = {'fg': 'white', 'bg': 'coral2', 'activebackground':\n'gray71', 'activeforeground': 'gray71'}\nstyle_cycle = itertools.cycle([style_1, style_2, style_3, style_4 ])\n#Define a function to update the button style\ndef update_style():\nstyle = next(style_cycle)\nbutton.configure(**style)\n#Create a tk button\nbutton = Button(win,width=40,font=('Helvetica 18 bold'), text=\"Change\nStyle\", command=update_style)\nbutton.pack(padx=50, pady=50)\nwin.mainloop()" }, { "code": null, "e": 2653, "s": 2505, "text": "Running the above code will display a window with a button. When you click the button, it will switch the style of background color and text color." }, { "code": null, "e": 2710, "s": 2653, "text": "Now, click the button to change the color of the Button." } ]
Generalized Abbreviation in C++
Suppose there is a word. We have to define a function that can generate the generalized abbreviations of a word. So, if the input is like "word", then the output will be ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d", "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"] To solve this, we will follow these steps − Define an array ret Define an array ret Define a function solve(), this will take s, idx, Define a function solve(), this will take s, idx, if idx >= size of s, then −insert s at the end of retreturn if idx >= size of s, then − insert s at the end of ret insert s at the end of ret return return y := substring of s from index 0 to idx - 1 y := substring of s from index 0 to idx - 1 i := size of y i := size of y num := blank string num := blank string while (i >= 0 and y[i] <= ASCII of '9' and y[i] >= ASCII of '0'), do −num := y[i] + num(decrease i by 1) while (i >= 0 and y[i] <= ASCII of '9' and y[i] >= ASCII of '0'), do − num := y[i] + num num := y[i] + num (decrease i by 1) (decrease i by 1) if i is not equal to size of y, then −ret := substring of s from index (0 to idx - (size of y - 1 - i) - 1) concatenate (number + 1)as string concatenate substring of s from index (0 to idx)s1 := num + 1 as strings2 := num as stringif size of s1 is same as size of s2, then −Otherwisesolve(ret, idx + 1) if i is not equal to size of y, then − ret := substring of s from index (0 to idx - (size of y - 1 - i) - 1) concatenate (number + 1)as string concatenate substring of s from index (0 to idx) ret := substring of s from index (0 to idx - (size of y - 1 - i) - 1) concatenate (number + 1)as string concatenate substring of s from index (0 to idx) s1 := num + 1 as string s1 := num + 1 as string s2 := num as string s2 := num as string if size of s1 is same as size of s2, then − if size of s1 is same as size of s2, then − Otherwisesolve(ret, idx + 1) Otherwise solve(ret, idx + 1) solve(ret, idx + 1) Otherwiseprev := s[idx]s[idx] := '1'solve(s, idx + 1)s[idx] := prev Otherwise prev := s[idx] prev := s[idx] s[idx] := '1' s[idx] := '1' solve(s, idx + 1) solve(s, idx + 1) s[idx] := prev s[idx] := prev solve(s, idx + 1) solve(s, idx + 1) From the main method do the following − From the main method do the following − solve(word, 0) solve(word, 0) return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; void print_vector(vector<auto< v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<string> ret; void solve(string s, int idx){ if (idx >= s.size()) { ret.push_back(s); return; } string y = s.substr(0, idx); int i = y.size() - 1; string num = ""; while (i >= 0 && y[i] <= '9' && y[i] >= '0') { num = y[i] + num; i--; } if (i != y.size() - 1) { string ret = s.substr(0, idx - (y.size() - 1 - i)) + to_string(stoi(num) + 1) + s.substr(idx + 1); string s1 = to_string(stoi(num) + 1); string s2 = to_string(stoi(num)); if (s1.size() == s2.size()) solve(ret, idx); else solve(ret, idx + 1); } else { char prev = s[idx]; s[idx] = '1'; solve(s, idx + 1); s[idx] = prev; } solve(s, idx + 1); } vector<string< generateAbbreviations(string word){ solve(word, 0); return ret; } }; main(){ Solution ob; print_vector(ob.generateAbbreviations("hello")); } hello [5, 4o, 3l1, 3lo, 2l2, 2l1o, 2ll1, 2llo, 1e3, 1e2o, 1e1l1, 1e1lo, 1el2, 1el1o, 1ell1, 1ello, h4, h3o, h2l1, h2lo, h1l2, h1l1o, h1ll1, h1llo, he3, he2o, he1l1, he1lo, hel2, hel1o, hell1, hello, ]
[ { "code": null, "e": 1175, "s": 1062, "text": "Suppose there is a word. We have to define a function that can generate the generalized abbreviations of a word." }, { "code": null, "e": 1349, "s": 1175, "text": "So, if the input is like \"word\", then the output will be [\"word\", \"1ord\", \"w1rd\", \"wo1d\", \"wor1\", \"2rd\", \"w2d\", \"wo2\", \"1o1d\", \"1or1\", \"w1r1\", \"1o2\", \"2r1\", \"3d\", \"w3\", \"4\"]" }, { "code": null, "e": 1393, "s": 1349, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1413, "s": 1393, "text": "Define an array ret" }, { "code": null, "e": 1433, "s": 1413, "text": "Define an array ret" }, { "code": null, "e": 1483, "s": 1433, "text": "Define a function solve(), this will take s, idx," }, { "code": null, "e": 1533, "s": 1483, "text": "Define a function solve(), this will take s, idx," }, { "code": null, "e": 1593, "s": 1533, "text": "if idx >= size of s, then −insert s at the end of retreturn" }, { "code": null, "e": 1621, "s": 1593, "text": "if idx >= size of s, then −" }, { "code": null, "e": 1648, "s": 1621, "text": "insert s at the end of ret" }, { "code": null, "e": 1675, "s": 1648, "text": "insert s at the end of ret" }, { "code": null, "e": 1682, "s": 1675, "text": "return" }, { "code": null, "e": 1689, "s": 1682, "text": "return" }, { "code": null, "e": 1733, "s": 1689, "text": "y := substring of s from index 0 to idx - 1" }, { "code": null, "e": 1777, "s": 1733, "text": "y := substring of s from index 0 to idx - 1" }, { "code": null, "e": 1792, "s": 1777, "text": "i := size of y" }, { "code": null, "e": 1807, "s": 1792, "text": "i := size of y" }, { "code": null, "e": 1827, "s": 1807, "text": "num := blank string" }, { "code": null, "e": 1847, "s": 1827, "text": "num := blank string" }, { "code": null, "e": 1952, "s": 1847, "text": "while (i >= 0 and y[i] <= ASCII of '9' and y[i] >= ASCII of '0'), do −num := y[i] + num(decrease i by 1)" }, { "code": null, "e": 2023, "s": 1952, "text": "while (i >= 0 and y[i] <= ASCII of '9' and y[i] >= ASCII of '0'), do −" }, { "code": null, "e": 2041, "s": 2023, "text": "num := y[i] + num" }, { "code": null, "e": 2059, "s": 2041, "text": "num := y[i] + num" }, { "code": null, "e": 2077, "s": 2059, "text": "(decrease i by 1)" }, { "code": null, "e": 2095, "s": 2077, "text": "(decrease i by 1)" }, { "code": null, "e": 2399, "s": 2095, "text": "if i is not equal to size of y, then −ret := substring of s from index (0 to idx - (size of y - 1 - i) - 1) concatenate (number + 1)as string concatenate substring of s from index (0 to idx)s1 := num + 1 as strings2 := num as stringif size of s1 is same as size of s2, then −Otherwisesolve(ret, idx + 1)" }, { "code": null, "e": 2438, "s": 2399, "text": "if i is not equal to size of y, then −" }, { "code": null, "e": 2591, "s": 2438, "text": "ret := substring of s from index (0 to idx - (size of y - 1 - i) - 1) concatenate (number + 1)as string concatenate substring of s from index (0 to idx)" }, { "code": null, "e": 2744, "s": 2591, "text": "ret := substring of s from index (0 to idx - (size of y - 1 - i) - 1) concatenate (number + 1)as string concatenate substring of s from index (0 to idx)" }, { "code": null, "e": 2768, "s": 2744, "text": "s1 := num + 1 as string" }, { "code": null, "e": 2792, "s": 2768, "text": "s1 := num + 1 as string" }, { "code": null, "e": 2812, "s": 2792, "text": "s2 := num as string" }, { "code": null, "e": 2832, "s": 2812, "text": "s2 := num as string" }, { "code": null, "e": 2876, "s": 2832, "text": "if size of s1 is same as size of s2, then −" }, { "code": null, "e": 2920, "s": 2876, "text": "if size of s1 is same as size of s2, then −" }, { "code": null, "e": 2949, "s": 2920, "text": "Otherwisesolve(ret, idx + 1)" }, { "code": null, "e": 2959, "s": 2949, "text": "Otherwise" }, { "code": null, "e": 2979, "s": 2959, "text": "solve(ret, idx + 1)" }, { "code": null, "e": 2999, "s": 2979, "text": "solve(ret, idx + 1)" }, { "code": null, "e": 3067, "s": 2999, "text": "Otherwiseprev := s[idx]s[idx] := '1'solve(s, idx + 1)s[idx] := prev" }, { "code": null, "e": 3077, "s": 3067, "text": "Otherwise" }, { "code": null, "e": 3092, "s": 3077, "text": "prev := s[idx]" }, { "code": null, "e": 3107, "s": 3092, "text": "prev := s[idx]" }, { "code": null, "e": 3121, "s": 3107, "text": "s[idx] := '1'" }, { "code": null, "e": 3135, "s": 3121, "text": "s[idx] := '1'" }, { "code": null, "e": 3153, "s": 3135, "text": "solve(s, idx + 1)" }, { "code": null, "e": 3171, "s": 3153, "text": "solve(s, idx + 1)" }, { "code": null, "e": 3186, "s": 3171, "text": "s[idx] := prev" }, { "code": null, "e": 3201, "s": 3186, "text": "s[idx] := prev" }, { "code": null, "e": 3219, "s": 3201, "text": "solve(s, idx + 1)" }, { "code": null, "e": 3237, "s": 3219, "text": "solve(s, idx + 1)" }, { "code": null, "e": 3277, "s": 3237, "text": "From the main method do the following −" }, { "code": null, "e": 3317, "s": 3277, "text": "From the main method do the following −" }, { "code": null, "e": 3332, "s": 3317, "text": "solve(word, 0)" }, { "code": null, "e": 3347, "s": 3332, "text": "solve(word, 0)" }, { "code": null, "e": 3358, "s": 3347, "text": "return ret" }, { "code": null, "e": 3369, "s": 3358, "text": "return ret" }, { "code": null, "e": 3439, "s": 3369, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3450, "s": 3439, "text": " Live Demo" }, { "code": null, "e": 4676, "s": 3450, "text": "#include <bits/stdc++.h>\nusing namespace std;\nvoid print_vector(vector<auto< v){\n cout << \"[\";\n for(int i = 0; i<v.size(); i++){\n cout << v[i] << \", \";\n }\n cout << \"]\"<<endl;\n}\nclass Solution {\npublic:\n vector<string> ret;\n void solve(string s, int idx){\n if (idx >= s.size()) {\n ret.push_back(s);\n return;\n }\n string y = s.substr(0, idx);\n int i = y.size() - 1;\n string num = \"\";\n while (i >= 0 && y[i] <= '9' && y[i] >= '0') {\n num = y[i] + num;\n i--;\n }\n if (i != y.size() - 1) {\n string ret = s.substr(0, idx - (y.size() - 1 - i)) + to_string(stoi(num) + 1) + s.substr(idx + 1);\n string s1 = to_string(stoi(num) + 1);\n string s2 = to_string(stoi(num));\n if (s1.size() == s2.size())\n solve(ret, idx);\n else\n solve(ret, idx + 1);\n }\n else {\n char prev = s[idx];\n s[idx] = '1';\n solve(s, idx + 1);\n s[idx] = prev;\n }\n solve(s, idx + 1);\n }\n vector<string< generateAbbreviations(string word){\n solve(word, 0);\n return ret;\n }\n};\nmain(){\n Solution ob;\n print_vector(ob.generateAbbreviations(\"hello\"));\n}" }, { "code": null, "e": 4682, "s": 4676, "text": "hello" }, { "code": null, "e": 4877, "s": 4682, "text": "[5, 4o, 3l1, 3lo, 2l2, 2l1o, 2ll1, 2llo, 1e3, 1e2o, 1e1l1, 1e1lo, 1el2, 1el1o, 1ell1, 1ello, h4, h3o, h2l1, h2lo, h1l2, h1l1o, h1ll1, h1llo, he3, he2o, he1l1, he1lo, hel2, hel1o, hell1, hello, ]" } ]
How to use Radar Chart graph in android?
This example demonstrates How to use Radar chart graph in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Open build.gradle(module level) and add library dependency. apply plugin: 'com.android.application' android { packagingOptions { exclude 'META-INF/proguard/androidx-annotations.pro' } packagingOptions { exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/LICENSE' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/license.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/notice.txt' exclude 'META-INF/ASL2.0' } compileSdkVersion 28 defaultConfig { applicationId "com.example.andy.myapplication" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' } Step 3 − Open build.gradle(application level) and add library dependency. // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() maven { url 'https://jitpack.io' } } } task clean(type: Delete) { delete rootProject.buildDir } Step 4 − Add the following code to res/layout/activity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android = "http://schemas.android.com/apk/res/android" xmlns:app = "http://schemas.android.com/apk/res-auto" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity"> <com.github.mikephil.charting.charts.RadarChart android:id = "@+id/RadarChart" android:layout_width = "fill_parent" android:layout_height = "fill_parent" /> </android.support.constraint.ConstraintLayout> In the above code, we have taken the Radar Chart view to show a Radar chart Step 4 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import com.github.mikephil.charting.charts.BubbleChart; import com.github.mikephil.charting.charts.RadarChart; import com.github.mikephil.charting.data.BubbleData; import com.github.mikephil.charting.data.BubbleDataSet; import com.github.mikephil.charting.data.BubbleEntry; import com.github.mikephil.charting.data.RadarData; import com.github.mikephil.charting.data.RadarDataSet; import com.github.mikephil.charting.data.RadarEntry; import com.github.mikephil.charting.utils.ColorTemplate; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { RadarChart RadarChart; RadarData radarData; RadarDataSet radarDataSet; ArrayList radarEntries; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RadarChart = findViewById(R.id.RadarChart); getEntries(); radarDataSet = new RadarDataSet(radarEntries, ""); radarData = new RadarData(radarDataSet); RadarChart.setData(radarData); radarDataSet.setColors(ColorTemplate.JOYFUL_COLORS); radarDataSet.setValueTextColor(Color.BLACK); radarDataSet.setValueTextSize(18f); } private void getEntries() { radarEntries = new ArrayList<>(); radarEntries.add(new RadarEntry(0, 0.21f)); radarEntries.add(new RadarEntry(1, 0.12f)); radarEntries.add(new RadarEntry(2, 0.20f)); radarEntries.add(new RadarEntry(2, 0.52f)); radarEntries.add(new RadarEntry(3, 0.29f)); radarEntries.add(new RadarEntry(4, 0.62f)); } } Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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 – In the above result, it is showing the radar chart as per our data set values. Click here to download the project code
[ { "code": null, "e": 1129, "s": 1062, "text": "This example demonstrates How to use Radar chart graph in android." }, { "code": null, "e": 1258, "s": 1129, "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": 1327, "s": 1258, "text": "Step 2 − Open build.gradle(module level) and add library dependency." }, { "code": null, "e": 2688, "s": 1327, "text": "apply plugin: 'com.android.application'\nandroid {\n packagingOptions {\n exclude 'META-INF/proguard/androidx-annotations.pro'\n }\n packagingOptions {\n exclude 'META-INF/DEPENDENCIES'\n exclude 'META-INF/LICENSE'\n exclude 'META-INF/LICENSE.txt'\n exclude 'META-INF/license.txt'\n exclude 'META-INF/NOTICE'\n exclude 'META-INF/NOTICE.txt'\n exclude 'META-INF/notice.txt'\n exclude 'META-INF/ASL2.0'\n }\n compileSdkVersion 28\n defaultConfig {\n applicationId \"com.example.andy.myapplication\"\n minSdkVersion 15\n targetSdkVersion 28\n versionCode 1\n versionName \"1.0\"\n testInstrumentationRunner \"android.support.test.runner.AndroidJUnitRunner\"\n }\n buildTypes {\n release {\n minifyEnabled false\n proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\n }\n }\n}\ndependencies {\n implementation fileTree(dir: 'libs', include: ['*.jar'])\n implementation 'com.android.support:appcompat-v7:28.0.0'\n implementation 'com.android.support.constraint:constraint-layout:1.1.3'\n implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0-alpha'\n testImplementation 'junit:junit:4.12'\n androidTestImplementation 'com.android.support.test:runner:1.0.2'\n androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'\n}" }, { "code": null, "e": 2762, "s": 2688, "text": "Step 3 − Open build.gradle(application level) and add library dependency." }, { "code": null, "e": 3313, "s": 2762, "text": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\nbuildscript {\n repositories {\n google()\n jcenter()\n }\n dependencies {\n classpath 'com.android.tools.build:gradle:3.2.1'\n // NOTE: Do not place your application dependencies here; they belong\n // in the individual module build.gradle files\n }\n}\nallprojects {\n repositories {\n google()\n jcenter()\n maven { url 'https://jitpack.io' }\n }\n}\ntask clean(type: Delete) {\n delete rootProject.buildDir\n}" }, { "code": null, "e": 3378, "s": 3313, "text": "Step 4 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 3980, "s": 3378, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<android.support.constraint.ConstraintLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n xmlns:app = \"http://schemas.android.com/apk/res-auto\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\">\n <com.github.mikephil.charting.charts.RadarChart\n android:id = \"@+id/RadarChart\"\n android:layout_width = \"fill_parent\"\n android:layout_height = \"fill_parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 4056, "s": 3980, "text": "In the above code, we have taken the Radar Chart view to show a Radar chart" }, { "code": null, "e": 4113, "s": 4056, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5842, "s": 4113, "text": "package com.example.andy.myapplication;\nimport android.graphics.Color;\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport com.github.mikephil.charting.charts.BubbleChart;\nimport com.github.mikephil.charting.charts.RadarChart;\nimport com.github.mikephil.charting.data.BubbleData;\nimport com.github.mikephil.charting.data.BubbleDataSet;\nimport com.github.mikephil.charting.data.BubbleEntry;\nimport com.github.mikephil.charting.data.RadarData;\nimport com.github.mikephil.charting.data.RadarDataSet;\nimport com.github.mikephil.charting.data.RadarEntry;\nimport com.github.mikephil.charting.utils.ColorTemplate;\nimport java.util.ArrayList;\npublic class MainActivity extends AppCompatActivity {\n RadarChart RadarChart;\n RadarData radarData;\n RadarDataSet radarDataSet;\n ArrayList radarEntries;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n RadarChart = findViewById(R.id.RadarChart);\n getEntries();\n radarDataSet = new RadarDataSet(radarEntries, \"\");\n radarData = new RadarData(radarDataSet);\n RadarChart.setData(radarData);\n radarDataSet.setColors(ColorTemplate.JOYFUL_COLORS);\n radarDataSet.setValueTextColor(Color.BLACK);\n radarDataSet.setValueTextSize(18f);\n }\n private void getEntries() {\n radarEntries = new ArrayList<>();\n radarEntries.add(new RadarEntry(0, 0.21f));\n radarEntries.add(new RadarEntry(1, 0.12f));\n radarEntries.add(new RadarEntry(2, 0.20f));\n radarEntries.add(new RadarEntry(2, 0.52f));\n radarEntries.add(new RadarEntry(3, 0.29f));\n radarEntries.add(new RadarEntry(4, 0.62f));\n }\n}" }, { "code": null, "e": 6193, "s": 5842, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the 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": 6272, "s": 6193, "text": "In the above result, it is showing the radar chart as per our data set values." }, { "code": null, "e": 6312, "s": 6272, "text": "Click here to download the project code" } ]
12 Math Tricks to Help You Solve Problems Without a Calculator | by Andrew Jamieson | Towards Data Science
The first trick is to simplify your problem by breaking it into smaller pieces. For example, we can rewrite 567 + 432 = 567 + (400 + 30 + 2)= 967 + 30 + 2 = 997 + 2 = 999 It’s often easier to work with adding a smaller number, so instead of 131 + 858, swap the numbers 858 + 131 = 858 + 100 + 30 + 1 = 989 Using the complement of a number can help make subtraction easier. The complement is the difference between the original number and a round number — say 100, 1000. Here are some examples with the number and its complement compared with 100: 67:33, 45:55, 89:11, 3:97 Notice that the second digits add up to 10, and the first digit adds up to 9. Here is how this is helpful 721–387 # the complement of 87 is 13, so we can swap 387 with 400 – 13-> 721 — (400 - 13) = 321 - -13 = 321 + 13= 334 Another method is to write out the larger number so it ends in 99. With the same example: 721 -> (699 + 22)= 699 – 387 + 22 = 312 + 22 = 334 For a two-digit number, add the digits and put the answer in the middle of the number you are multiplying: 35 x 11 -> 3_5 -> 3+5 = 8 -> 385 If the sum is greater than 10, add the tens digit to the next column to the left, and write the ones digit in the answer. For example, 4+8 = 12, write down 2 and carry the 1 into the next column. 48 x 11 -> 4_8 -> 4+8 = 12 -> 4,12,8 -> 528 The process is a little more complicated for three-digit and greater numbers, but it works in a similar way. This time keep the first and last digit and sum the digits in pairs 725 X 11 -> 7__5 -> 7_,(7+2=9), (2+5=7), _5 -> 797551973 x 11 -> 5__3 -> 5_,(5+1=6),(1+9=10), (9+7=16), (7+3=10), _3 # where the sum is greater than ten we move the tens digit into the next column -> 5,(6+1),(0+1),(6+1),(0),3 -> 571703 Multiplying by nines can be simplified by multiplying by 10 and subtracting the original number 799 x 9 = 799 x (10 -1) = 7990 – 799 = 7191 Use the same method for anything ending in 9 72 x 89 = 72 x (90–1) = (70 x 90) + (2 x 90) — 72 = 6300 + 180–72 = 6408 You can re-write a square equation into numbers that are easier to deal with using this formula n^2 = (n+d)(n-d) + d^2 where n is the number to be squared, and d is the difference Here’s an example 57^2 = (57+3)(57–3) + 3^2# we add 3 to 57, as 60 is easier to multiply than 57, and subtract 3 from the second 57-> 60 x 54 + 9 = 3000 + 240 + 9 = 3249 The ultimate example is when you are squaring a number ending in 5, then round one number up to the nearest 10, the other number down to the nearest 10, and add 25. 65^2 = (60 x 70) + 5^2 = 4200 + 25 = 4225 A similar method works for multiplying numbers that are close together. The formula works for all numbers, but it doesn’t simplify well unless the numbers are similar. Here’s the formula. n is the “base” number (n+a)(n+b) = n(n + a + b) + ab An example: 47 x 43 = (40 + 7)(40 + 3) = 40 x (40 + 3 + 7) + (7 x 3)= (40 x 50) + (7 x 3) = 2000 + 21 = 2021 In this example, the ones digits add up to ten, so our “base” number and the multiplier are round numbers (40 and 50). Here’s another example. Reduce the smaller number to reach the nearest round number — our base number, in this case, 40. Add the difference to the larger number. Multiple the base and larger number. Finally, add the product of the difference between the original numbers and the base number. 47 x 42 = (40 + 7) x (40 + 2) = (40 + 7 + 2) x 40 + (7 x 2)= (49 x 40) + (7 x 2) = (40 x 40) + (40 x 9) + (7 x 2)= 1600 + 360 + 14 = 1974 You can also round up to the base number. As the original numbers are smaller than the base, we add the product of two negative numbers. 47 x 42 = (50 x 39) + (-3 x -8) = (50 x 30) + (50 x 9) + (-3 x -8)= 1500 + 450 + 24 = 1974 This works for three-digit numbers too. In this case, the base number is between our numbers, so the product is a negative number. 497 x 504 = (500 – 3) x (500 + 4)= (500) x (500 + 4 - 3) + (-3 x 4)= 500 x 501 - 12= 250,000 + 500 – 12= 250,488 You can simplify some equations before you even start. For example, divide both the divisor and dividend by two. 898 / 4 = 449 / 2 = 224 and 1⁄2 Note with this method, you have to write the remainder as a fraction: 898/4 has a remainder of 2 — divided by 4449/2 has a remainder of 1 — divided by 2 The fraction is the same, but the absolute number is different. When dividing by 5, modify the equation by multiplying by 2. It is much easier to divide by 10. For example: 1753/5 = 3506 / 10= 350.6 There are many ways to quickly whether a number is a factor. 2: The number is even. Example 28790 is even, so it is divisible by 2. 3: The sum of the digits is divisible by 3. Example: 1281 -> 1+2+8+1 = 12 -> 12 is a multiple of 3, so 1281 is divisible by 3 4: The last two digits are divisible by 4. Why does this work? 100 is a multiple of 4, so we only have to check the last two digits. Example: 1472, 72 is divisible by 4, so 1472 is divisible by 4. 5: The number ends in 5 or 0. Example: 575 ends in 5, so it is divisible by zero 6: The number is even, and the sum of the digits is divisible by 3. 6 is 3 x 2, so the rules of 2 and 3 apply. Example: 774 is even and 7+7+4 = 18 -> 18 is divisible by 3, so 774 is divisible by 6. 7: Add or subtract a multiple of 7 to your number so that it ends in zero. Drop the last digit with the zero and repeat the process. Continue until you can determine whether the result is divisible by 7. Example: 2702 add 98 (7 x 14) -> 2800, drop the zeroes-> 28 is a multiple of 7, so 2702 is divisible by 7. 8: The last three digits are divisible by 8. Example: 79256, 256 is divisible by 8, so 79256 is divisible by 8.(Alternate rule: if the hundreds digit is even, last 2 digits divisble by 8, if hundreds digit is odd, last 2 digits + 4 divisible by 8) 9: The same rule as 3, but with 9. If the sum of the digits is divisible by 9, then the number is divisible by 9. Example: 13671 -> 1+3+6+7+1 = 18 -> 18 is divisible by 9, so 13671 is divisible by 9 10: The number ends in 0. Example: 280 ends in 0, 280 is divisible by 10 11: Similar rule to 3 and 9, start at the right digit and alternate subtracting and adding the remaining digits. If the answer is zero, or a multiple of 11, then the number is divisible by 11. Example: 12727 -> 1 - 2 + 7 - 2 + 7 = 11, so 12727 is divisible by 11. You can check out some additional methods here. Example:-> 10520/9 Write the first digit above the equation and write an “R” (for remainder) above the last digit. Add the number you just wrote and the number diagonally below and to the right of it. Write this new number in the second spot. Add that number to the number diagonally below and to the right. Continue this process until you reach the R. Finally, add the last digit to the number below the R to get your remainder. 10520/9= 1168 R8or 1168.889 Here’s another example: -> 57423/9 This time after we’ve completed the first step, the sum of our first number and the number diagonally below and to the right is larger than ten (5+7 =12). We put a one above the first digit and subtract nine from it. (We are dividing by a base of nine, so we subtract nine rather than ten). Place the resulting number in the second position (12–9 = 3). Continue with the same process. In this example, our remainder is larger than 9 (9+3 = 12). Once again, we carry a one above the previous digit and subtract nine from the remainder, leaving us with three. Now add the result and the carry digits. 57423 / 9 = 6380 R3or 6380.333 Percentages are associative, so sometimes reversing the question’s order makes it easier to calculate. Example: What’s 36% of 25 -> is the same as 25% of 36 -> 25% is 1⁄4 -> 36/4 = 9 36% of 25 is 9 As you can see with the use of 1⁄4 in the last example, it helps know fractions and how they relate to percentages. 1/2 = 50%1/3 = 33.33%, 2/3 = 66.67%,1/4 = 25%, 3/4= 75%1/5 = 20%, 2/5 = 40% ...1/6 = 16.67%, 5/6 = 83.33% (2/6 = 1/3, 3/6 = 1/2, 4/6 = 2/3)1/7 = 14.2857%, 2/7 = 28.5714%, 3/7 = 42.8571%, 4/7 = 57.1428% (note the recurring .142857 pattern)1/8 = 12.5%, 3/8 = 37.5%, 5/8 = 62.5%, 7/8 = 87.5%1/9 = 11.11%, 2/9 = 22.22%, 3/9 = 33.33% ...1/10 = 10%, 2/10 = 20% ...1/11 = 9.09%, 2/11 = 18.18%, 3/11 = 27.27% ...1/12 = 8.33%, 5/12 = 41.67%, 7/12 = 58.33%, 11/12 = 91.67% The rule of 72 provides an estimate of how many years it will take an investment to double in value at a given percentage return. It works by dividing 72 by the percentage, with the answer as the number of years it will take to double. 2% -> 72/2 = 36, approximately 36 years to double8% -> 72/8 = 9, approximately 9 years to double Note that the rule of 72 is a guideline based on the natural log of 2 — which gives 0.693. So a rule of 69.3 would be more accurate, but 72 is easier to calculate. There is also a rule of 114 for tripling an investment and a rule of 144 for quadrupling your money. I found two books by Arthur Benjamin to be helpful on this topic. Many of the examples in this blog were inspired by these books. You can check them out here. www.amazon.com https://www.amazon.com/Secrets-Mental-Math-Mathemagicians-Calculation/dp/0307338401/ Please leave a comment if you found this helpful, or share any other useful tricks you have come across.
[ { "code": null, "e": 280, "s": 172, "text": "The first trick is to simplify your problem by breaking it into smaller pieces. For example, we can rewrite" }, { "code": null, "e": 343, "s": 280, "text": "567 + 432 = 567 + (400 + 30 + 2)= 967 + 30 + 2 = 997 + 2 = 999" }, { "code": null, "e": 441, "s": 343, "text": "It’s often easier to work with adding a smaller number, so instead of 131 + 858, swap the numbers" }, { "code": null, "e": 478, "s": 441, "text": "858 + 131 = 858 + 100 + 30 + 1 = 989" }, { "code": null, "e": 642, "s": 478, "text": "Using the complement of a number can help make subtraction easier. The complement is the difference between the original number and a round number — say 100, 1000." }, { "code": null, "e": 719, "s": 642, "text": "Here are some examples with the number and its complement compared with 100:" }, { "code": null, "e": 745, "s": 719, "text": "67:33, 45:55, 89:11, 3:97" }, { "code": null, "e": 823, "s": 745, "text": "Notice that the second digits add up to 10, and the first digit adds up to 9." }, { "code": null, "e": 851, "s": 823, "text": "Here is how this is helpful" }, { "code": null, "e": 970, "s": 851, "text": "721–387 # the complement of 87 is 13, so we can swap 387 with 400 – 13-> 721 — (400 - 13) = 321 - -13 = 321 + 13= 334" }, { "code": null, "e": 1060, "s": 970, "text": "Another method is to write out the larger number so it ends in 99. With the same example:" }, { "code": null, "e": 1111, "s": 1060, "text": "721 -> (699 + 22)= 699 – 387 + 22 = 312 + 22 = 334" }, { "code": null, "e": 1218, "s": 1111, "text": "For a two-digit number, add the digits and put the answer in the middle of the number you are multiplying:" }, { "code": null, "e": 1251, "s": 1218, "text": "35 x 11 -> 3_5 -> 3+5 = 8 -> 385" }, { "code": null, "e": 1447, "s": 1251, "text": "If the sum is greater than 10, add the tens digit to the next column to the left, and write the ones digit in the answer. For example, 4+8 = 12, write down 2 and carry the 1 into the next column." }, { "code": null, "e": 1491, "s": 1447, "text": "48 x 11 -> 4_8 -> 4+8 = 12 -> 4,12,8 -> 528" }, { "code": null, "e": 1668, "s": 1491, "text": "The process is a little more complicated for three-digit and greater numbers, but it works in a similar way. This time keep the first and last digit and sum the digits in pairs" }, { "code": null, "e": 1904, "s": 1668, "text": "725 X 11 -> 7__5 -> 7_,(7+2=9), (2+5=7), _5 -> 797551973 x 11 -> 5__3 -> 5_,(5+1=6),(1+9=10), (9+7=16), (7+3=10), _3 # where the sum is greater than ten we move the tens digit into the next column -> 5,(6+1),(0+1),(6+1),(0),3 -> 571703" }, { "code": null, "e": 2000, "s": 1904, "text": "Multiplying by nines can be simplified by multiplying by 10 and subtracting the original number" }, { "code": null, "e": 2044, "s": 2000, "text": "799 x 9 = 799 x (10 -1) = 7990 – 799 = 7191" }, { "code": null, "e": 2089, "s": 2044, "text": "Use the same method for anything ending in 9" }, { "code": null, "e": 2162, "s": 2089, "text": "72 x 89 = 72 x (90–1) = (70 x 90) + (2 x 90) — 72 = 6300 + 180–72 = 6408" }, { "code": null, "e": 2258, "s": 2162, "text": "You can re-write a square equation into numbers that are easier to deal with using this formula" }, { "code": null, "e": 2282, "s": 2258, "text": "n^2 = (n+d)(n-d) + d^2 " }, { "code": null, "e": 2343, "s": 2282, "text": "where n is the number to be squared, and d is the difference" }, { "code": null, "e": 2361, "s": 2343, "text": "Here’s an example" }, { "code": null, "e": 2513, "s": 2361, "text": "57^2 = (57+3)(57–3) + 3^2# we add 3 to 57, as 60 is easier to multiply than 57, and subtract 3 from the second 57-> 60 x 54 + 9 = 3000 + 240 + 9 = 3249" }, { "code": null, "e": 2678, "s": 2513, "text": "The ultimate example is when you are squaring a number ending in 5, then round one number up to the nearest 10, the other number down to the nearest 10, and add 25." }, { "code": null, "e": 2720, "s": 2678, "text": "65^2 = (60 x 70) + 5^2 = 4200 + 25 = 4225" }, { "code": null, "e": 2888, "s": 2720, "text": "A similar method works for multiplying numbers that are close together. The formula works for all numbers, but it doesn’t simplify well unless the numbers are similar." }, { "code": null, "e": 2931, "s": 2888, "text": "Here’s the formula. n is the “base” number" }, { "code": null, "e": 2962, "s": 2931, "text": "(n+a)(n+b) = n(n + a + b) + ab" }, { "code": null, "e": 2974, "s": 2962, "text": "An example:" }, { "code": null, "e": 3071, "s": 2974, "text": "47 x 43 = (40 + 7)(40 + 3) = 40 x (40 + 3 + 7) + (7 x 3)= (40 x 50) + (7 x 3) = 2000 + 21 = 2021" }, { "code": null, "e": 3190, "s": 3071, "text": "In this example, the ones digits add up to ten, so our “base” number and the multiplier are round numbers (40 and 50)." }, { "code": null, "e": 3482, "s": 3190, "text": "Here’s another example. Reduce the smaller number to reach the nearest round number — our base number, in this case, 40. Add the difference to the larger number. Multiple the base and larger number. Finally, add the product of the difference between the original numbers and the base number." }, { "code": null, "e": 3620, "s": 3482, "text": "47 x 42 = (40 + 7) x (40 + 2) = (40 + 7 + 2) x 40 + (7 x 2)= (49 x 40) + (7 x 2) = (40 x 40) + (40 x 9) + (7 x 2)= 1600 + 360 + 14 = 1974" }, { "code": null, "e": 3757, "s": 3620, "text": "You can also round up to the base number. As the original numbers are smaller than the base, we add the product of two negative numbers." }, { "code": null, "e": 3848, "s": 3757, "text": "47 x 42 = (50 x 39) + (-3 x -8) = (50 x 30) + (50 x 9) + (-3 x -8)= 1500 + 450 + 24 = 1974" }, { "code": null, "e": 3979, "s": 3848, "text": "This works for three-digit numbers too. In this case, the base number is between our numbers, so the product is a negative number." }, { "code": null, "e": 4092, "s": 3979, "text": "497 x 504 = (500 – 3) x (500 + 4)= (500) x (500 + 4 - 3) + (-3 x 4)= 500 x 501 - 12= 250,000 + 500 – 12= 250,488" }, { "code": null, "e": 4205, "s": 4092, "text": "You can simplify some equations before you even start. For example, divide both the divisor and dividend by two." }, { "code": null, "e": 4237, "s": 4205, "text": "898 / 4 = 449 / 2 = 224 and 1⁄2" }, { "code": null, "e": 4307, "s": 4237, "text": "Note with this method, you have to write the remainder as a fraction:" }, { "code": null, "e": 4390, "s": 4307, "text": "898/4 has a remainder of 2 — divided by 4449/2 has a remainder of 1 — divided by 2" }, { "code": null, "e": 4454, "s": 4390, "text": "The fraction is the same, but the absolute number is different." }, { "code": null, "e": 4563, "s": 4454, "text": "When dividing by 5, modify the equation by multiplying by 2. It is much easier to divide by 10. For example:" }, { "code": null, "e": 4589, "s": 4563, "text": "1753/5 = 3506 / 10= 350.6" }, { "code": null, "e": 4650, "s": 4589, "text": "There are many ways to quickly whether a number is a factor." }, { "code": null, "e": 4673, "s": 4650, "text": "2: The number is even." }, { "code": null, "e": 4721, "s": 4673, "text": "Example 28790 is even, so it is divisible by 2." }, { "code": null, "e": 4765, "s": 4721, "text": "3: The sum of the digits is divisible by 3." }, { "code": null, "e": 4847, "s": 4765, "text": "Example: 1281 -> 1+2+8+1 = 12 -> 12 is a multiple of 3, so 1281 is divisible by 3" }, { "code": null, "e": 4980, "s": 4847, "text": "4: The last two digits are divisible by 4. Why does this work? 100 is a multiple of 4, so we only have to check the last two digits." }, { "code": null, "e": 5044, "s": 4980, "text": "Example: 1472, 72 is divisible by 4, so 1472 is divisible by 4." }, { "code": null, "e": 5074, "s": 5044, "text": "5: The number ends in 5 or 0." }, { "code": null, "e": 5125, "s": 5074, "text": "Example: 575 ends in 5, so it is divisible by zero" }, { "code": null, "e": 5236, "s": 5125, "text": "6: The number is even, and the sum of the digits is divisible by 3. 6 is 3 x 2, so the rules of 2 and 3 apply." }, { "code": null, "e": 5323, "s": 5236, "text": "Example: 774 is even and 7+7+4 = 18 -> 18 is divisible by 3, so 774 is divisible by 6." }, { "code": null, "e": 5527, "s": 5323, "text": "7: Add or subtract a multiple of 7 to your number so that it ends in zero. Drop the last digit with the zero and repeat the process. Continue until you can determine whether the result is divisible by 7." }, { "code": null, "e": 5634, "s": 5527, "text": "Example: 2702 add 98 (7 x 14) -> 2800, drop the zeroes-> 28 is a multiple of 7, so 2702 is divisible by 7." }, { "code": null, "e": 5679, "s": 5634, "text": "8: The last three digits are divisible by 8." }, { "code": null, "e": 5882, "s": 5679, "text": "Example: 79256, 256 is divisible by 8, so 79256 is divisible by 8.(Alternate rule: if the hundreds digit is even, last 2 digits divisble by 8, if hundreds digit is odd, last 2 digits + 4 divisible by 8)" }, { "code": null, "e": 5996, "s": 5882, "text": "9: The same rule as 3, but with 9. If the sum of the digits is divisible by 9, then the number is divisible by 9." }, { "code": null, "e": 6081, "s": 5996, "text": "Example: 13671 -> 1+3+6+7+1 = 18 -> 18 is divisible by 9, so 13671 is divisible by 9" }, { "code": null, "e": 6107, "s": 6081, "text": "10: The number ends in 0." }, { "code": null, "e": 6154, "s": 6107, "text": "Example: 280 ends in 0, 280 is divisible by 10" }, { "code": null, "e": 6347, "s": 6154, "text": "11: Similar rule to 3 and 9, start at the right digit and alternate subtracting and adding the remaining digits. If the answer is zero, or a multiple of 11, then the number is divisible by 11." }, { "code": null, "e": 6418, "s": 6347, "text": "Example: 12727 -> 1 - 2 + 7 - 2 + 7 = 11, so 12727 is divisible by 11." }, { "code": null, "e": 6466, "s": 6418, "text": "You can check out some additional methods here." }, { "code": null, "e": 6485, "s": 6466, "text": "Example:-> 10520/9" }, { "code": null, "e": 6819, "s": 6485, "text": "Write the first digit above the equation and write an “R” (for remainder) above the last digit. Add the number you just wrote and the number diagonally below and to the right of it. Write this new number in the second spot. Add that number to the number diagonally below and to the right. Continue this process until you reach the R." }, { "code": null, "e": 6896, "s": 6819, "text": "Finally, add the last digit to the number below the R to get your remainder." }, { "code": null, "e": 6924, "s": 6896, "text": "10520/9= 1168 R8or 1168.889" }, { "code": null, "e": 6948, "s": 6924, "text": "Here’s another example:" }, { "code": null, "e": 6959, "s": 6948, "text": "-> 57423/9" }, { "code": null, "e": 7344, "s": 6959, "text": "This time after we’ve completed the first step, the sum of our first number and the number diagonally below and to the right is larger than ten (5+7 =12). We put a one above the first digit and subtract nine from it. (We are dividing by a base of nine, so we subtract nine rather than ten). Place the resulting number in the second position (12–9 = 3). Continue with the same process." }, { "code": null, "e": 7558, "s": 7344, "text": "In this example, our remainder is larger than 9 (9+3 = 12). Once again, we carry a one above the previous digit and subtract nine from the remainder, leaving us with three. Now add the result and the carry digits." }, { "code": null, "e": 7589, "s": 7558, "text": "57423 / 9 = 6380 R3or 6380.333" }, { "code": null, "e": 7692, "s": 7589, "text": "Percentages are associative, so sometimes reversing the question’s order makes it easier to calculate." }, { "code": null, "e": 7787, "s": 7692, "text": "Example: What’s 36% of 25 -> is the same as 25% of 36 -> 25% is 1⁄4 -> 36/4 = 9 36% of 25 is 9" }, { "code": null, "e": 7903, "s": 7787, "text": "As you can see with the use of 1⁄4 in the last example, it helps know fractions and how they relate to percentages." }, { "code": null, "e": 8367, "s": 7903, "text": "1/2 = 50%1/3 = 33.33%, 2/3 = 66.67%,1/4 = 25%, 3/4= 75%1/5 = 20%, 2/5 = 40% ...1/6 = 16.67%, 5/6 = 83.33% (2/6 = 1/3, 3/6 = 1/2, 4/6 = 2/3)1/7 = 14.2857%, 2/7 = 28.5714%, 3/7 = 42.8571%, 4/7 = 57.1428% (note the recurring .142857 pattern)1/8 = 12.5%, 3/8 = 37.5%, 5/8 = 62.5%, 7/8 = 87.5%1/9 = 11.11%, 2/9 = 22.22%, 3/9 = 33.33% ...1/10 = 10%, 2/10 = 20% ...1/11 = 9.09%, 2/11 = 18.18%, 3/11 = 27.27% ...1/12 = 8.33%, 5/12 = 41.67%, 7/12 = 58.33%, 11/12 = 91.67%" }, { "code": null, "e": 8603, "s": 8367, "text": "The rule of 72 provides an estimate of how many years it will take an investment to double in value at a given percentage return. It works by dividing 72 by the percentage, with the answer as the number of years it will take to double." }, { "code": null, "e": 8700, "s": 8603, "text": "2% -> 72/2 = 36, approximately 36 years to double8% -> 72/8 = 9, approximately 9 years to double" }, { "code": null, "e": 8864, "s": 8700, "text": "Note that the rule of 72 is a guideline based on the natural log of 2 — which gives 0.693. So a rule of 69.3 would be more accurate, but 72 is easier to calculate." }, { "code": null, "e": 8965, "s": 8864, "text": "There is also a rule of 114 for tripling an investment and a rule of 144 for quadrupling your money." }, { "code": null, "e": 9124, "s": 8965, "text": "I found two books by Arthur Benjamin to be helpful on this topic. Many of the examples in this blog were inspired by these books. You can check them out here." }, { "code": null, "e": 9139, "s": 9124, "text": "www.amazon.com" }, { "code": null, "e": 9224, "s": 9139, "text": "https://www.amazon.com/Secrets-Mental-Math-Mathemagicians-Calculation/dp/0307338401/" } ]
How to submit a form in Selenium webdriver if submit button can't be identified?
We can submit a form in Selenium webdriver even if the submit button cannot be identified. This can be achieved by locating any element within the form tag and the applying submit method on it. A form in the html code is identified by the <form> tag. Let us investigate the html code of element with in a form tag − In the above example, we shall try to submit the form with the help of the Email or Password field and not by clicking on the Sign in button. driver.findElement(By.className("input__input")).sendKeys("96968547"); driver.findElement(By.className("session_password")).sendKeys("test123"); driver.findElement(By.className("session_password")).submit(); import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class SubmitFrm{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.linkedin.com/"); // identify element within form WebElement m=driver.findElement(By.id("session_key")); m.sendKeys("96968547"); WebElement n=driver.findElement(By.id("session_password")); n.sendKeys("test12"); //submit form n.submit(); Thread.sleep(1000); System.out.println("Page title: " + driver.getTitle()); driver.close(); } }
[ { "code": null, "e": 1313, "s": 1062, "text": "We can submit a form in Selenium webdriver even if the submit button cannot be identified. This can be achieved by locating any element within the form tag and the applying submit method on it. A form in the html code is identified by the <form> tag." }, { "code": null, "e": 1378, "s": 1313, "text": "Let us investigate the html code of element with in a form tag −" }, { "code": null, "e": 1520, "s": 1378, "text": "In the above example, we shall try to submit the form with the help of the Email or Password field and not by clicking on the Sign in button." }, { "code": null, "e": 1728, "s": 1520, "text": "driver.findElement(By.className(\"input__input\")).sendKeys(\"96968547\");\ndriver.findElement(By.className(\"session_password\")).sendKeys(\"test123\");\ndriver.findElement(By.className(\"session_password\")).submit();" }, { "code": null, "e": 2689, "s": 1728, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class SubmitFrm{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.linkedin.com/\");\n // identify element within form\n WebElement m=driver.findElement(By.id(\"session_key\"));\n m.sendKeys(\"96968547\");\n WebElement n=driver.findElement(By.id(\"session_password\"));\n n.sendKeys(\"test12\");\n //submit form\n n.submit();\n Thread.sleep(1000);\n System.out.println(\"Page title: \" + driver.getTitle());\n driver.close();\n }\n}" } ]
How to update MongoDB collection using $toLower?
There is a $toLower operator in MongoDB to be used as part of aggregate framework. But, we can also use the for loop to iterate over the specific field and update one by one. Let us first create a collection with documents > db.toLowerDemo.insertOne({"StudentId":101,"StudentName":"John"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1b4515e86fd1496b38bf") } > db.toLowerDemo.insertOne({"StudentId":102,"StudentName":"Larry"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1b4b15e86fd1496b38c0") } > db.toLowerDemo.insertOne({"StudentId":103,"StudentName":"CHris"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1b5115e86fd1496b38c1") } > db.toLowerDemo.insertOne({"StudentId":104,"StudentName":"ROBERT"}); { "acknowledged" : true, "insertedId" : ObjectId("5c9b1b5a15e86fd1496b38c2") } Following is the query to display all documents from a collection with the help of find() method > db.toLowerDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9b1b4515e86fd1496b38bf"), "StudentId" : 101, "StudentName" : "John" } { "_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"), "StudentId" : 102, "StudentName" : "Larry" } { "_id" : ObjectId("5c9b1b5115e86fd1496b38c1"), "StudentId" : 103, "StudentName" : "CHris" } { "_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"), "StudentId" : 104, "StudentName" : "ROBERT" } Following is the query to update MongoDB like $toLower > db.toLowerDemo.find().forEach( ... function(lower) { ... lower.StudentName = lower.StudentName.toLowerCase(); ... db.toLowerDemo.save(lower); ... } ... ); Let us check the document once again from the above collection. Following is the query > db.toLowerDemo.find().pretty(); This will produce the following output { "_id" : ObjectId("5c9b1b4515e86fd1496b38bf"), "StudentId" : 101, "StudentName" : "john" } { "_id" : ObjectId("5c9b1b4b15e86fd1496b38c0"), "StudentId" : 102, "StudentName" : "larry" } { "_id" : ObjectId("5c9b1b5115e86fd1496b38c1"), "StudentId" : 103, "StudentName" : "chris" } { "_id" : ObjectId("5c9b1b5a15e86fd1496b38c2"), "StudentId" : 104, "StudentName" : "robert" }
[ { "code": null, "e": 1237, "s": 1062, "text": "There is a $toLower operator in MongoDB to be used as part of aggregate framework. But, we can also use the for loop to iterate over the specific field and update one by one." }, { "code": null, "e": 1285, "s": 1237, "text": "Let us first create a collection with documents" }, { "code": null, "e": 1901, "s": 1285, "text": "> db.toLowerDemo.insertOne({\"StudentId\":101,\"StudentName\":\"John\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b1b4515e86fd1496b38bf\")\n}\n> db.toLowerDemo.insertOne({\"StudentId\":102,\"StudentName\":\"Larry\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b1b4b15e86fd1496b38c0\")\n}\n> db.toLowerDemo.insertOne({\"StudentId\":103,\"StudentName\":\"CHris\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b1b5115e86fd1496b38c1\")\n}\n> db.toLowerDemo.insertOne({\"StudentId\":104,\"StudentName\":\"ROBERT\"});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c9b1b5a15e86fd1496b38c2\")\n}" }, { "code": null, "e": 1998, "s": 1901, "text": "Following is the query to display all documents from a collection with the help of find() method" }, { "code": null, "e": 2032, "s": 1998, "text": "> db.toLowerDemo.find().pretty();" }, { "code": null, "e": 2071, "s": 2032, "text": "This will produce the following output" }, { "code": null, "e": 2479, "s": 2071, "text": "{\n \"_id\" : ObjectId(\"5c9b1b4515e86fd1496b38bf\"),\n \"StudentId\" : 101,\n \"StudentName\" : \"John\"\n}\n{\n \"_id\" : ObjectId(\"5c9b1b4b15e86fd1496b38c0\"),\n \"StudentId\" : 102,\n \"StudentName\" : \"Larry\"\n}\n{\n \"_id\" : ObjectId(\"5c9b1b5115e86fd1496b38c1\"),\n \"StudentId\" : 103,\n \"StudentName\" : \"CHris\"\n}\n{\n \"_id\" : ObjectId(\"5c9b1b5a15e86fd1496b38c2\"),\n \"StudentId\" : 104,\n \"StudentName\" : \"ROBERT\"\n}" }, { "code": null, "e": 2534, "s": 2479, "text": "Following is the query to update MongoDB like $toLower" }, { "code": null, "e": 2709, "s": 2534, "text": "> db.toLowerDemo.find().forEach(\n... function(lower) {\n... lower.StudentName = lower.StudentName.toLowerCase();\n... db.toLowerDemo.save(lower);\n... }\n... );" }, { "code": null, "e": 2796, "s": 2709, "text": "Let us check the document once again from the above collection. Following is the query" }, { "code": null, "e": 2830, "s": 2796, "text": "> db.toLowerDemo.find().pretty();" }, { "code": null, "e": 2869, "s": 2830, "text": "This will produce the following output" }, { "code": null, "e": 3277, "s": 2869, "text": "{\n \"_id\" : ObjectId(\"5c9b1b4515e86fd1496b38bf\"),\n \"StudentId\" : 101,\n \"StudentName\" : \"john\"\n}\n{\n \"_id\" : ObjectId(\"5c9b1b4b15e86fd1496b38c0\"),\n \"StudentId\" : 102,\n \"StudentName\" : \"larry\"\n}\n{\n \"_id\" : ObjectId(\"5c9b1b5115e86fd1496b38c1\"),\n \"StudentId\" : 103,\n \"StudentName\" : \"chris\"\n}\n{\n \"_id\" : ObjectId(\"5c9b1b5a15e86fd1496b38c2\"),\n \"StudentId\" : 104,\n \"StudentName\" : \"robert\"\n}" } ]
Unpacking tuple of lists in Python
When it is required to unpack a tuple of list, the 'reduce' method can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access. A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on). A tuple of list contains multiple lists, which are enclosed in '(' and ')'. The 'reduce' method is used to apply a specific method (that is passed as an argument to it) to all the values in the iterable. This method is present in the 'functools' module. Below is a demonstration for the same − Live Demo from functools import reduce import operator def unpack_tuple(my_tup): return (reduce(operator.add, my_tup)) my_tuple = (['h', 'jane'], ['m', 'may']) print("The tuple of list is") print(my_tuple) print("After unpacking, it is") print(unpack_tuple(my_tuple)) The tuple of list is (['h', 'jane'], ['m', 'may']) After unpacking, it is ['h', 'jane', 'm', 'may'] The required packages are imported into the environment. A function named 'unpack_tuple' is defined that takes a tuple as parameter. It uses the 'reduce' method, and calls the 'add' method on all elements inside the tuple. Now, a tuple of list is defined, and is displayed on the console. This function is called by passing the tuple of list as parameter. This operation's data is stored in a variable. This variable is the output that is displayed on the console.
[ { "code": null, "e": 1381, "s": 1062, "text": "When it is required to unpack a tuple of list, the 'reduce' method can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements. If we try to change the elements, it results in an error. They are important contains since they ensure read-only access." }, { "code": null, "e": 1508, "s": 1381, "text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)." }, { "code": null, "e": 1584, "s": 1508, "text": "A tuple of list contains multiple lists, which are enclosed in '(' and ')'." }, { "code": null, "e": 1762, "s": 1584, "text": "The 'reduce' method is used to apply a specific method (that is passed as an argument to it) to all the values in the iterable. This method is present in the 'functools' module." }, { "code": null, "e": 1802, "s": 1762, "text": "Below is a demonstration for the same −" }, { "code": null, "e": 1812, "s": 1802, "text": "Live Demo" }, { "code": null, "e": 2077, "s": 1812, "text": "from functools import reduce\nimport operator\ndef unpack_tuple(my_tup): \n return (reduce(operator.add, my_tup))\n\nmy_tuple = (['h', 'jane'], ['m', 'may'])\n\nprint(\"The tuple of list is\")\nprint(my_tuple)\nprint(\"After unpacking, it is\")\nprint(unpack_tuple(my_tuple))" }, { "code": null, "e": 2177, "s": 2077, "text": "The tuple of list is\n(['h', 'jane'], ['m', 'may'])\nAfter unpacking, it is\n['h', 'jane', 'm', 'may']" }, { "code": null, "e": 2234, "s": 2177, "text": "The required packages are imported into the environment." }, { "code": null, "e": 2310, "s": 2234, "text": "A function named 'unpack_tuple' is defined that takes a tuple as parameter." }, { "code": null, "e": 2400, "s": 2310, "text": "It uses the 'reduce' method, and calls the 'add' method on all elements inside the tuple." }, { "code": null, "e": 2466, "s": 2400, "text": "Now, a tuple of list is defined, and is displayed on the console." }, { "code": null, "e": 2533, "s": 2466, "text": "This function is called by passing the tuple of list as parameter." }, { "code": null, "e": 2580, "s": 2533, "text": "This operation's data is stored in a variable." }, { "code": null, "e": 2642, "s": 2580, "text": "This variable is the output that is displayed on the console." } ]
LESS - Escaping
It builds selectors dynamically and uses property or variable value as arbitrary string. The following example demonstrates the use of escaping in the LESS file − <html> <head> <title>Less Escaping</title> <link rel = "stylesheet" type = "text/css" href = "style.css" /> </head> <body> <h1>Example using Escaping</h1> <p>LESS enables customizable, manageable and reusable style sheet for web site.</p> </body> </html> Now create the style.less file. p { color: ~"green"; } You can compile the style.less file to style.css by using the following command − lessc style.less style.css Execute the above command, it will create the style.css file automatically with the following code − p { color: green; } Anything written inside ~"some_text" will be displayed as some_text after compiling the LESS code to CSS code. Let us now perform the following steps to see how the above code works − Save the above html code in the escaping.html file. Save the above html code in the escaping.html file. Open this HTML file in a browser, the following output will get displayed. Open this HTML file in a browser, the following output will get displayed. 20 Lectures 1 hours Anadi Sharma 44 Lectures 7.5 hours Eduonix Learning Solutions 17 Lectures 2 hours Zach Miller 23 Lectures 1.5 hours Zach Miller 34 Lectures 4 hours Syed Raza 31 Lectures 3 hours Harshit Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2639, "s": 2550, "text": "It builds selectors dynamically and uses property or variable value as arbitrary string." }, { "code": null, "e": 2713, "s": 2639, "text": "The following example demonstrates the use of escaping in the LESS file −" }, { "code": null, "e": 3008, "s": 2713, "text": "<html>\n <head>\n <title>Less Escaping</title>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\" />\n </head>\n \n <body>\n <h1>Example using Escaping</h1>\n <p>LESS enables customizable, manageable and reusable style sheet for web site.</p>\n </body>\n</html>" }, { "code": null, "e": 3040, "s": 3008, "text": "Now create the style.less file." }, { "code": null, "e": 3066, "s": 3040, "text": "p {\n color: ~\"green\";\n}" }, { "code": null, "e": 3148, "s": 3066, "text": "You can compile the style.less file to style.css by using the following command −" }, { "code": null, "e": 3176, "s": 3148, "text": "lessc style.less style.css\n" }, { "code": null, "e": 3277, "s": 3176, "text": "Execute the above command, it will create the style.css file automatically with the following code −" }, { "code": null, "e": 3300, "s": 3277, "text": "p {\n color: green;\n}" }, { "code": null, "e": 3411, "s": 3300, "text": "Anything written inside ~\"some_text\" will be displayed as some_text after compiling the LESS code to CSS code." }, { "code": null, "e": 3484, "s": 3411, "text": "Let us now perform the following steps to see how the above code works −" }, { "code": null, "e": 3536, "s": 3484, "text": "Save the above html code in the escaping.html file." }, { "code": null, "e": 3588, "s": 3536, "text": "Save the above html code in the escaping.html file." }, { "code": null, "e": 3663, "s": 3588, "text": "Open this HTML file in a browser, the following output will get displayed." }, { "code": null, "e": 3738, "s": 3663, "text": "Open this HTML file in a browser, the following output will get displayed." }, { "code": null, "e": 3771, "s": 3738, "text": "\n 20 Lectures \n 1 hours \n" }, { "code": null, "e": 3785, "s": 3771, "text": " Anadi Sharma" }, { "code": null, "e": 3820, "s": 3785, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 3848, "s": 3820, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3881, "s": 3848, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 3894, "s": 3881, "text": " Zach Miller" }, { "code": null, "e": 3929, "s": 3894, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3942, "s": 3929, "text": " Zach Miller" }, { "code": null, "e": 3975, "s": 3942, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3986, "s": 3975, "text": " Syed Raza" }, { "code": null, "e": 4019, "s": 3986, "text": "\n 31 Lectures \n 3 hours \n" }, { "code": null, "e": 4039, "s": 4019, "text": " Harshit Srivastava" }, { "code": null, "e": 4046, "s": 4039, "text": " Print" }, { "code": null, "e": 4057, "s": 4046, "text": " Add Notes" } ]
How Are Convolutions Actually Performed Under the Hood? | by Anirudh Shenoy | Towards Data Science
Convolutions have become a fundamental part of modern neural networks because of their ability to capture local information and reduce the number of parameters with weight sharing. Since almost all vision-based models (and a few NLP-models) use convolutions of one form or the other, it’s obvious that we would like to make these operations as fast as possible. To emphasis the need for fast convolutions, here’s a profiler output of a simple network with a single 2D convolution layer followed by a Fully Connected layer: The convolutional layer followed by the linear layer (addmm) are responsible for ~ 90% of the total execution time. As a consequence, it’s no surprise that several tricks have been developed to speed up this computation as much as possible. In this blog, we’ll look at 2 tricks that PyTorch and TensorFlow use to make convolutions significantly faster. We’ll use 2D convolutions since that’s the easiest to visualize, but the exact same concept applies to 1D and 3D convolutions Let’s start with a naive implementation for 2D convolution. We’ll use a simple 2x2 kernel with a 3x3 input matrix (with 1 channel): input_matrixarray([[3., 9., 0.], [2., 8., 1.], [1., 4., 8.]], dtype=float32)kernelarray([[8., 9.], [4., 4.]], dtype=float32)biasarray([0.06], dtype=float32) The naive implementation is quite simple to understand, we simply traverse the input matrix and pull out “windows” that are equal to the shape of the kernel. For each window, we do simple element-wise multiplication with the kernel and sum up all the values. Finally, before returning the result we add the bias term to each element of the output. We can quickly verify that we’re getting the correct result by checking the output with PyTorch’s own conv2d layer. naive_conv_op = conv_2d(input_matrix, kernel, bias)print(naive_conv_op)torch_conv = nn.Conv2d(1, 1, 2)torch_conv_op = torch_conv(input_matrix)print(torch_conv_op)Output:naive_conv_oparray([[145.06, 108.06], [108.06, 121.06]])torch_conv_optensor([[[[145.07, 108.07], [108.07, 121.07]]]]) And here’s the execution time for both of them: %%timeitconv_2d(input_matrix, kernel, bias)%%timeittorch_conv(input_matrix)Output:Naive Conv:26.9 μs ± 1.34 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)Torch Conv:59.5 μs ± 935 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) Now let’s check how the execution time changes when the kernel size is kept the same and the size of the input matrix is slowly varied. The 2 for-loops in our implementation are responsible for O(n2) execution time and as the input size increases beyond 250 x 250, Naive Conv takes 1–3 secs per matrix. If we had a huge network like Inception Net with hundreds of convolutions and thousands of large input matrices, naive convolution would be an absolutely terrible idea. However, notice that PyTorch’s own implementation scales very well with the input matrix size. Clearly, PyTorch does convolutions differently. While multiplying each window with the kernel we did 2 operations: Multiplied the termsAdded them all together. Multiplied the terms Added them all together. ....and we did this for each window in the input matrix. Now the important question to ask here is: Can we vectorize this entire operation? The answer is Yes and that’s exactly what im2col helps us do (which stands for Image Block to Column) Simply put, im2col is a technique where we take each window, flatten it out and stack them as columns in a matrix. Now, if we flatten out the kernel into a row vector and do matrix multiplication between the two, we should get the exact same result after reshaping the output. Let’s try it out: im2col(input_matrix, kernel)Output:array([[3, 9, 2, 8], [9, 0, 8, 1], [2, 8, 1, 4], [8, 1, 4, 8]]) And now we flatten the kernel and do matrix multiplication: output_shape = (input_matrix.shape[0] - kernel.shape[0]) + 1im2col_matrix = im2col(input_matrix, kernel) im2col_conv = np.dot(kernel.flatten(), im2col_matrix) + biasim2col_conv = im2col_conv.reshape(output_shape,output_shape)print(im2col_conv)torch_conv = nn.Conv2d(1, 1, 2)torch_conv_op = torch_conv(input_matrix)print(torch_conv_op)Output:im2col_convarray([[145.06, 108.06], [108.06, 121.06]])torch_conv_optensor([[[[145.07, 108.07], [108.07, 121.07]]]]) Now let’s check how it scales: Vectorizing definitely helped but there’s still room for improvement. Before we move on to the next trick, let’s see why vectorizing actually helps. All modern CPUs and GPUs come with optimized matrix algebra libraries that allow code to take advantage of hardware acceleration. These libraries fall under the umbrella term of BLAS or Basic Linear Algebra Subroutines. When we vectorize code and call np.dot() it allows numpy to use the BLAS Library allowing for faster execution. In fact, in the earlier profiler output, you might have seen this: MKLDNN stands for Math Kernel Library for Deep Neural Networks which is Intel’s BLAS library. Since I ran the PyTorch model on my Intel i7, PyTorch automatically called Intel’s BLAS library. If you ran this on an Nvidia GPU, PyTorch would have used cuBLAS (Nvidia’s BLAS library). The next trick involves getting rid of the 2- for loops and creating the im2col matrix efficiently. While creating the windows in im2col we still used 2 for loops to index the input matrix, which slows down execution. To understand how to improve this we need to take a look at how numpy arrays are stored in memory. Just like all other arrays, numpy arrays are stored as contiguous blocks in memory. Each numpy array also has a .strides attribute that tells us how many bytes need to be jumped to access the next element. For eg: x = np.arange(10, dtype = 'int64')print(x)print(x.strides)Output:xarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])x.strides(8,) Each element is int64 i.e. 64bits or 8bytes and this is why x.strides tells us we need to jumpy 8bytes to access the next element in the array. When dealing with 2D arrays we get two stride values telling us how many bytes to jump in the column direction and the row direction. x = np.array([[1,2,3], [4,5,6], [7,8,9]])print(x)print(x.strides)Output:xarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])x.strides(24,8)#Jump 24bytes to access next row, 8bytes to access next column Now here’s the interesting part, numpy gives us the ability to change the strides of any numpy array by using a function callednp.lib.stride_tricks.as_strided. Based on what stride values we provide, this function simply changes the way we look at the array in memory and generates a new “view”. Here’s an example: x = np.array([[1,2,3], [4,5,6], [7,8,9]])print(x)x_newview = np.lib.stride_tricks.as_strided(x, shape = (5, 4), strides = (8,8))print(x_newview)Output:Xarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])X_newviewarray([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]]) Instead of jumping 24bytes (3 elements) to start the next row we used as_strided to jump only 8 bytes (1 element) when starting the next row. Using the shape parameter we can also set the output shape as needed. Note: As mentioned earlier, as_strided changes the way we look at the array in the memory. This means if we change a value in the “view” it changes the value in memory which changes the element in the original matrix. X_newview[1,3] = -99print(X_newview)print(X)Output:X_newviewarray([[ 1, 2, 3, 4], [ 2, 3, 4, -99], [ 3, 4, -99, 6], [ 4, -99, 6, 7], [-99, 6, 7, 8]])Xarray([[ 1, 2, 3], [ 4, -99, 6], [ 7, 8, 9]]) Since as_strided does not use any loops to create these “views” we can use it to efficiently generate the windows for convolution. All we need to do is calculate the right stride values and output shape and as_strided does the rest for us. However, if we provide wrong stride values,as_strided will access memory locations that are outside the array and return junk values. Luckily, the view_as_windows function in the scikit-images library does all the heavy lifting for us by calculating the shape and stride values automatically while using as_strided in the background: from skimage.util.shape import view_as_windowsinput_matrix = np.array([[3,9,0], [2, 8, 1], [1,4,8]])print(input_matrix)kernel = np.array([[8,9], [4,4]])print(kernel)windows = view_as_windows(x, kernel.shape)print(windows)Output:input_matrixarray([[3, 9, 0], [2, 8, 1], [1, 4, 8]])kernelarray([[8, 9], [4, 4]])windowsarray([[[[3, 9], [2, 8]], [[9, 0], [8, 1]]], [[[2, 8], [1, 4]], [[8, 1], [4, 8]]]]) And now we just reshape: output_shape = (input_matrix.shape[0] - kernel.shape[0]) + 1windows = windows.reshape(output_shape**2, kernel.shape[0]*2)print(windows)Output:windowsarray([[3, 9, 2, 8], [9, 0, 8, 1], [2, 8, 1, 4], [8, 1, 4, 8]]) Here’s the final function that does all of these: Now we can do matrix multiplication, in the same way we did previously: output_shape = (input_matrix.shape[0] - kernel.shape[0]) + 1mem_strided_mat = memory_strided_im2col(input_matrix, kernel) mem_strided_conv = np.dot(kernel.flatten(), mem_strided_mat) + biasmem_strided_conv = mem_strided_conv.reshape(output_shape, output_shape)print(mem_strided_conv)torch_conv = nn.Conv2d(1, 1, 2)torch_conv_op = torch_conv(input_matrix)print(torch_conv_op)Output:mem_strided_convarray([[145.06, 108.06], [108.06, 121.06]])torch_conv_optensor([[[[145.07, 108.07], [108.07, 121.07]]]]) Let’s check how it compares against all the other implementations so far: Using as_strided has significantly increased the speed of our implementation! In fact, it’s almost as fast as PyTorch. Also, if you noticed in the profiler output, PyTorch uses its own as_strided function before convolution: Since we need to create columns for each window of the input matrix, the im2col matrix ends up consuming more memory than the naive implementation. However, the improvements in speed(shown in table below) far outweigh the difficulties with increased memory consumption. Here’s a summary of the execution times for all implementations. The kernel size (2 x 2) was held constant while the input size was changed. I ran all of these on my Intel i7 processor. It’s incredible that we were able to get almost 150x improvement over Naive convolution with just 2 simple tricks. The PyTorch implementation is still 2x faster than our Memory Strided im2col implementation. This is most likely because PyTorch has its own tensor implementation that might be optimized for bigger matrices. In fact, our implementation is faster than PyTorch for matrix sizes below 50 x 50. Although we used only PyTorch here, TensorFlow also performs the exact same set of operations while performing convolutions (docs). And finally, here’s how our implementation would change when padding, strides or 1D/3D convolutions are used: Padding: If we added padding it would make no difference to our implementation, as padding is generally applied before convolution. However, the output shape would have to be correctly calculated. Strides: Here we assumed a stride of 1. A larger stride would just slide the window with bigger jumps, which means the strides in as_strided would have to be re-calculated. However, the concept remains the same. ( In fact, view_as_windows has a step parameter that takes care of strides as well. ) More Filters: In our examples, we assumed a single filter for the kernel. If we had more filters, each filter would be flattened out to give us a matrix instead of vector. Next, we would multiply this matrix with the im2col matrix. This means we would multiply a matrix by a matrix instead of vector by matrix to get the output. 1D or 3D Convolution: The columns in the im2col matrix would just be shorter or taller since the size of the window changes (depending on the kernel as well). I hope you enjoyed and found this useful! Feel free to connect with me for any questions or comments. Gist with all code: https://gist.github.com/anirudhshenoy/089a70deed944d0ca7ab0b6a5eb5a7f1 References: [1] Lecture 11 CS231N: Fei-Fei Li & Andrej Karpathy & Justin Johnson http://cs231n.stanford.edu/slides/2016/winter1516_lecture11.pdf [2] https://stackoverflow.com/questions/53097952/how-to-understand-numpy-strides-for-layman [3] TensorFlow Conv2D documentation: https://www.tensorflow.org/api_docs/python/tf/nn/conv2d
[ { "code": null, "e": 534, "s": 172, "text": "Convolutions have become a fundamental part of modern neural networks because of their ability to capture local information and reduce the number of parameters with weight sharing. Since almost all vision-based models (and a few NLP-models) use convolutions of one form or the other, it’s obvious that we would like to make these operations as fast as possible." }, { "code": null, "e": 695, "s": 534, "text": "To emphasis the need for fast convolutions, here’s a profiler output of a simple network with a single 2D convolution layer followed by a Fully Connected layer:" }, { "code": null, "e": 936, "s": 695, "text": "The convolutional layer followed by the linear layer (addmm) are responsible for ~ 90% of the total execution time. As a consequence, it’s no surprise that several tricks have been developed to speed up this computation as much as possible." }, { "code": null, "e": 1174, "s": 936, "text": "In this blog, we’ll look at 2 tricks that PyTorch and TensorFlow use to make convolutions significantly faster. We’ll use 2D convolutions since that’s the easiest to visualize, but the exact same concept applies to 1D and 3D convolutions" }, { "code": null, "e": 1306, "s": 1174, "text": "Let’s start with a naive implementation for 2D convolution. We’ll use a simple 2x2 kernel with a 3x3 input matrix (with 1 channel):" }, { "code": null, "e": 1481, "s": 1306, "text": "input_matrixarray([[3., 9., 0.], [2., 8., 1.], [1., 4., 8.]], dtype=float32)kernelarray([[8., 9.], [4., 4.]], dtype=float32)biasarray([0.06], dtype=float32)" }, { "code": null, "e": 1829, "s": 1481, "text": "The naive implementation is quite simple to understand, we simply traverse the input matrix and pull out “windows” that are equal to the shape of the kernel. For each window, we do simple element-wise multiplication with the kernel and sum up all the values. Finally, before returning the result we add the bias term to each element of the output." }, { "code": null, "e": 1945, "s": 1829, "text": "We can quickly verify that we’re getting the correct result by checking the output with PyTorch’s own conv2d layer." }, { "code": null, "e": 2247, "s": 1945, "text": "naive_conv_op = conv_2d(input_matrix, kernel, bias)print(naive_conv_op)torch_conv = nn.Conv2d(1, 1, 2)torch_conv_op = torch_conv(input_matrix)print(torch_conv_op)Output:naive_conv_oparray([[145.06, 108.06], [108.06, 121.06]])torch_conv_optensor([[[[145.07, 108.07], [108.07, 121.07]]]])" }, { "code": null, "e": 2295, "s": 2247, "text": "And here’s the execution time for both of them:" }, { "code": null, "e": 2545, "s": 2295, "text": "%%timeitconv_2d(input_matrix, kernel, bias)%%timeittorch_conv(input_matrix)Output:Naive Conv:26.9 μs ± 1.34 μs per loop (mean ± std. dev. of 7 runs, 10000 loops each)Torch Conv:59.5 μs ± 935 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)" }, { "code": null, "e": 2681, "s": 2545, "text": "Now let’s check how the execution time changes when the kernel size is kept the same and the size of the input matrix is slowly varied." }, { "code": null, "e": 3017, "s": 2681, "text": "The 2 for-loops in our implementation are responsible for O(n2) execution time and as the input size increases beyond 250 x 250, Naive Conv takes 1–3 secs per matrix. If we had a huge network like Inception Net with hundreds of convolutions and thousands of large input matrices, naive convolution would be an absolutely terrible idea." }, { "code": null, "e": 3160, "s": 3017, "text": "However, notice that PyTorch’s own implementation scales very well with the input matrix size. Clearly, PyTorch does convolutions differently." }, { "code": null, "e": 3227, "s": 3160, "text": "While multiplying each window with the kernel we did 2 operations:" }, { "code": null, "e": 3272, "s": 3227, "text": "Multiplied the termsAdded them all together." }, { "code": null, "e": 3293, "s": 3272, "text": "Multiplied the terms" }, { "code": null, "e": 3318, "s": 3293, "text": "Added them all together." }, { "code": null, "e": 3375, "s": 3318, "text": "....and we did this for each window in the input matrix." }, { "code": null, "e": 3458, "s": 3375, "text": "Now the important question to ask here is: Can we vectorize this entire operation?" }, { "code": null, "e": 3560, "s": 3458, "text": "The answer is Yes and that’s exactly what im2col helps us do (which stands for Image Block to Column)" }, { "code": null, "e": 3837, "s": 3560, "text": "Simply put, im2col is a technique where we take each window, flatten it out and stack them as columns in a matrix. Now, if we flatten out the kernel into a row vector and do matrix multiplication between the two, we should get the exact same result after reshaping the output." }, { "code": null, "e": 3855, "s": 3837, "text": "Let’s try it out:" }, { "code": null, "e": 3972, "s": 3855, "text": "im2col(input_matrix, kernel)Output:array([[3, 9, 2, 8], [9, 0, 8, 1], [2, 8, 1, 4], [8, 1, 4, 8]])" }, { "code": null, "e": 4032, "s": 3972, "text": "And now we flatten the kernel and do matrix multiplication:" }, { "code": null, "e": 4504, "s": 4032, "text": "output_shape = (input_matrix.shape[0] - kernel.shape[0]) + 1im2col_matrix = im2col(input_matrix, kernel) im2col_conv = np.dot(kernel.flatten(), im2col_matrix) + biasim2col_conv = im2col_conv.reshape(output_shape,output_shape)print(im2col_conv)torch_conv = nn.Conv2d(1, 1, 2)torch_conv_op = torch_conv(input_matrix)print(torch_conv_op)Output:im2col_convarray([[145.06, 108.06], [108.06, 121.06]])torch_conv_optensor([[[[145.07, 108.07], [108.07, 121.07]]]])" }, { "code": null, "e": 4535, "s": 4504, "text": "Now let’s check how it scales:" }, { "code": null, "e": 4684, "s": 4535, "text": "Vectorizing definitely helped but there’s still room for improvement. Before we move on to the next trick, let’s see why vectorizing actually helps." }, { "code": null, "e": 5016, "s": 4684, "text": "All modern CPUs and GPUs come with optimized matrix algebra libraries that allow code to take advantage of hardware acceleration. These libraries fall under the umbrella term of BLAS or Basic Linear Algebra Subroutines. When we vectorize code and call np.dot() it allows numpy to use the BLAS Library allowing for faster execution." }, { "code": null, "e": 5083, "s": 5016, "text": "In fact, in the earlier profiler output, you might have seen this:" }, { "code": null, "e": 5364, "s": 5083, "text": "MKLDNN stands for Math Kernel Library for Deep Neural Networks which is Intel’s BLAS library. Since I ran the PyTorch model on my Intel i7, PyTorch automatically called Intel’s BLAS library. If you ran this on an Nvidia GPU, PyTorch would have used cuBLAS (Nvidia’s BLAS library)." }, { "code": null, "e": 5464, "s": 5364, "text": "The next trick involves getting rid of the 2- for loops and creating the im2col matrix efficiently." }, { "code": null, "e": 5681, "s": 5464, "text": "While creating the windows in im2col we still used 2 for loops to index the input matrix, which slows down execution. To understand how to improve this we need to take a look at how numpy arrays are stored in memory." }, { "code": null, "e": 5887, "s": 5681, "text": "Just like all other arrays, numpy arrays are stored as contiguous blocks in memory. Each numpy array also has a .strides attribute that tells us how many bytes need to be jumped to access the next element." }, { "code": null, "e": 5895, "s": 5887, "text": "For eg:" }, { "code": null, "e": 6012, "s": 5895, "text": "x = np.arange(10, dtype = 'int64')print(x)print(x.strides)Output:xarray([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])x.strides(8,)" }, { "code": null, "e": 6156, "s": 6012, "text": "Each element is int64 i.e. 64bits or 8bytes and this is why x.strides tells us we need to jumpy 8bytes to access the next element in the array." }, { "code": null, "e": 6290, "s": 6156, "text": "When dealing with 2D arrays we get two stride values telling us how many bytes to jump in the column direction and the row direction." }, { "code": null, "e": 6493, "s": 6290, "text": "x = np.array([[1,2,3], [4,5,6], [7,8,9]])print(x)print(x.strides)Output:xarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])x.strides(24,8)#Jump 24bytes to access next row, 8bytes to access next column" }, { "code": null, "e": 6789, "s": 6493, "text": "Now here’s the interesting part, numpy gives us the ability to change the strides of any numpy array by using a function callednp.lib.stride_tricks.as_strided. Based on what stride values we provide, this function simply changes the way we look at the array in memory and generates a new “view”." }, { "code": null, "e": 6808, "s": 6789, "text": "Here’s an example:" }, { "code": null, "e": 7123, "s": 6808, "text": "x = np.array([[1,2,3], [4,5,6], [7,8,9]])print(x)x_newview = np.lib.stride_tricks.as_strided(x, shape = (5, 4), strides = (8,8))print(x_newview)Output:Xarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])X_newviewarray([[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8]])" }, { "code": null, "e": 7335, "s": 7123, "text": "Instead of jumping 24bytes (3 elements) to start the next row we used as_strided to jump only 8 bytes (1 element) when starting the next row. Using the shape parameter we can also set the output shape as needed." }, { "code": null, "e": 7553, "s": 7335, "text": "Note: As mentioned earlier, as_strided changes the way we look at the array in the memory. This means if we change a value in the “view” it changes the value in memory which changes the element in the original matrix." }, { "code": null, "e": 7826, "s": 7553, "text": "X_newview[1,3] = -99print(X_newview)print(X)Output:X_newviewarray([[ 1, 2, 3, 4], [ 2, 3, 4, -99], [ 3, 4, -99, 6], [ 4, -99, 6, 7], [-99, 6, 7, 8]])Xarray([[ 1, 2, 3], [ 4, -99, 6], [ 7, 8, 9]])" }, { "code": null, "e": 8066, "s": 7826, "text": "Since as_strided does not use any loops to create these “views” we can use it to efficiently generate the windows for convolution. All we need to do is calculate the right stride values and output shape and as_strided does the rest for us." }, { "code": null, "e": 8400, "s": 8066, "text": "However, if we provide wrong stride values,as_strided will access memory locations that are outside the array and return junk values. Luckily, the view_as_windows function in the scikit-images library does all the heavy lifting for us by calculating the shape and stride values automatically while using as_strided in the background:" }, { "code": null, "e": 8870, "s": 8400, "text": "from skimage.util.shape import view_as_windowsinput_matrix = np.array([[3,9,0], [2, 8, 1], [1,4,8]])print(input_matrix)kernel = np.array([[8,9], [4,4]])print(kernel)windows = view_as_windows(x, kernel.shape)print(windows)Output:input_matrixarray([[3, 9, 0], [2, 8, 1], [1, 4, 8]])kernelarray([[8, 9], [4, 4]])windowsarray([[[[3, 9], [2, 8]], [[9, 0], [8, 1]]], [[[2, 8], [1, 4]], [[8, 1], [4, 8]]]])" }, { "code": null, "e": 8895, "s": 8870, "text": "And now we just reshape:" }, { "code": null, "e": 9126, "s": 8895, "text": "output_shape = (input_matrix.shape[0] - kernel.shape[0]) + 1windows = windows.reshape(output_shape**2, kernel.shape[0]*2)print(windows)Output:windowsarray([[3, 9, 2, 8], [9, 0, 8, 1], [2, 8, 1, 4], [8, 1, 4, 8]])" }, { "code": null, "e": 9176, "s": 9126, "text": "Here’s the final function that does all of these:" }, { "code": null, "e": 9248, "s": 9176, "text": "Now we can do matrix multiplication, in the same way we did previously:" }, { "code": null, "e": 9765, "s": 9248, "text": "output_shape = (input_matrix.shape[0] - kernel.shape[0]) + 1mem_strided_mat = memory_strided_im2col(input_matrix, kernel) mem_strided_conv = np.dot(kernel.flatten(), mem_strided_mat) + biasmem_strided_conv = mem_strided_conv.reshape(output_shape, output_shape)print(mem_strided_conv)torch_conv = nn.Conv2d(1, 1, 2)torch_conv_op = torch_conv(input_matrix)print(torch_conv_op)Output:mem_strided_convarray([[145.06, 108.06], [108.06, 121.06]])torch_conv_optensor([[[[145.07, 108.07], [108.07, 121.07]]]])" }, { "code": null, "e": 9839, "s": 9765, "text": "Let’s check how it compares against all the other implementations so far:" }, { "code": null, "e": 9958, "s": 9839, "text": "Using as_strided has significantly increased the speed of our implementation! In fact, it’s almost as fast as PyTorch." }, { "code": null, "e": 10064, "s": 9958, "text": "Also, if you noticed in the profiler output, PyTorch uses its own as_strided function before convolution:" }, { "code": null, "e": 10212, "s": 10064, "text": "Since we need to create columns for each window of the input matrix, the im2col matrix ends up consuming more memory than the naive implementation." }, { "code": null, "e": 10334, "s": 10212, "text": "However, the improvements in speed(shown in table below) far outweigh the difficulties with increased memory consumption." }, { "code": null, "e": 10520, "s": 10334, "text": "Here’s a summary of the execution times for all implementations. The kernel size (2 x 2) was held constant while the input size was changed. I ran all of these on my Intel i7 processor." }, { "code": null, "e": 10926, "s": 10520, "text": "It’s incredible that we were able to get almost 150x improvement over Naive convolution with just 2 simple tricks. The PyTorch implementation is still 2x faster than our Memory Strided im2col implementation. This is most likely because PyTorch has its own tensor implementation that might be optimized for bigger matrices. In fact, our implementation is faster than PyTorch for matrix sizes below 50 x 50." }, { "code": null, "e": 11058, "s": 10926, "text": "Although we used only PyTorch here, TensorFlow also performs the exact same set of operations while performing convolutions (docs)." }, { "code": null, "e": 11168, "s": 11058, "text": "And finally, here’s how our implementation would change when padding, strides or 1D/3D convolutions are used:" }, { "code": null, "e": 11365, "s": 11168, "text": "Padding: If we added padding it would make no difference to our implementation, as padding is generally applied before convolution. However, the output shape would have to be correctly calculated." }, { "code": null, "e": 11663, "s": 11365, "text": "Strides: Here we assumed a stride of 1. A larger stride would just slide the window with bigger jumps, which means the strides in as_strided would have to be re-calculated. However, the concept remains the same. ( In fact, view_as_windows has a step parameter that takes care of strides as well. )" }, { "code": null, "e": 11992, "s": 11663, "text": "More Filters: In our examples, we assumed a single filter for the kernel. If we had more filters, each filter would be flattened out to give us a matrix instead of vector. Next, we would multiply this matrix with the im2col matrix. This means we would multiply a matrix by a matrix instead of vector by matrix to get the output." }, { "code": null, "e": 12151, "s": 11992, "text": "1D or 3D Convolution: The columns in the im2col matrix would just be shorter or taller since the size of the window changes (depending on the kernel as well)." }, { "code": null, "e": 12253, "s": 12151, "text": "I hope you enjoyed and found this useful! Feel free to connect with me for any questions or comments." }, { "code": null, "e": 12344, "s": 12253, "text": "Gist with all code: https://gist.github.com/anirudhshenoy/089a70deed944d0ca7ab0b6a5eb5a7f1" }, { "code": null, "e": 12356, "s": 12344, "text": "References:" }, { "code": null, "e": 12489, "s": 12356, "text": "[1] Lecture 11 CS231N: Fei-Fei Li & Andrej Karpathy & Justin Johnson http://cs231n.stanford.edu/slides/2016/winter1516_lecture11.pdf" }, { "code": null, "e": 12581, "s": 12489, "text": "[2] https://stackoverflow.com/questions/53097952/how-to-understand-numpy-strides-for-layman" } ]
Get min at pop | Practice | GeeksforGeeks
Now, we'll try to solve a famous stack problem. You are given an array A of size N. You need to first push the elements of the array into a stack and then print minimum in the stack at each pop. Example 1: Input: N = 5 A = {1 2 3 4 5} Output: 1 1 1 1 1 Explanation: After pushing elements to the stack, the stack will be "top -> 5, 4, 3, 2, 1". Now, start popping elements from the stack popping 5: min in the stack is 1.popped 5 popping 4: min in the stack is 1. popped 4 popping 3: min in the stack is 1. popped 3 popping 2: min in the stack is 1. popped 2 popping 1: min in the stack is 1. popped 1 Example 2: Input: N = 7 A = {1 6 43 1 2 0 5} Output: 0 0 1 1 1 1 1 Explanation: After pushing the elements to the stack, the stack will be 5->0->2->1->43->6->1. Now, poping the elements from the stack: popping 5: min in the stack is 0. popped 5 popping 0: min in the stack is 0. popped 0 popping 2: min in the stack is 1. popped 2 popping 1: min in the stack is 1. popped 1 popping 43: min in the stack is 1. popped 43 popping 6: min in the stack is 1. popped 6 popping 1: min in the stack is 1. popped 1. Your Task: Since this is a function problem, you don't need to take any input. Just complete the provided functions _push() and _getMinAtPop(). The _push() function takes an array as parameter, you need to push all elements of this array onto a stack and return the stack. The _getMinAtPop() accepts a stack as a parameter which is returned by _push() function and prints minimum in the stack at each pop separated by spaces. Expected Time Complexity: O(N). Expected Auxiliary Space: O(N). Constraints: 1 <= Ai <= 107 0 kirtikumaricdac5 days ago //User function Template for Java class GetMin { //Function to push all the elements into the stack. public static PriorityQueue<Integer> min=new PriorityQueue<Integer>(); public static Stack<Integer> _push(int arr[],int n) { // your code here Stack<Integer> stack=new Stack<>(); for(int i=0;i<arr.length;i++) { min.add(arr[i]); stack.push(arr[i]); } return stack; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { // your code here while(!s.isEmpty()) { // System.out.println(s.peek()); if(min.peek()==s.peek()) { System.out.print(min.peek()+" "); min.poll(); } else { System.out.print(min.peek()+" "); min.remove(s.peek()); } s.pop(); } min.clear(); } } 0 avfriendscc1 week ago //best solution c++, TC= O(N), AS= O(N) stack<int> nearestMin; stack<int> _push(int arr[],int n){ stack<int> s; s.push(arr[0]); nearestMin.push(arr[0]); for(int i=1; i<n; i++){ if(arr[i]<= nearestMin.top()){ nearestMin.push(arr[i]); } s.push(arr[i]); } return s;} //Function to print minimum value in stack each time while popping.void _getMinAtPop(stack<int>s){ while(s.empty() != true){ cout<<nearestMin.top()<<" "; if(s.top()== nearestMin.top()) nearestMin.pop(); s.pop(); }} 0 pooja13082 weeks ago C++ Solution Using Vectors stack<int> _push(int arr[],int n) { stack<int> s; for(int i=0;i<n;i++) { s.push(arr[i]); } return s; } void _getMinAtPop(stack<int>s) { int n=s.size(); vector<int> v; for(int i=0;i<n;i++){ v.push_back(s.top()); s.pop(); } for(int i=0;i<n;i++) { cout<<*min_element(v.begin(),v.end())<<" "; v.erase(v.begin()); } } 0 jraveen19971 month ago TOTAL TIME TAKEN:0.0 #Function to push all the elements into the stack. def _push(a,n): # code here stack = [] while len(a)!=0: stack.append(a.pop()) return stack #Function to print minimum value in stack each time while popping. def _getMinAtPop(stack): # code here while len(stack)!=0: print(min(stack),end=" ") stack.pop(0) +2 lakshta191 month ago C++ sol stack<int> _push(int arr[],int n) { stack<int>s; for(int i=0;i<n;i++){ s.push(arr[i]); } return s; } int getMin(stack<int>s){ int ans=INT_MAX; while(!s.empty()){ ans=min(ans,s.top()); s.pop(); } return ans; } void _getMinAtPop(stack<int>s) { int x; while(!s.empty()){ x=getMin(s); s.pop(); cout<<x<<" "; } } 0 mashhadihossain1 month ago SIMPLE JAVA SOLUTION (0.3/1.4 SEC) class GetMin{ //Function to push all the elements into the stack. public static Stack<Integer> _push(int arr[],int n) { Stack<Integer> stack=new Stack<Integer>(); for(int i=0;i<n;i++) { stack.push(arr[i]); } return stack; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { while(!s.isEmpty()) { int min=Integer.MAX_VALUE; for(int x : s) { if(x<min) { min=x; } } s.pop(); System.out.print(min+" "); } }} 0 gfgselfpaceddsa1 month ago //directly calculating min stack public static Stack<Integer> _push(int arr[],int n) { // your code here Stack<Integer> min1 = new Stack<>(); int min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { min=Math.min(min,arr[i]); min1.push(min); } return min1; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { // your code here while(!s.isEmpty()) { System.out.print(s.pop()+" "); } } +1 lokeshdohare1231 month ago JAVA Code: public static Stack<Integer> _push(int arr[],int n) { Stack<Integer> stack = new Stack<>(); for(int i=0;i<n;i++) stack.push(arr[i]); return stack; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { ArrayList<Integer> arr = new ArrayList<Integer>(); while(s.isEmpty()==false) { arr.add(s.pop()); } while(arr.size()>0) { System.out.print(Collections.min(arr)+" "); arr.remove(0); } } 0 chandannayak42071 month ago Java Solution class GetMin{ static Stack<Integer> mst = new Stack<>(); public static Stack<Integer> _push(int arr[],int n) { Stack<Integer> st = new Stack<>(); mst.push(arr[0]); for(int i = 0 ; i < n ; i++){ st.push(arr[i]); if(mst.peek() >= arr[i]){ mst.push(arr[i]); } } return st; } static void _getMinAtPop(Stack<Integer>s) { while(s.size() != 0 ){ int n = s.pop(); System.out.print( mst.peek() + " "); if(mst.peek() == n) mst.pop(); } }} +1 abhijeet194032 months ago Put all the lements in a list Put the last element of the list in a min stack Traverse the list fron n-2 element and keep pushing the element in the min stack depending upon if it less or greater than current minimum ***********Code Alert*********** ***********Code Alert*********** ***********Code Alert*********** ***********Code Alert*********** //Function to push all the elements into the stack.stack<int> _push(int arr[],int n){ // your code here stack<int> s; for(int i=0;i<n;i++) s.push(arr[i]); return s;} //Function to print minimum value in stack each time while popping.void _getMinAtPop(stack<int>s){ // store the elements in a vector vector<int> vec; while(s.empty()==false) { vec.push_back(s.top()); s.pop(); } // make a new stack and push the last element of the vector stack<int> min; min.push(vec.back()); // keep pushing the elements in the min stack for(int i=vec.size()-2;i>=0;i--) { if(vec[i]<min.top()) min.push(vec[i]); else min.push(min.top()); } // print the values in the stack while(min.empty()==false) { cout << min.top()<<" "; min.pop(); }} 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": 422, "s": 226, "text": "Now, we'll try to solve a famous stack problem. \nYou are given an array A of size N. You need to first push the elements of the array into a stack and then print minimum in the stack at each pop." }, { "code": null, "e": 433, "s": 422, "text": "Example 1:" }, { "code": null, "e": 834, "s": 433, "text": "Input:\nN = 5\nA = {1 2 3 4 5}\nOutput: \n1 1 1 1 1\nExplanation: \nAfter pushing elements to the stack, \nthe stack will be \"top -> 5, 4, 3, 2, 1\". \nNow, start popping elements from the stack\npopping 5: min in the stack is 1.popped 5\npopping 4: min in the stack is 1. popped 4\npopping 3: min in the stack is 1. popped 3\npopping 2: min in the stack is 1. popped 2\npopping 1: min in the stack is 1. popped 1\n" }, { "code": null, "e": 845, "s": 834, "text": "Example 2:" }, { "code": null, "e": 1360, "s": 845, "text": "Input: \nN = 7\nA = {1 6 43 1 2 0 5}\nOutput: \n0 0 1 1 1 1 1\nExplanation: \nAfter pushing the elements to the stack, \nthe stack will be 5->0->2->1->43->6->1. \nNow, poping the elements from the stack:\npopping 5: min in the stack is 0. popped 5\npopping 0: min in the stack is 0. popped 0\npopping 2: min in the stack is 1. popped 2\npopping 1: min in the stack is 1. popped 1\npopping 43: min in the stack is 1. \n popped 43\npopping 6: min in the stack is 1. popped 6\npopping 1: min in the stack is 1. popped 1.\n\n" }, { "code": null, "e": 1788, "s": 1362, "text": "Your Task:\nSince this is a function problem, you don't need to take any input. Just complete the provided functions _push() and _getMinAtPop(). The _push() function takes an array as parameter, you need to push all elements of this array onto a stack and return the stack. The _getMinAtPop() accepts a stack as a parameter which is returned by _push() function and prints minimum in the stack at each pop separated by spaces." }, { "code": null, "e": 1853, "s": 1788, "text": "\nExpected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1882, "s": 1853, "text": "\nConstraints:\n1 <= Ai <= 107" }, { "code": null, "e": 1884, "s": 1882, "text": "0" }, { "code": null, "e": 1910, "s": 1884, "text": "kirtikumaricdac5 days ago" }, { "code": null, "e": 1944, "s": 1910, "text": "//User function Template for Java" }, { "code": null, "e": 2929, "s": 1944, "text": "\nclass GetMin\n{\n //Function to push all the elements into the stack.\n public static PriorityQueue<Integer> min=new PriorityQueue<Integer>();\n public static Stack<Integer> _push(int arr[],int n)\n {\n // your code here\n Stack<Integer> stack=new Stack<>();\n for(int i=0;i<arr.length;i++)\n {\n \n min.add(arr[i]);\n stack.push(arr[i]);\n }\n return stack;\n \n }\n \n //Function to print minimum value in stack each time while popping.\n static void _getMinAtPop(Stack<Integer>s)\n {\n // your code here\n while(!s.isEmpty())\n {\n // System.out.println(s.peek());\n \n if(min.peek()==s.peek())\n {\n System.out.print(min.peek()+\" \");\n min.poll();\n }\n else\n {\n System.out.print(min.peek()+\" \");\n min.remove(s.peek());\n }\n s.pop();\n }\n min.clear();\n }\n}" }, { "code": null, "e": 2931, "s": 2929, "text": "0" }, { "code": null, "e": 2953, "s": 2931, "text": "avfriendscc1 week ago" }, { "code": null, "e": 2993, "s": 2953, "text": "//best solution c++, TC= O(N), AS= O(N)" }, { "code": null, "e": 3016, "s": 2993, "text": "stack<int> nearestMin;" }, { "code": null, "e": 3281, "s": 3016, "text": "stack<int> _push(int arr[],int n){ stack<int> s; s.push(arr[0]); nearestMin.push(arr[0]); for(int i=1; i<n; i++){ if(arr[i]<= nearestMin.top()){ nearestMin.push(arr[i]); } s.push(arr[i]); } return s;}" }, { "code": null, "e": 3542, "s": 3281, "text": "//Function to print minimum value in stack each time while popping.void _getMinAtPop(stack<int>s){ while(s.empty() != true){ cout<<nearestMin.top()<<\" \"; if(s.top()== nearestMin.top()) nearestMin.pop(); s.pop(); }}" }, { "code": null, "e": 3544, "s": 3542, "text": "0" }, { "code": null, "e": 3565, "s": 3544, "text": "pooja13082 weeks ago" }, { "code": null, "e": 3592, "s": 3565, "text": "C++ Solution Using Vectors" }, { "code": null, "e": 3702, "s": 3594, "text": "stack<int> _push(int arr[],int n)\n{\nstack<int> s;\nfor(int i=0;i<n;i++)\n{\n s.push(arr[i]);\n}\nreturn s;\n}\n" }, { "code": null, "e": 3960, "s": 3702, "text": "void _getMinAtPop(stack<int>s)\n{\nint n=s.size();\n vector<int> v;\n for(int i=0;i<n;i++){\n v.push_back(s.top());\n s.pop();\n \n }\n\n for(int i=0;i<n;i++)\n {\n cout<<*min_element(v.begin(),v.end())<<\" \";\n v.erase(v.begin());\n }\n}" }, { "code": null, "e": 3964, "s": 3962, "text": "0" }, { "code": null, "e": 3987, "s": 3964, "text": "jraveen19971 month ago" }, { "code": null, "e": 4008, "s": 3987, "text": "TOTAL TIME TAKEN:0.0" }, { "code": null, "e": 4385, "s": 4008, "text": "#Function to push all the elements into the stack.\ndef _push(a,n):\n # code here\n stack = []\n while len(a)!=0:\n stack.append(a.pop())\n \n return stack\n#Function to print minimum value in stack each time while popping. \ndef _getMinAtPop(stack):\n \n # code here\n while len(stack)!=0:\n print(min(stack),end=\" \")\n stack.pop(0)\n " }, { "code": null, "e": 4388, "s": 4385, "text": "+2" }, { "code": null, "e": 4409, "s": 4388, "text": "lakshta191 month ago" }, { "code": null, "e": 4417, "s": 4409, "text": "C++ sol" }, { "code": null, "e": 4820, "s": 4417, "text": "stack<int> _push(int arr[],int n)\n{ stack<int>s;\n for(int i=0;i<n;i++){\n s.push(arr[i]);\n }\n return s;\n}\nint getMin(stack<int>s){\n int ans=INT_MAX;\n while(!s.empty()){\n ans=min(ans,s.top());\n s.pop();\n }\n return ans; \n}\nvoid _getMinAtPop(stack<int>s)\n{\n int x;\n while(!s.empty()){\n x=getMin(s);\n s.pop();\n cout<<x<<\" \";\n } \n}" }, { "code": null, "e": 4822, "s": 4820, "text": "0" }, { "code": null, "e": 4849, "s": 4822, "text": "mashhadihossain1 month ago" }, { "code": null, "e": 4884, "s": 4849, "text": "SIMPLE JAVA SOLUTION (0.3/1.4 SEC)" }, { "code": null, "e": 5550, "s": 4884, "text": "class GetMin{ //Function to push all the elements into the stack. public static Stack<Integer> _push(int arr[],int n) { Stack<Integer> stack=new Stack<Integer>(); for(int i=0;i<n;i++) { stack.push(arr[i]); } return stack; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { while(!s.isEmpty()) { int min=Integer.MAX_VALUE; for(int x : s) { if(x<min) { min=x; } } s.pop(); System.out.print(min+\" \"); } }}" }, { "code": null, "e": 5552, "s": 5550, "text": "0" }, { "code": null, "e": 5579, "s": 5552, "text": "gfgselfpaceddsa1 month ago" }, { "code": null, "e": 5613, "s": 5579, "text": "//directly calculating min stack " }, { "code": null, "e": 6146, "s": 5613, "text": "public static Stack<Integer> _push(int arr[],int n) { // your code here Stack<Integer> min1 = new Stack<>(); int min=Integer.MAX_VALUE; for(int i=0;i<n;i++) { min=Math.min(min,arr[i]); min1.push(min); } return min1; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { // your code here while(!s.isEmpty()) { System.out.print(s.pop()+\" \"); } }" }, { "code": null, "e": 6149, "s": 6146, "text": "+1" }, { "code": null, "e": 6176, "s": 6149, "text": "lokeshdohare1231 month ago" }, { "code": null, "e": 6187, "s": 6176, "text": "JAVA Code:" }, { "code": null, "e": 6749, "s": 6189, "text": "public static Stack<Integer> _push(int arr[],int n) { Stack<Integer> stack = new Stack<>(); for(int i=0;i<n;i++) stack.push(arr[i]); return stack; } //Function to print minimum value in stack each time while popping. static void _getMinAtPop(Stack<Integer>s) { ArrayList<Integer> arr = new ArrayList<Integer>(); while(s.isEmpty()==false) { arr.add(s.pop()); } while(arr.size()>0) { System.out.print(Collections.min(arr)+\" \"); arr.remove(0); } }" }, { "code": null, "e": 6753, "s": 6751, "text": "0" }, { "code": null, "e": 6781, "s": 6753, "text": "chandannayak42071 month ago" }, { "code": null, "e": 6795, "s": 6781, "text": "Java Solution" }, { "code": null, "e": 7425, "s": 6795, "text": "class GetMin{ static Stack<Integer> mst = new Stack<>(); public static Stack<Integer> _push(int arr[],int n) { Stack<Integer> st = new Stack<>(); mst.push(arr[0]); for(int i = 0 ; i < n ; i++){ st.push(arr[i]); if(mst.peek() >= arr[i]){ mst.push(arr[i]); } } return st; } static void _getMinAtPop(Stack<Integer>s) { while(s.size() != 0 ){ int n = s.pop(); System.out.print( mst.peek() + \" \"); if(mst.peek() == n) mst.pop(); } }}" }, { "code": null, "e": 7428, "s": 7425, "text": "+1" }, { "code": null, "e": 7454, "s": 7428, "text": "abhijeet194032 months ago" }, { "code": null, "e": 7484, "s": 7454, "text": "Put all the lements in a list" }, { "code": null, "e": 7532, "s": 7484, "text": "Put the last element of the list in a min stack" }, { "code": null, "e": 7671, "s": 7532, "text": "Traverse the list fron n-2 element and keep pushing the element in the min stack depending upon if it less or greater than current minimum" }, { "code": null, "e": 7706, "s": 7673, "text": "***********Code Alert***********" }, { "code": null, "e": 7739, "s": 7706, "text": "***********Code Alert***********" }, { "code": null, "e": 7772, "s": 7739, "text": "***********Code Alert***********" }, { "code": null, "e": 7805, "s": 7772, "text": "***********Code Alert***********" }, { "code": null, "e": 7980, "s": 7807, "text": "//Function to push all the elements into the stack.stack<int> _push(int arr[],int n){ // your code here stack<int> s; for(int i=0;i<n;i++) s.push(arr[i]); return s;}" }, { "code": null, "e": 8621, "s": 7980, "text": "//Function to print minimum value in stack each time while popping.void _getMinAtPop(stack<int>s){ // store the elements in a vector vector<int> vec; while(s.empty()==false) { vec.push_back(s.top()); s.pop(); } // make a new stack and push the last element of the vector stack<int> min; min.push(vec.back()); // keep pushing the elements in the min stack for(int i=vec.size()-2;i>=0;i--) { if(vec[i]<min.top()) min.push(vec[i]); else min.push(min.top()); } // print the values in the stack while(min.empty()==false) { cout << min.top()<<\" \"; min.pop(); }} " }, { "code": null, "e": 8767, "s": 8621, "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": 8803, "s": 8767, "text": " Login to access your submissions. " }, { "code": null, "e": 8813, "s": 8803, "text": "\nProblem\n" }, { "code": null, "e": 8823, "s": 8813, "text": "\nContest\n" }, { "code": null, "e": 8886, "s": 8823, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 9034, "s": 8886, "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": 9242, "s": 9034, "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": 9348, "s": 9242, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Why floating-point values do not represent exact value
07 Sep, 2020 The floating-point numbers serve as rough approximations of mathematical real numbers. They do not represent the exact value. For this reason, we compare the arithmetic results of float variables with a minimum tolerance value. Example: C++ Java Python3 C# // C++ program to illustrate the// floating point values#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double num1 = 10000.29; double num2 = 10000.2; // Output should be 0.0900000000 cout << std::setprecision(15) << (num1 - num2); return 0;} // Java program to illustrate the// floating point valuesimport java.text.DecimalFormat; class GFG{ // Driver Codepublic static void main(String[] args){ double num1 = 10000.29; double num2 = 10000.2; // Output should be 0.0900000000 DecimalFormat df = new DecimalFormat( "#.################"); System.out.println(df.format(num1 - num2));}} // This code is contributed by 29AjayKumar # Python3 program to illustrate# the floating povalues# Driver Codeif __name__ == '__main__': num1 = 10000.29; num2 = 10000.2; # Output should be 0.0900000000 print ("{0:.10f}".format(num1 - num2)); # This code is contributed by Rajput-Ji // C# program to illustrate the// floating point valuesusing System; class GFG{ // Driver Codepublic static void Main(String[] args){ double num1 = 10000.29; double num2 = 10000.2; // Output should be 0.0900000000 Console.WriteLine( string.Format("{0:F15}", Decimal.Parse((num1 - num2).ToString())));}} // This code is contributed by 29AjayKumar 0.0900000000001455 Explanation: The expected output is 0.09 as output. But, the output is not 0.09. To understand this, you first have to know how a computer works with float values. When a float variable is initialized, the computer treats it as an exponential value and allocates 4 bytes(32 bits) memory where the mantissa part occupies 24 bits, the exponent part occupies 7 bits, and the remaining 1 bit is used to denote sign. For type double, the computer does the same but allocates larger memory compared to the float type. In the decimal system, every position from(left to right) in the fractional part is one-tenth of the position to its left. If we move from right to left then every position is 10 times the position to its right. In a binary system, the factor is two as shown in the table: To simplify things, let us think of a mythical type named small float(see the above image) which consists of only 5 bits – very small compared to float and double. The first three bits of the type small float will represent mantissa, the last 2 bits will represent the exponent part. For the sake of simplicity, we do not think about the sign. So the mantissa part can have only 8 possible values and the exponent part can only have 4 possible values. See the tables below: So, one combination of mantissa and exponent part can be 11100 where the leftmost two bits represent the exponent part and the remaining three bits represent the mantissa part. The value is calculated as: From the two tables, we can easily say that a small float can contain only 32 numbers and the range of the mythical type is 0 to 7. The range is not equally dense. If you see the following image carefully you will see most values lie between 0 and 1. The more you move from right to left the more sparse the numbers will be. The small float can not represent 1.3, 2.4, 5.6, etc. In that case, small float approximates them. It can not represent numbers bigger than 7. Besides many combinations represent the same value. For example: 00000, 00001, 00010, 00011 represent the same decimal value i.e., (0.000). Twelve of the 32 combinations are redundant. If we increase the number of bits allocated for small float, the denser portion will increase. As float values reserve 32 bits, float value can represent more numbers compared to small float. But some issues can be observed with float values and double values. There is no path to overcome this. Computers with infinite memory and fast preprocessor can only compute exact float or double values which is a fantasy for us. 29AjayKumar Rajput-Ji C Programs C++ Programs How To Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Difference between break and continue statement in C C Hello World Program C program to find the length of a string Sorting a Map by value in C++ STL Shallow Copy and Deep Copy in C++ C++ program for hashing with chaining C++ Program to check if a given String is Palindrome or not How to find the minimum and maximum element of a Vector using STL in C++?
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Sep, 2020" }, { "code": null, "e": 265, "s": 28, "text": "The floating-point numbers serve as rough approximations of mathematical real numbers. They do not represent the exact value. For this reason, we compare the arithmetic results of float variables with a minimum tolerance value. Example:" }, { "code": null, "e": 269, "s": 265, "text": "C++" }, { "code": null, "e": 274, "s": 269, "text": "Java" }, { "code": null, "e": 282, "s": 274, "text": "Python3" }, { "code": null, "e": 285, "s": 282, "text": "C#" }, { "code": "// C++ program to illustrate the// floating point values#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ double num1 = 10000.29; double num2 = 10000.2; // Output should be 0.0900000000 cout << std::setprecision(15) << (num1 - num2); return 0;}", "e": 575, "s": 285, "text": null }, { "code": "// Java program to illustrate the// floating point valuesimport java.text.DecimalFormat; class GFG{ // Driver Codepublic static void main(String[] args){ double num1 = 10000.29; double num2 = 10000.2; // Output should be 0.0900000000 DecimalFormat df = new DecimalFormat( \"#.################\"); System.out.println(df.format(num1 - num2));}} // This code is contributed by 29AjayKumar", "e": 991, "s": 575, "text": null }, { "code": "# Python3 program to illustrate# the floating povalues# Driver Codeif __name__ == '__main__': num1 = 10000.29; num2 = 10000.2; # Output should be 0.0900000000 print (\"{0:.10f}\".format(num1 - num2)); # This code is contributed by Rajput-Ji", "e": 1243, "s": 991, "text": null }, { "code": "// C# program to illustrate the// floating point valuesusing System; class GFG{ // Driver Codepublic static void Main(String[] args){ double num1 = 10000.29; double num2 = 10000.2; // Output should be 0.0900000000 Console.WriteLine( string.Format(\"{0:F15}\", Decimal.Parse((num1 - num2).ToString())));}} // This code is contributed by 29AjayKumar", "e": 1616, "s": 1243, "text": null }, { "code": null, "e": 1638, "s": 1616, "text": "0.0900000000001455\n\n\n" }, { "code": null, "e": 2424, "s": 1638, "text": "Explanation: The expected output is 0.09 as output. But, the output is not 0.09. To understand this, you first have to know how a computer works with float values. When a float variable is initialized, the computer treats it as an exponential value and allocates 4 bytes(32 bits) memory where the mantissa part occupies 24 bits, the exponent part occupies 7 bits, and the remaining 1 bit is used to denote sign. For type double, the computer does the same but allocates larger memory compared to the float type. In the decimal system, every position from(left to right) in the fractional part is one-tenth of the position to its left. If we move from right to left then every position is 10 times the position to its right. In a binary system, the factor is two as shown in the table: " }, { "code": null, "e": 2901, "s": 2426, "text": "To simplify things, let us think of a mythical type named small float(see the above image) which consists of only 5 bits – very small compared to float and double. The first three bits of the type small float will represent mantissa, the last 2 bits will represent the exponent part. For the sake of simplicity, we do not think about the sign. So the mantissa part can have only 8 possible values and the exponent part can only have 4 possible values. See the tables below: " }, { "code": null, "e": 3110, "s": 2903, "text": "So, one combination of mantissa and exponent part can be 11100 where the leftmost two bits represent the exponent part and the remaining three bits represent the mantissa part. The value is calculated as: " }, { "code": null, "e": 3436, "s": 3110, "text": "From the two tables, we can easily say that a small float can contain only 32 numbers and the range of the mythical type is 0 to 7. The range is not equally dense. If you see the following image carefully you will see most values lie between 0 and 1. The more you move from right to left the more sparse the numbers will be. " }, { "code": null, "e": 4187, "s": 3436, "text": "The small float can not represent 1.3, 2.4, 5.6, etc. In that case, small float approximates them. It can not represent numbers bigger than 7. Besides many combinations represent the same value. For example: 00000, 00001, 00010, 00011 represent the same decimal value i.e., (0.000). Twelve of the 32 combinations are redundant. If we increase the number of bits allocated for small float, the denser portion will increase. As float values reserve 32 bits, float value can represent more numbers compared to small float. But some issues can be observed with float values and double values. There is no path to overcome this. Computers with infinite memory and fast preprocessor can only compute exact float or double values which is a fantasy for us. " }, { "code": null, "e": 4199, "s": 4187, "text": "29AjayKumar" }, { "code": null, "e": 4209, "s": 4199, "text": "Rajput-Ji" }, { "code": null, "e": 4220, "s": 4209, "text": "C Programs" }, { "code": null, "e": 4233, "s": 4220, "text": "C++ Programs" }, { "code": null, "e": 4240, "s": 4233, "text": "How To" }, { "code": null, "e": 4338, "s": 4240, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4379, "s": 4338, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 4410, "s": 4379, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 4463, "s": 4410, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 4485, "s": 4463, "text": "C Hello World Program" }, { "code": null, "e": 4526, "s": 4485, "text": "C program to find the length of a string" }, { "code": null, "e": 4560, "s": 4526, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 4594, "s": 4560, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 4632, "s": 4594, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 4692, "s": 4632, "text": "C++ Program to check if a given String is Palindrome or not" } ]
BigInteger intValue() Method in Java
04 Dec, 2018 The java.math.BigInteger.intValue() converts this BigInteger to an integer value. If the value returned by this function is too big to fit into integer value, then it will return only the low-order 32 bits. Further there is chance that this conversion can loose information about the overall magnitude of the BigInteger value. This method can also return the result with opposite sign. Syntax: public int intValue() Returns: The method returns an int value which represents integer value for this BigInteger. Examples: Input: BigInteger1=32145 Output: 32145 Explanation: BigInteger1.intValue()=32145. Input: BigInteger1=4326516236135 Output: 1484169063 Explanation: BigInteger1.intValue()=1484169063. This BigInteger is too big for intValue so it is returning lower 32 bit. Example 1:Below programs illustrate intValue() method of BigInteger class // Java program to demonstrate // intValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("32145"); b2 = new BigInteger("7613721"); // apply intValue() method int intValueOfb1 = b1.intValue(); int intValueOfb2 = b2.intValue(); // print intValue System.out.println("intValue of " + b1 + " : " + intValueOfb1); System.out.println("intValue of " + b2 + " : " + intValueOfb2); }} intValue of 32145 : 32145 intValue of 7613721 : 7613721 Example 2: when return integer is too big for int value. // Java program to demonstrate // intValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("4326516236135"); b2 = new BigInteger("251362466336"); // apply intValue() method int intValueOfb1 = b1.intValue(); int intValueOfb2 = b2.intValue(); // print intValue System.out.println("intValue of " + b1 + " : " + intValueOfb1); System.out.println("intValue of " + b2 + " : " + intValueOfb2); }} intValue of 4326516236135 : 1484169063 intValue of 251362466336 : -2040604128 Reference:BigInteger intValue() Docs java-basics Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2018" }, { "code": null, "e": 414, "s": 28, "text": "The java.math.BigInteger.intValue() converts this BigInteger to an integer value. If the value returned by this function is too big to fit into integer value, then it will return only the low-order 32 bits. Further there is chance that this conversion can loose information about the overall magnitude of the BigInteger value. This method can also return the result with opposite sign." }, { "code": null, "e": 422, "s": 414, "text": "Syntax:" }, { "code": null, "e": 444, "s": 422, "text": "public int intValue()" }, { "code": null, "e": 537, "s": 444, "text": "Returns: The method returns an int value which represents integer value for this BigInteger." }, { "code": null, "e": 547, "s": 537, "text": "Examples:" }, { "code": null, "e": 805, "s": 547, "text": "Input: BigInteger1=32145\nOutput: 32145\nExplanation: BigInteger1.intValue()=32145.\n\nInput: BigInteger1=4326516236135\nOutput: 1484169063\nExplanation: BigInteger1.intValue()=1484169063. This BigInteger is too big for \nintValue so it is returning lower 32 bit.\n" }, { "code": null, "e": 879, "s": 805, "text": "Example 1:Below programs illustrate intValue() method of BigInteger class" }, { "code": "// Java program to demonstrate // intValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"32145\"); b2 = new BigInteger(\"7613721\"); // apply intValue() method int intValueOfb1 = b1.intValue(); int intValueOfb2 = b2.intValue(); // print intValue System.out.println(\"intValue of \" + b1 + \" : \" + intValueOfb1); System.out.println(\"intValue of \" + b2 + \" : \" + intValueOfb2); }}", "e": 1535, "s": 879, "text": null }, { "code": null, "e": 1592, "s": 1535, "text": "intValue of 32145 : 32145\nintValue of 7613721 : 7613721\n" }, { "code": null, "e": 1649, "s": 1592, "text": "Example 2: when return integer is too big for int value." }, { "code": "// Java program to demonstrate // intValue() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"4326516236135\"); b2 = new BigInteger(\"251362466336\"); // apply intValue() method int intValueOfb1 = b1.intValue(); int intValueOfb2 = b2.intValue(); // print intValue System.out.println(\"intValue of \" + b1 + \" : \" + intValueOfb1); System.out.println(\"intValue of \" + b2 + \" : \" + intValueOfb2); }}", "e": 2318, "s": 1649, "text": null }, { "code": null, "e": 2397, "s": 2318, "text": "intValue of 4326516236135 : 1484169063\nintValue of 251362466336 : -2040604128\n" }, { "code": null, "e": 2434, "s": 2397, "text": "Reference:BigInteger intValue() Docs" }, { "code": null, "e": 2446, "s": 2434, "text": "java-basics" }, { "code": null, "e": 2462, "s": 2446, "text": "Java-BigInteger" }, { "code": null, "e": 2477, "s": 2462, "text": "Java-Functions" }, { "code": null, "e": 2487, "s": 2477, "text": "java-math" }, { "code": null, "e": 2505, "s": 2487, "text": "Java-math-package" }, { "code": null, "e": 2510, "s": 2505, "text": "Java" }, { "code": null, "e": 2526, "s": 2510, "text": "Java-BigInteger" }, { "code": null, "e": 2531, "s": 2526, "text": "Java" }, { "code": null, "e": 2629, "s": 2531, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2680, "s": 2629, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2711, "s": 2680, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2730, "s": 2711, "text": "Interfaces in Java" }, { "code": null, "e": 2760, "s": 2730, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2778, "s": 2760, "text": "ArrayList in Java" }, { "code": null, "e": 2793, "s": 2778, "text": "Stream In Java" }, { "code": null, "e": 2813, "s": 2793, "text": "Collections in Java" }, { "code": null, "e": 2845, "s": 2813, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2869, "s": 2845, "text": "Singleton Class in Java" } ]
How to compare password and confirm password inputs using express-validator ?
14 Jan, 2022 The registration or Sign Up in any website always requires a confirm password input and it must be the same as the password. It is basically to ensure that the user enters the password full of his sense and there is no conflict happens. This functionality can be implemented anywhere in our code like in index file or route file but this comes under the validation part. So we usually prefer to code this logic where all the other validations are coded. Here we use ‘express-validator’ middleware to implement this functionality. Command to install express-validator npm install express-validator Steps to use express-validator to implement the logic: Install express-validator middleware. Create a validator.js file to code all the validation logic. Validate confirmPassword by validateConfirmPassword: check(‘confirmPassword’) and chain on all the validation with ‘ . ‘ Use the validation name(validateConfirmPassword) in the routes as a middleware as an array of validations. Destructure ‘validationResult’ function from express-validator to use it to find any errors If error occurs redirect to the same page passing the error information If error list is empty, give access to the user for the subsequent request. Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql. Example 1: This example illustrates how to check if email address is already in use or not for a particular website. Filename: index.js javascript const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateConfirmPassword } = require('./validator')const signupTemplet = require('./signup') const app = express() const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to sign inapp.get('/signup', (req, res) => { res.send(signupTemplet({}))}) // Post route to handle form submission logic andapp.post( '/signup', [validateConfirmPassword], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(signupTemplet({errors})) } const {email, password} = req.body await repo.create({email, password}) res.send('Sign Up successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)}) Filename: repository.js This file contains all the logic to create a local database and interact with it. javascript // Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are // going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist it is // created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding: 'utf8' }) ) } // Find record by properties async getOneBy(filters) { const records = await this.getAll() for (let record of records) { let found = true for (let key in filters) { if (record[key] !== filters[key]) { found = false } } if (found) return record; } } // Create new record async create(attrs) { const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json') Filename: signup.js This file contains logic to show sign up form. javascript const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({ errors }) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <h1 class='title'>Sign Up<h1> <form method='POST'> <div> <div> <label class='label' id='email'> Username</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id= 'password'>Password</label> </div> <input class='input' type= 'password' name='password' placeholder='Password' for='password'> </div> <div> <div> <label class='label' id='confirmPassword'> Confirm Password</label> </div> <input class='input' type='password' name='confirmPassword' placeholder='Confirm Password' for='confirmPassword'> <p class="help is-danger"> ${getError(errors, 'confirmPassword')} </p> </div> <div> <button class='button is-primary'> Sign Up</button> </div> </form> </div> </div> </div> </body> </html> `} Filename: validator.js This file contain all the validation logic (Logic to see if password and passwordConfirm are same). javascript const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateConfirmPassword : check('confirmPassword') // To delete leading and trailing space .trim() // Validate minimum length of password // Optional for this context .isLength({min:4, max:16}) // Custom message .withMessage('Password must be between 4 to 16 characters') // Custom validation // Validate confirmPassword .custom(async (confirmPassword, {req}) => { const password = req.body.password // If password and confirm password not same // don't allow to sign up and throw error if(password !== confirmPassword){ throw new Error('Passwords must be same') } }),} Filename: package.json package.json file Database: Database Output: Attempt to sign up when password and confirm password inputs are different Response when attempt to sign up with different password and confirm password inputs Attempt to sign up when password and confirm password inputs are same Response when attempt to sign up with same password and confirm password inputs Database after successful Sign Up(Sign Up with same password and confirm password inputs) Database after successful Sign Up(Sign Up with same password and confirm password inputs) Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content. kk9826225 clintra Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js 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 ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jan, 2022" }, { "code": null, "e": 582, "s": 52, "text": "The registration or Sign Up in any website always requires a confirm password input and it must be the same as the password. It is basically to ensure that the user enters the password full of his sense and there is no conflict happens. This functionality can be implemented anywhere in our code like in index file or route file but this comes under the validation part. So we usually prefer to code this logic where all the other validations are coded. Here we use ‘express-validator’ middleware to implement this functionality." }, { "code": null, "e": 619, "s": 582, "text": "Command to install express-validator" }, { "code": null, "e": 649, "s": 619, "text": "npm install express-validator" }, { "code": null, "e": 704, "s": 649, "text": "Steps to use express-validator to implement the logic:" }, { "code": null, "e": 742, "s": 704, "text": "Install express-validator middleware." }, { "code": null, "e": 803, "s": 742, "text": "Create a validator.js file to code all the validation logic." }, { "code": null, "e": 924, "s": 803, "text": "Validate confirmPassword by validateConfirmPassword: check(‘confirmPassword’) and chain on all the validation with ‘ . ‘" }, { "code": null, "e": 1031, "s": 924, "text": "Use the validation name(validateConfirmPassword) in the routes as a middleware as an array of validations." }, { "code": null, "e": 1123, "s": 1031, "text": "Destructure ‘validationResult’ function from express-validator to use it to find any errors" }, { "code": null, "e": 1195, "s": 1123, "text": "If error occurs redirect to the same page passing the error information" }, { "code": null, "e": 1271, "s": 1195, "text": "If error list is empty, give access to the user for the subsequent request." }, { "code": null, "e": 1438, "s": 1271, "text": "Note: Here we use local or custom database to implement the logic, the same steps can be followed to implement the logic in a regular database like MongoDB or MySql. " }, { "code": null, "e": 1555, "s": 1438, "text": "Example 1: This example illustrates how to check if email address is already in use or not for a particular website." }, { "code": null, "e": 1576, "s": 1557, "text": "Filename: index.js" }, { "code": null, "e": 1589, "s": 1578, "text": "javascript" }, { "code": "const express = require('express')const bodyParser = require('body-parser')const {validationResult} = require('express-validator')const repo = require('./repository')const { validateConfirmPassword } = require('./validator')const signupTemplet = require('./signup') const app = express() const port = process.env.PORT || 3000 // The body-parser middleware to parse form dataapp.use(bodyParser.urlencoded({extended : true})) // Get route to display HTML form to sign inapp.get('/signup', (req, res) => { res.send(signupTemplet({}))}) // Post route to handle form submission logic andapp.post( '/signup', [validateConfirmPassword], async (req, res) => { const errors = validationResult(req) if(!errors.isEmpty()){ return res.send(signupTemplet({errors})) } const {email, password} = req.body await repo.create({email, password}) res.send('Sign Up successfully')}) // Server setupapp.listen(port, () => { console.log(`Server start on port ${port}`)})", "e": 2566, "s": 1589, "text": null }, { "code": null, "e": 2674, "s": 2566, "text": "Filename: repository.js This file contains all the logic to create a local database and interact with it. " }, { "code": null, "e": 2685, "s": 2674, "text": "javascript" }, { "code": "// Importing node.js file system moduleconst fs = require('fs') class Repository { constructor(filename) { // The filename where datas are // going to store if (!filename) { throw new Error('Filename is required to create a datastore!') } this.filename = filename try { fs.accessSync(this.filename) } catch (err) { // If file not exist it is // created with empty array fs.writeFileSync(this.filename, '[]') } } // Get all existing records async getAll() { return JSON.parse( await fs.promises.readFile(this.filename, { encoding: 'utf8' }) ) } // Find record by properties async getOneBy(filters) { const records = await this.getAll() for (let record of records) { let found = true for (let key in filters) { if (record[key] !== filters[key]) { found = false } } if (found) return record; } } // Create new record async create(attrs) { const records = await this.getAll() records.push(attrs) await fs.promises.writeFile( this.filename, JSON.stringify(records, null, 2) ) return attrs }} // The 'datastore.json' file created at runtime// and all the information provided via signup form// store in this file in JSON format.module.exports = new Repository('datastore.json')", "e": 4228, "s": 2685, "text": null }, { "code": null, "e": 4297, "s": 4228, "text": "Filename: signup.js This file contains logic to show sign up form. " }, { "code": null, "e": 4308, "s": 4297, "text": "javascript" }, { "code": "const getError = (errors, prop) => { try { return errors.mapped()[prop].msg } catch (error) { return '' }} module.exports = ({ errors }) => { return ` <!DOCTYPE html> <html> <head> <link rel='stylesheet'href='https://cdnjs.cloudflare.com/ajax/libs/bulma/0.9.0/css/bulma.min.css'> <style> div.columns{ margin-top: 100px; } .button{ margin-top : 10px } </style> </head> <body> <div class='container'> <div class='columns is-centered'> <div class='column is-5'> <h1 class='title'>Sign Up<h1> <form method='POST'> <div> <div> <label class='label' id='email'> Username</label> </div> <input class='input' type='text' name='email' placeholder='Email' for='email'> </div> <div> <div> <label class='label' id= 'password'>Password</label> </div> <input class='input' type= 'password' name='password' placeholder='Password' for='password'> </div> <div> <div> <label class='label' id='confirmPassword'> Confirm Password</label> </div> <input class='input' type='password' name='confirmPassword' placeholder='Confirm Password' for='confirmPassword'> <p class=\"help is-danger\"> ${getError(errors, 'confirmPassword')} </p> </div> <div> <button class='button is-primary'> Sign Up</button> </div> </form> </div> </div> </div> </body> </html> `}", "e": 6342, "s": 4308, "text": null }, { "code": null, "e": 6467, "s": 6342, "text": "Filename: validator.js This file contain all the validation logic (Logic to see if password and passwordConfirm are same). " }, { "code": null, "e": 6478, "s": 6467, "text": "javascript" }, { "code": "const {check} = require('express-validator')const repo = require('./repository')module.exports = { validateConfirmPassword : check('confirmPassword') // To delete leading and trailing space .trim() // Validate minimum length of password // Optional for this context .isLength({min:4, max:16}) // Custom message .withMessage('Password must be between 4 to 16 characters') // Custom validation // Validate confirmPassword .custom(async (confirmPassword, {req}) => { const password = req.body.password // If password and confirm password not same // don't allow to sign up and throw error if(password !== confirmPassword){ throw new Error('Passwords must be same') } }),}", "e": 7221, "s": 6478, "text": null }, { "code": null, "e": 7244, "s": 7221, "text": "Filename: package.json" }, { "code": null, "e": 7262, "s": 7244, "text": "package.json file" }, { "code": null, "e": 7272, "s": 7262, "text": "Database:" }, { "code": null, "e": 7281, "s": 7272, "text": "Database" }, { "code": null, "e": 7289, "s": 7281, "text": "Output:" }, { "code": null, "e": 7364, "s": 7289, "text": "Attempt to sign up when password and confirm password inputs are different" }, { "code": null, "e": 7449, "s": 7364, "text": "Response when attempt to sign up with different password and confirm password inputs" }, { "code": null, "e": 7519, "s": 7449, "text": "Attempt to sign up when password and confirm password inputs are same" }, { "code": null, "e": 7599, "s": 7519, "text": "Response when attempt to sign up with same password and confirm password inputs" }, { "code": null, "e": 7689, "s": 7599, "text": "Database after successful Sign Up(Sign Up with same password and confirm password inputs)" }, { "code": null, "e": 7779, "s": 7689, "text": "Database after successful Sign Up(Sign Up with same password and confirm password inputs)" }, { "code": null, "e": 7878, "s": 7779, "text": "Note: We have used some Bulma classes(CSS framework) in the signup.js file to design the content." }, { "code": null, "e": 7888, "s": 7878, "text": "kk9826225" }, { "code": null, "e": 7896, "s": 7888, "text": "clintra" }, { "code": null, "e": 7909, "s": 7896, "text": "Node.js-Misc" }, { "code": null, "e": 7917, "s": 7909, "text": "Node.js" }, { "code": null, "e": 7934, "s": 7917, "text": "Web Technologies" }, { "code": null, "e": 8032, "s": 7934, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8089, "s": 8032, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 8119, "s": 8089, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 8173, "s": 8119, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 8213, "s": 8173, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 8245, "s": 8213, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 8307, "s": 8245, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 8368, "s": 8307, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 8418, "s": 8368, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 8461, "s": 8418, "text": "How to fetch data from an API in ReactJS ?" } ]
EtherChannel in Computer Network
23 Mar, 2022 EtherChannel is a port link aggregation technology in which multiple physical port links are grouped into one logical link. It is used to provide high-speed links and redundancy. A maximum of 8 links can be aggregated to form a single logical link. Need of EtherChannel – Here is a topology in which two switches are connected with one PC each. The link between the switches and PC is 1000mb/s and the link between the switches is 100mb/s. Now, suppose if you want to send traffic of more than 100mb/s then we have congestion as the link between the switches is of 100mb/s only and packets will start dropping. Now, to solve this problem, we should have a high-speed link between the switches. To achieve this, We can simply replace the current link with a high-speed link or we can bundle up more than one link of the same speed of 100mb/s. By forming an EtherChannel, you can bundle up more than one link into a single logical link. But, as you connect the switches with more than one link, STP (Spanning Tree Protocol) will block the least redundant link. As we have made an EtherChannel, all the links (that are grouped as one logical link k) will be treated as single logical links therefore no link will be blocked and also, it will provide us high-speed link and redundancy in our network. Criteria – To form an EtherChannel, all ports should have: Same duplexSame speedSame VLAN configuration (i.e., native VLAN and allowed VLAN should be same)Switch port modes should be the same (access or trunk mode) Same duplex Same speed Same VLAN configuration (i.e., native VLAN and allowed VLAN should be same) Switch port modes should be the same (access or trunk mode) EtherChannel protocols – To form an EtherChannel, there are 2 protocols, port aggregation Protocol (PAgP) and link aggregation control protocol (LACP). 1. Port Aggregation Protocol (PAgP) – The Cisco proprietary protocol Port Aggregation Protocol (PAgP) is an EtherChannel technology. It’s a type of data/traffic load balancing that involves the logical aggregation of Cisco Ethernet switch ports. A PAgP EtherChannel can merge up to eight physical links into one virtual link. LACP, or Link Aggregation Control Protocol, is an IEEE open standard. These are namely: ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes place.Desirable: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel.Auto: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface.Off: No EtherChannel configured on the interface. ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes place. Desirable: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel. Auto: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface. Off: No EtherChannel configured on the interface. Configuration – There is a small topology in which 2 switches S1 and S2 are connected with each other and we have to bundle these two links into a single logical link. S1(config)# interface fa0/1 S1(config-if)# channel-group 1 mode desirable S1(config)# interface fa0/2 S1(config-if)# channel-group 1 mode desirable S1(config)# interface port-channel 1 S1(config-if)# switchport trunk encapsulation dot1q S1(config-if)# switchport mode trunk Here, the user has used the mode desirable and switch-port mode trunk. The modes should be the same on both switches therefore the user will configure this on the other switch also. Now, configuring on switch S2: S2(config)# interface fa0/1 S2(config-if)# channel-group 1 mode desirable S2(config)# interface fa0/2 S2(config-if)# channel-group 1 mode desirable S2(config)# interface port-channel 1 S2(config-if)# switchport trunk encapsulation dot1q S2(config-if)# switchport mode trunk 2. Link Aggregation Control Protocol (LACP) – Link Aggregation Control Protocol is an IEEE protocol, originally defined in 802.3ad, used to form an EtherChannel. This protocol is almost similar to Cisco PAgP. There are different modes in which you can configure your interface. These are namely: ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes placeActive: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel.Passive: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface.Off: No EtherChannel configured on the interface. ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes place Active: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel. Passive: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface. Off: No EtherChannel configured on the interface. Configuration – Taking the same topology, you will now configure LACP on both switches. First, configuring for S1: S1(config)# interface fa0/1 S1(config-if)# channel-group mode active S1(config)# interface fa0/2 S1(config-if)# channel-group mode active S1(config)# interface port-channel 1 S1(config-if)# switchport trunk encapsulation dot1q S1(config-if)# switchport mode trunk Now, configuring for S2: S2(config)# interface fa0/1 S2(config-if)# channel-group mode active S2(config)# interface fa0/2 S2(config-if)# channel-group mode active S2(config)# interface port-channel 1 S2(config-if)# switchport trunk encapsulation dot1q S2(config-if)# switchport mode trunk abhishekpal97854368 akashmomale Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP RSA Algorithm in Cryptography GSM in Wireless Communication TCP Server-Client implementation in C Socket Programming in Python Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) Data encryption standard (DES) | Set 1
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Mar, 2022" }, { "code": null, "e": 304, "s": 54, "text": "EtherChannel is a port link aggregation technology in which multiple physical port links are grouped into one logical link. It is used to provide high-speed links and redundancy. A maximum of 8 links can be aggregated to form a single logical link. " }, { "code": null, "e": 328, "s": 304, "text": "Need of EtherChannel – " }, { "code": null, "e": 497, "s": 328, "text": "Here is a topology in which two switches are connected with one PC each. The link between the switches and PC is 1000mb/s and the link between the switches is 100mb/s. " }, { "code": null, "e": 993, "s": 497, "text": "Now, suppose if you want to send traffic of more than 100mb/s then we have congestion as the link between the switches is of 100mb/s only and packets will start dropping. Now, to solve this problem, we should have a high-speed link between the switches. To achieve this, We can simply replace the current link with a high-speed link or we can bundle up more than one link of the same speed of 100mb/s. By forming an EtherChannel, you can bundle up more than one link into a single logical link. " }, { "code": null, "e": 1356, "s": 993, "text": "But, as you connect the switches with more than one link, STP (Spanning Tree Protocol) will block the least redundant link. As we have made an EtherChannel, all the links (that are grouped as one logical link k) will be treated as single logical links therefore no link will be blocked and also, it will provide us high-speed link and redundancy in our network. " }, { "code": null, "e": 1416, "s": 1356, "text": "Criteria – To form an EtherChannel, all ports should have: " }, { "code": null, "e": 1572, "s": 1416, "text": "Same duplexSame speedSame VLAN configuration (i.e., native VLAN and allowed VLAN should be same)Switch port modes should be the same (access or trunk mode)" }, { "code": null, "e": 1584, "s": 1572, "text": "Same duplex" }, { "code": null, "e": 1595, "s": 1584, "text": "Same speed" }, { "code": null, "e": 1671, "s": 1595, "text": "Same VLAN configuration (i.e., native VLAN and allowed VLAN should be same)" }, { "code": null, "e": 1731, "s": 1671, "text": "Switch port modes should be the same (access or trunk mode)" }, { "code": null, "e": 1884, "s": 1731, "text": "EtherChannel protocols – To form an EtherChannel, there are 2 protocols, port aggregation Protocol (PAgP) and link aggregation control protocol (LACP). " }, { "code": null, "e": 2299, "s": 1884, "text": "1. Port Aggregation Protocol (PAgP) – The Cisco proprietary protocol Port Aggregation Protocol (PAgP) is an EtherChannel technology. It’s a type of data/traffic load balancing that involves the logical aggregation of Cisco Ethernet switch ports. A PAgP EtherChannel can merge up to eight physical links into one virtual link. LACP, or Link Aggregation Control Protocol, is an IEEE open standard. These are namely: " }, { "code": null, "e": 2691, "s": 2299, "text": "ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes place.Desirable: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel.Auto: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface.Off: No EtherChannel configured on the interface." }, { "code": null, "e": 2786, "s": 2691, "text": "ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes place." }, { "code": null, "e": 2909, "s": 2786, "text": "Desirable: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel." }, { "code": null, "e": 3036, "s": 2909, "text": "Auto: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface." }, { "code": null, "e": 3086, "s": 3036, "text": "Off: No EtherChannel configured on the interface." }, { "code": null, "e": 3103, "s": 3086, "text": "Configuration – " }, { "code": null, "e": 3257, "s": 3103, "text": "There is a small topology in which 2 switches S1 and S2 are connected with each other and we have to bundle these two links into a single logical link. " }, { "code": null, "e": 3534, "s": 3257, "text": "S1(config)# interface fa0/1\nS1(config-if)# channel-group 1 mode desirable \nS1(config)# interface fa0/2\nS1(config-if)# channel-group 1 mode desirable \n\nS1(config)# interface port-channel 1\nS1(config-if)# switchport trunk encapsulation dot1q\nS1(config-if)# switchport mode trunk" }, { "code": null, "e": 3717, "s": 3534, "text": "Here, the user has used the mode desirable and switch-port mode trunk. The modes should be the same on both switches therefore the user will configure this on the other switch also. " }, { "code": null, "e": 3750, "s": 3717, "text": "Now, configuring on switch S2: " }, { "code": null, "e": 4026, "s": 3750, "text": "S2(config)# interface fa0/1\nS2(config-if)# channel-group 1 mode desirable \nS2(config)# interface fa0/2\nS2(config-if)# channel-group 1 mode desirable \nS2(config)# interface port-channel 1\nS2(config-if)# switchport trunk encapsulation dot1q\nS2(config-if)# switchport mode trunk" }, { "code": null, "e": 4324, "s": 4026, "text": "2. Link Aggregation Control Protocol (LACP) – Link Aggregation Control Protocol is an IEEE protocol, originally defined in 802.3ad, used to form an EtherChannel. This protocol is almost similar to Cisco PAgP. There are different modes in which you can configure your interface. These are namely: " }, { "code": null, "e": 4715, "s": 4324, "text": "ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes placeActive: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel.Passive: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface.Off: No EtherChannel configured on the interface." }, { "code": null, "e": 4809, "s": 4715, "text": "ON: In this mode, the interface will be a part of EtherChannel but no negotiation takes place" }, { "code": null, "e": 4929, "s": 4809, "text": "Active: In this mode, the interface will continuously attempt to convert the other side interface into an EtherChannel." }, { "code": null, "e": 5059, "s": 4929, "text": "Passive: In this mode, the interface will become a part of EtherChannel if and only if it is requested by the opposite interface." }, { "code": null, "e": 5109, "s": 5059, "text": "Off: No EtherChannel configured on the interface." }, { "code": null, "e": 5126, "s": 5109, "text": "Configuration – " }, { "code": null, "e": 5227, "s": 5126, "text": "Taking the same topology, you will now configure LACP on both switches. First, configuring for S1: " }, { "code": null, "e": 5493, "s": 5227, "text": "S1(config)# interface fa0/1\nS1(config-if)# channel-group mode active \nS1(config)# interface fa0/2\nS1(config-if)# channel-group mode active\n\nS1(config)# interface port-channel 1\nS1(config-if)# switchport trunk encapsulation dot1q\nS1(config-if)# switchport mode trunk" }, { "code": null, "e": 5519, "s": 5493, "text": "Now, configuring for S2: " }, { "code": null, "e": 5785, "s": 5519, "text": "S2(config)# interface fa0/1\nS2(config-if)# channel-group mode active\nS2(config)# interface fa0/2\nS2(config-if)# channel-group mode active \n\nS2(config)# interface port-channel 1\nS2(config-if)# switchport trunk encapsulation dot1q\nS2(config-if)# switchport mode trunk" }, { "code": null, "e": 5807, "s": 5787, "text": "abhishekpal97854368" }, { "code": null, "e": 5819, "s": 5807, "text": "akashmomale" }, { "code": null, "e": 5837, "s": 5819, "text": "Computer Networks" }, { "code": null, "e": 5855, "s": 5837, "text": "Computer Networks" }, { "code": null, "e": 5953, "s": 5855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5985, "s": 5953, "text": "Differences between TCP and UDP" }, { "code": null, "e": 6015, "s": 5985, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 6045, "s": 6015, "text": "GSM in Wireless Communication" }, { "code": null, "e": 6083, "s": 6045, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 6112, "s": 6083, "text": "Socket Programming in Python" }, { "code": null, "e": 6146, "s": 6112, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 6172, "s": 6146, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 6202, "s": 6172, "text": "Wireless Application Protocol" }, { "code": null, "e": 6242, "s": 6202, "text": "Mobile Internet Protocol (or Mobile IP)" } ]
HTML | <frame> frameborder Attribute
30 Sep, 2019 The HTML <frame> frameborder attribute is used to specify whether or not a border should be displayed between the frames. For this, we use two values 0 and 1, where 0 defines no border and 1 defines the border. Syntax <frame frameborder="1|0"> Attribute Values: 0: It has a default value. It sets the border on one state. 1: It sets the border off state. Example: <!DOCTYPE html> <html> <head> <title> HTML frame frameborder Attribute </title> </head> <frameset cols="30%, 40%, 30%"> <frame name="left" src="https://media.geeksforgeeks.org/wp-content/uploads/20190401113144/gfg_200X2001.png" frameborder="1" /> <frame name="main" src="https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png" frameborder="1" /> <frame name="bottom" src="https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png" frameborder="0" /> </frameset> </html> Output: Supported Browsers: The browsers supported by HTML <frame> frameborder attribute are listed below: Google Chrome Internet Explorer Firefox Safari Opera HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Sep, 2019" }, { "code": null, "e": 239, "s": 28, "text": "The HTML <frame> frameborder attribute is used to specify whether or not a border should be displayed between the frames. For this, we use two values 0 and 1, where 0 defines no border and 1 defines the border." }, { "code": null, "e": 246, "s": 239, "text": "Syntax" }, { "code": null, "e": 273, "s": 246, "text": "<frame frameborder=\"1|0\"> " }, { "code": null, "e": 291, "s": 273, "text": "Attribute Values:" }, { "code": null, "e": 351, "s": 291, "text": "0: It has a default value. It sets the border on one state." }, { "code": null, "e": 384, "s": 351, "text": "1: It sets the border off state." }, { "code": null, "e": 393, "s": 384, "text": "Example:" }, { "code": "<!DOCTYPE html> <html> <head> <title> HTML frame frameborder Attribute </title> </head> <frameset cols=\"30%, 40%, 30%\"> <frame name=\"left\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190401113144/gfg_200X2001.png\" frameborder=\"1\" /> <frame name=\"main\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190328185307/gfg28.png\" frameborder=\"1\" /> <frame name=\"bottom\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190807114330/GFG115.png\" frameborder=\"0\" /> </frameset> </html>", "e": 990, "s": 393, "text": null }, { "code": null, "e": 998, "s": 990, "text": "Output:" }, { "code": null, "e": 1097, "s": 998, "text": "Supported Browsers: The browsers supported by HTML <frame> frameborder attribute are listed below:" }, { "code": null, "e": 1111, "s": 1097, "text": "Google Chrome" }, { "code": null, "e": 1129, "s": 1111, "text": "Internet Explorer" }, { "code": null, "e": 1137, "s": 1129, "text": "Firefox" }, { "code": null, "e": 1144, "s": 1137, "text": "Safari" }, { "code": null, "e": 1150, "s": 1144, "text": "Opera" }, { "code": null, "e": 1166, "s": 1150, "text": "HTML-Attributes" }, { "code": null, "e": 1171, "s": 1166, "text": "HTML" }, { "code": null, "e": 1188, "s": 1171, "text": "Web Technologies" }, { "code": null, "e": 1193, "s": 1188, "text": "HTML" } ]
Python Pillow – Writing Text on Image
13 Jul, 2021 In this article, we will see how to write text on images with the Python Pillow module. This module is not preloaded with Python. So to install it execute the following command in the command-line: pip install pillow Stepwise implementation: Step 1: Import Pillow library To complete this task the functions required from the Pillow library are: Image, ImageDraw, ImageFont. All these functions are imported as: from PIL import Image, ImageDraw, ImageFont Step 2: Open an image In this step, the image on which we are going to add text is imported and open by using the “Image.open(‘Image_name’)”. In the given case the gfg logo is used to add the text on it. The image name is gfg_logo.jpeg. So, it is written as: img = Image.open(‘gfg_logo.jpeg’) Step 3: Image Conversion In this step, we convert our image into an editable format by using “ImageDraw.Draw(‘variable used to store the image in above step’)”. In the given case this is written as: d1 = ImageDraw.Draw(img) Step 4: Font style. This step is optional. It is for those who want their text to look cool or stylish because someone won’t select any font style then the system takes the default font style. At first download the font style file from https://ttfonts.net/font/1004_Mistral.htm . After downloading the file use the function ImageFont.truetype(‘adddress_of_font_style’, font_style). In given cases this is written as: myFont = ImageFont.truetype(‘/home/raghav/PycharmProjects/gfg/Mistral.ttf’, 20) Step 5: Render the text This is the main step in which the whole properties of the font get decided. This is written as: d1.text((65, 10), “Sample text”, fill =(255, 0, 0),font=myFont) Starting Coordinates: Pillow library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. Text: String between single or double quotations Text color in RGB format: For the color, you want you can check it to Google for its RGB color code and use. Font style: Download the font from Google and use it. Step 6: Show and Save result. The final step is to display the modified image on the screen for this img.show() function is used and to store the image img.save(“results.jpeg”) is used. Below is the implementation: Input Image Python3 # Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using open# function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using# Draw function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 10), "Sample text", fill =(255, 0, 0),font=myFont) # show and save the imageimg.show()img.save("results.jpeg") Output: Image after modification Example 1: To change the location of the text change the coordinates in step 5. The dimensions are changed from (65,100) to (65,170). So, the location of text goes down because from (x,y) coordinates the value of y-coordinate gets increased as shown in the output. Python3 # Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using# open function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using# Draw function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 170), "Sample text", fill =(255, 0, 0),font=myFont) # show and save the imageimg.show()img.save("results.jpeg") Output: Image after changing it’s coordinates Example 2: To change the color of the text again change in step 5. There are RGB colour code on which Pillow work (R,G,B) R for RED, G for GREEN, B for Blue. In above case the R and B value is 0 and G value is 255 i.e. Maximum. So, the colour of text changes to green as shown in output. Python3 # Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using# open function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using Draw function# and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 170), "Sample text", fill =(0, 255, 0),font=myFont) # show and save the imageimg.show()img.save("results.jpeg") Output: Image after changing colour of text Example 3: To change the text change the text field in step 5. Python3 # Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using open function# and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using Draw# function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 170), "Sample text 2", fill=(0, 255, 0), font=myFont) # show and save the imageimg.show()img.save("results.jpeg") Output: Image after changing text field Example 4: To change the size of the text go to step 4 and change the size. Python3 # Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using# open function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using# Draw function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 30) # Decide the text location, color and fontd1.text((65, 170), "Sample text", fill = (0, 255, 0),font=myFont) # show and save the imageimg.show()img.save("results.jpeg") Output: Image after changing text size Example 5: To change the text font go to step 4. Python3 # Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using open function and# assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using Draw# function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/00006_44s.ttf', 30) # Decide the text location, color and fontd1.text((0, 170), "Sample text", fill =(0, 255, 0),font=myFont) # show and save the imageimg.show()img.save("results.jpeg") Output: Image after changing font style sooda367 Picked Python-pil Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jul, 2021" }, { "code": null, "e": 140, "s": 52, "text": "In this article, we will see how to write text on images with the Python Pillow module." }, { "code": null, "e": 250, "s": 140, "text": "This module is not preloaded with Python. So to install it execute the following command in the command-line:" }, { "code": null, "e": 269, "s": 250, "text": "pip install pillow" }, { "code": null, "e": 294, "s": 269, "text": "Stepwise implementation:" }, { "code": null, "e": 324, "s": 294, "text": "Step 1: Import Pillow library" }, { "code": null, "e": 464, "s": 324, "text": "To complete this task the functions required from the Pillow library are: Image, ImageDraw, ImageFont. All these functions are imported as:" }, { "code": null, "e": 508, "s": 464, "text": "from PIL import Image, ImageDraw, ImageFont" }, { "code": null, "e": 530, "s": 508, "text": "Step 2: Open an image" }, { "code": null, "e": 767, "s": 530, "text": "In this step, the image on which we are going to add text is imported and open by using the “Image.open(‘Image_name’)”. In the given case the gfg logo is used to add the text on it. The image name is gfg_logo.jpeg. So, it is written as:" }, { "code": null, "e": 801, "s": 767, "text": "img = Image.open(‘gfg_logo.jpeg’)" }, { "code": null, "e": 826, "s": 801, "text": "Step 3: Image Conversion" }, { "code": null, "e": 1000, "s": 826, "text": "In this step, we convert our image into an editable format by using “ImageDraw.Draw(‘variable used to store the image in above step’)”. In the given case this is written as:" }, { "code": null, "e": 1025, "s": 1000, "text": "d1 = ImageDraw.Draw(img)" }, { "code": null, "e": 1045, "s": 1025, "text": "Step 4: Font style." }, { "code": null, "e": 1442, "s": 1045, "text": "This step is optional. It is for those who want their text to look cool or stylish because someone won’t select any font style then the system takes the default font style. At first download the font style file from https://ttfonts.net/font/1004_Mistral.htm . After downloading the file use the function ImageFont.truetype(‘adddress_of_font_style’, font_style). In given cases this is written as:" }, { "code": null, "e": 1522, "s": 1442, "text": "myFont = ImageFont.truetype(‘/home/raghav/PycharmProjects/gfg/Mistral.ttf’, 20)" }, { "code": null, "e": 1546, "s": 1522, "text": "Step 5: Render the text" }, { "code": null, "e": 1643, "s": 1546, "text": "This is the main step in which the whole properties of the font get decided. This is written as:" }, { "code": null, "e": 1707, "s": 1643, "text": "d1.text((65, 10), “Sample text”, fill =(255, 0, 0),font=myFont)" }, { "code": null, "e": 1823, "s": 1707, "text": "Starting Coordinates: Pillow library uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner." }, { "code": null, "e": 1872, "s": 1823, "text": "Text: String between single or double quotations" }, { "code": null, "e": 1981, "s": 1872, "text": "Text color in RGB format: For the color, you want you can check it to Google for its RGB color code and use." }, { "code": null, "e": 2035, "s": 1981, "text": "Font style: Download the font from Google and use it." }, { "code": null, "e": 2065, "s": 2035, "text": "Step 6: Show and Save result." }, { "code": null, "e": 2222, "s": 2065, "text": "The final step is to display the modified image on the screen for this img.show() function is used and to store the image img.save(“results.jpeg”) is used. " }, { "code": null, "e": 2251, "s": 2222, "text": "Below is the implementation:" }, { "code": null, "e": 2263, "s": 2251, "text": "Input Image" }, { "code": null, "e": 2271, "s": 2263, "text": "Python3" }, { "code": "# Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using open# function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using# Draw function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 10), \"Sample text\", fill =(255, 0, 0),font=myFont) # show and save the imageimg.show()img.save(\"results.jpeg\")", "e": 2985, "s": 2271, "text": null }, { "code": null, "e": 2998, "s": 2989, "text": "Output: " }, { "code": null, "e": 3025, "s": 3000, "text": "Image after modification" }, { "code": null, "e": 3107, "s": 3027, "text": "Example 1: To change the location of the text change the coordinates in step 5." }, { "code": null, "e": 3294, "s": 3109, "text": "The dimensions are changed from (65,100) to (65,170). So, the location of text goes down because from (x,y) coordinates the value of y-coordinate gets increased as shown in the output." }, { "code": null, "e": 3304, "s": 3296, "text": "Python3" }, { "code": "# Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using# open function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using# Draw function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 170), \"Sample text\", fill =(255, 0, 0),font=myFont) # show and save the imageimg.show()img.save(\"results.jpeg\")", "e": 4019, "s": 3304, "text": null }, { "code": null, "e": 4032, "s": 4023, "text": "Output: " }, { "code": null, "e": 4072, "s": 4034, "text": "Image after changing it’s coordinates" }, { "code": null, "e": 4141, "s": 4074, "text": "Example 2: To change the color of the text again change in step 5." }, { "code": null, "e": 4365, "s": 4143, "text": "There are RGB colour code on which Pillow work (R,G,B) R for RED, G for GREEN, B for Blue. In above case the R and B value is 0 and G value is 255 i.e. Maximum. So, the colour of text changes to green as shown in output." }, { "code": null, "e": 4375, "s": 4367, "text": "Python3" }, { "code": "# Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using# open function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using Draw function# and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 170), \"Sample text\", fill =(0, 255, 0),font=myFont) # show and save the imageimg.show()img.save(\"results.jpeg\")", "e": 5090, "s": 4375, "text": null }, { "code": null, "e": 5103, "s": 5094, "text": "Output: " }, { "code": null, "e": 5141, "s": 5105, "text": "Image after changing colour of text" }, { "code": null, "e": 5206, "s": 5143, "text": "Example 3: To change the text change the text field in step 5." }, { "code": null, "e": 5216, "s": 5208, "text": "Python3" }, { "code": "# Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using open function# and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using Draw# function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 20) # Decide the text location, color and fontd1.text((65, 170), \"Sample text 2\", fill=(0, 255, 0), font=myFont) # show and save the imageimg.show()img.save(\"results.jpeg\")", "e": 5933, "s": 5216, "text": null }, { "code": null, "e": 5942, "s": 5933, "text": "Output: " }, { "code": null, "e": 5974, "s": 5942, "text": "Image after changing text field" }, { "code": null, "e": 6050, "s": 5974, "text": "Example 4: To change the size of the text go to step 4 and change the size." }, { "code": null, "e": 6058, "s": 6050, "text": "Python3" }, { "code": "# Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using# open function and assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using# Draw function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/Mistral.ttf', 30) # Decide the text location, color and fontd1.text((65, 170), \"Sample text\", fill = (0, 255, 0),font=myFont) # show and save the imageimg.show()img.save(\"results.jpeg\")", "e": 6774, "s": 6058, "text": null }, { "code": null, "e": 6787, "s": 6778, "text": "Output: " }, { "code": null, "e": 6820, "s": 6789, "text": "Image after changing text size" }, { "code": null, "e": 6871, "s": 6822, "text": "Example 5: To change the text font go to step 4." }, { "code": null, "e": 6881, "s": 6873, "text": "Python3" }, { "code": "# Import Image for basic functionalities like open, save, show# Import ImageDraw to convert image into editable format# Import ImageFont to choose the font stylefrom PIL import Image, ImageDraw, ImageFont # gfg_logo.jpeg image opened using open function and# assigned to variable named imgimg = Image.open('gfg_logo.jpeg') # Image is converted into editable form using Draw# function and assigned to d1d1 = ImageDraw.Draw(img) # Font selection from the downloaded filemyFont = ImageFont.truetype('/home/raghav/PycharmProjects/gfg/00006_44s.ttf', 30) # Decide the text location, color and fontd1.text((0, 170), \"Sample text\", fill =(0, 255, 0),font=myFont) # show and save the imageimg.show()img.save(\"results.jpeg\")", "e": 7597, "s": 6881, "text": null }, { "code": null, "e": 7609, "s": 7601, "text": "Output:" }, { "code": null, "e": 7643, "s": 7611, "text": "Image after changing font style" }, { "code": null, "e": 7654, "s": 7645, "text": "sooda367" }, { "code": null, "e": 7661, "s": 7654, "text": "Picked" }, { "code": null, "e": 7672, "s": 7661, "text": "Python-pil" }, { "code": null, "e": 7679, "s": 7672, "text": "Python" } ]
Multiple of x closest to n
27 Apr, 2021 Given two numbers n and x, we need to calculate the smallest value of x that is closest to given number n.Examples: Input : n = 9, x = 4 Output : 8 Input : n = 2855, x = 13 Output : 2860 Input : n = 46426171, x = 43 Output : 46426154 Input : n = 1, x = 3 Output : 3 We need to find a k such that x*k is closest to n. If we do k = n/x, we get a value of k that may not lead to maximum. We can get closest by comparing the values floor(n/x) * x and ceil(n/x) * x.Below is an interesting solution that doesn’t require computations of floor(n/x) and ceil(n/x). The idea is to do following two steps. n = n + x/2; n = n - (n%x); result = n Let us consider below example n = 2855 x = 13 n = 2855 + 13/2 = 2861 n = 2861 - (2861 % 13) = 2861 - 1 = 2860 Below are implementations of above steps. C++ Java Python3 C# PHP Javascript // CPP program to calculate the smallest multiple// of x closest to a given number#include <bits/stdc++.h>using namespace std; // Function to calculate the smallest multipleint closestMultiple(int n, int x){ if(x>n) return x; n = n + x/2; n = n - (n%x); return n;} // driver programint main(){ int n = 9, x = 4; printf("%d", closestMultiple(n, x)); return 0;} // Java program to calculate the smallest// multiple of x closest to a given numberimport java.io.*;class Solution{ // Function to calculate the smallest multiple static int closestMultiple(int n, int x) { if(x>n) return x; n = n + x/2; n = n - (n%x); return n; } // driver program public static void main (String[] args) { int n = 56287, x = 27; System.out.println(closestMultiple(n, x)); }} # Python3 program to calculate# the smallest multiple of x# closest to a given number # Function to calculate# the smallest multipledef closestMultiple(n, x): if x > n: return x; z = (int)(x / 2); n = n + z; n = n - (n % x); return n; # Driver Coden = 56287;x = 27;print(closestMultiple(n, x)); # This code is contributed# by mits // C# program to calculate smallest// multiple of x closest to a// given numberusing System; class Solution { // Function to calculate the // smallest multiple static int closestMultiple(int n, int x) { if (x > n) return x; n = n + x / 2; n = n - (n % x); return n; } // Driver program public static void Main() { int n = 56287, x = 27; Console.WriteLine(closestMultiple(n, x)); }} // This code is contributed by Anant Agarwal. <?php// PHP program to calculate// the smallest multiple// of x closest to a// given number // Function to calculate// the smallest multiplefunction closestMultiple($n, $x){ if($x > $n) return $x; $n = $n + $x / 2; $n = $n - ($n % $x); return $n;} // Driver Code $n = 9; $x = 4; echo closestMultiple($n, $x); // This code is contributed by ajit?> <script> // Javascript program to calculate smallest // multiple of x closest to a // given number // Function to calculate the // smallest multiple function closestMultiple(n, x) { if (x > n) return x; n = n + parseInt(x / 2, 10); n = n - (n % x); return n; } let n = 56287, x = 27; document.write(closestMultiple(n, x)); // This code is contributed by rameshtravel07.</script> Output: 56295 This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar rameshtravel07 Mathematical Misc School Programming Misc Mathematical Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Overview of Data Structures | Set 1 (Linear Data Structures) vector::push_back() and vector::pop_back() in C++ STL Top 10 algorithms in Interview Questions Virtualization In Cloud Computing and Types How to write Regular Expressions?
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Apr, 2021" }, { "code": null, "e": 170, "s": 52, "text": "Given two numbers n and x, we need to calculate the smallest value of x that is closest to given number n.Examples: " }, { "code": null, "e": 330, "s": 170, "text": "Input : n = 9, x = 4\nOutput : 8\n\nInput : n = 2855, x = 13\nOutput : 2860\n\nInput : n = 46426171, x = 43\nOutput : 46426154\n\nInput : n = 1, x = 3\nOutput : 3" }, { "code": null, "e": 664, "s": 332, "text": "We need to find a k such that x*k is closest to n. If we do k = n/x, we get a value of k that may not lead to maximum. We can get closest by comparing the values floor(n/x) * x and ceil(n/x) * x.Below is an interesting solution that doesn’t require computations of floor(n/x) and ceil(n/x). The idea is to do following two steps. " }, { "code": null, "e": 715, "s": 664, "text": " n = n + x/2;\n n = n - (n%x);\n result = n" }, { "code": null, "e": 747, "s": 715, "text": "Let us consider below example " }, { "code": null, "e": 850, "s": 747, "text": " n = 2855 \n x = 13\n\n n = 2855 + 13/2\n = 2861\n n = 2861 - (2861 % 13)\n = 2861 - 1\n = 2860 " }, { "code": null, "e": 893, "s": 850, "text": "Below are implementations of above steps. " }, { "code": null, "e": 897, "s": 893, "text": "C++" }, { "code": null, "e": 902, "s": 897, "text": "Java" }, { "code": null, "e": 910, "s": 902, "text": "Python3" }, { "code": null, "e": 913, "s": 910, "text": "C#" }, { "code": null, "e": 917, "s": 913, "text": "PHP" }, { "code": null, "e": 928, "s": 917, "text": "Javascript" }, { "code": "// CPP program to calculate the smallest multiple// of x closest to a given number#include <bits/stdc++.h>using namespace std; // Function to calculate the smallest multipleint closestMultiple(int n, int x){ if(x>n) return x; n = n + x/2; n = n - (n%x); return n;} // driver programint main(){ int n = 9, x = 4; printf(\"%d\", closestMultiple(n, x)); return 0;}", "e": 1318, "s": 928, "text": null }, { "code": "// Java program to calculate the smallest// multiple of x closest to a given numberimport java.io.*;class Solution{ // Function to calculate the smallest multiple static int closestMultiple(int n, int x) { if(x>n) return x; n = n + x/2; n = n - (n%x); return n; } // driver program public static void main (String[] args) { int n = 56287, x = 27; System.out.println(closestMultiple(n, x)); }}", "e": 1790, "s": 1318, "text": null }, { "code": "# Python3 program to calculate# the smallest multiple of x# closest to a given number # Function to calculate# the smallest multipledef closestMultiple(n, x): if x > n: return x; z = (int)(x / 2); n = n + z; n = n - (n % x); return n; # Driver Coden = 56287;x = 27;print(closestMultiple(n, x)); # This code is contributed# by mits", "e": 2143, "s": 1790, "text": null }, { "code": "// C# program to calculate smallest// multiple of x closest to a// given numberusing System; class Solution { // Function to calculate the // smallest multiple static int closestMultiple(int n, int x) { if (x > n) return x; n = n + x / 2; n = n - (n % x); return n; } // Driver program public static void Main() { int n = 56287, x = 27; Console.WriteLine(closestMultiple(n, x)); }} // This code is contributed by Anant Agarwal.", "e": 2653, "s": 2143, "text": null }, { "code": "<?php// PHP program to calculate// the smallest multiple// of x closest to a// given number // Function to calculate// the smallest multiplefunction closestMultiple($n, $x){ if($x > $n) return $x; $n = $n + $x / 2; $n = $n - ($n % $x); return $n;} // Driver Code $n = 9; $x = 4; echo closestMultiple($n, $x); // This code is contributed by ajit?>", "e": 3033, "s": 2653, "text": null }, { "code": "<script> // Javascript program to calculate smallest // multiple of x closest to a // given number // Function to calculate the // smallest multiple function closestMultiple(n, x) { if (x > n) return x; n = n + parseInt(x / 2, 10); n = n - (n % x); return n; } let n = 56287, x = 27; document.write(closestMultiple(n, x)); // This code is contributed by rameshtravel07.</script>", "e": 3504, "s": 3033, "text": null }, { "code": null, "e": 3514, "s": 3504, "text": "Output: " }, { "code": null, "e": 3521, "s": 3514, "text": " 56295" }, { "code": null, "e": 3942, "s": 3521, "text": "This article is contributed by Pramod Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 3948, "s": 3942, "text": "jit_t" }, { "code": null, "e": 3961, "s": 3948, "text": "Mithun Kumar" }, { "code": null, "e": 3976, "s": 3961, "text": "rameshtravel07" }, { "code": null, "e": 3989, "s": 3976, "text": "Mathematical" }, { "code": null, "e": 3994, "s": 3989, "text": "Misc" }, { "code": null, "e": 4013, "s": 3994, "text": "School Programming" }, { "code": null, "e": 4018, "s": 4013, "text": "Misc" }, { "code": null, "e": 4031, "s": 4018, "text": "Mathematical" }, { "code": null, "e": 4036, "s": 4031, "text": "Misc" }, { "code": null, "e": 4134, "s": 4036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4158, "s": 4134, "text": "Merge two sorted arrays" }, { "code": null, "e": 4179, "s": 4158, "text": "Operators in C / C++" }, { "code": null, "e": 4201, "s": 4179, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 4215, "s": 4201, "text": "Prime Numbers" }, { "code": null, "e": 4257, "s": 4215, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 4318, "s": 4257, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 4372, "s": 4318, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 4413, "s": 4372, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 4457, "s": 4413, "text": "Virtualization In Cloud Computing and Types" } ]
Node.js socket.send() Method
06 May, 2021 The socket.send() method is an inbuilt application programming interface of class Socket within dgram module which is used to send the message from one socket to another socket. Syntax: socket.send(msg[, offset, length][, port][, address][, callback]) Parameters: This method takes the following parameter: msg: Message to be sent. offset: Offset in the buffer where the message starts. length: Number of bytes in the message. port: Destination port. address: Destination host name or IP address. callback: Called when the message has been sent. Return Value: This method does not return any value. Example 1: Filename: index.js Javascript // Node.js program to demonstrate the// server.send() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket("udp4");var server = dgram.createSocket("udp4"); // Catching the message eventserver.on("message", function (msg) { // Displaying the client messageprocess.stdout.write("UDP String: " + msg + "\n"); // Exiting processprocess.exit();}) // Binding server with port .bind(1234, () => { // Getting the reference of the server // by using ref() method const size = server.ref(); // Display the result console.log(size.eventNames());}); // Client sending message to server// by using send() methodclient.send("Hello", 0, 7, 1234, "localhost"); Output: [ 'message' ] UDP String: Hello Example 2: Filename: index.js Javascript // Node.js program to demonstrate the// server.send() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket("udp4");var server = dgram.createSocket("udp4"); // Catching the message eventserver.on("message", function (msg) { // Displaying the client message process.stdout.write("UDP String: " + msg + "\n"); // Exiting process process.exit();}); // Catching the listening eventserver.on('listening', () => { // Getting address information for the server const address = server.address(); // Display the result console.log(`server listening ${address.address}:${address.port}`);}); // Binding server with port address// by using bind() methodserver.bind(1234, () => { // Getting the reference of server // by using ref() method const size = server.ref(); // display the result console.log(size.eventNames());}); // Client sending message to server// by using send() methodclient.send("Hello", 0, 7, 1234, "localhost", (err) =>{ if(err) throw err; console.log("message sent");}); Output: server listening 0.0.0.0:1234 [ 'message', 'listening' ] message sent UDP String: Hello Run the index.js file using the following command: node index.js Reference: https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_send_msg_offset_length_port_address_callback sweetyty Node.js-Methods Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n06 May, 2021" }, { "code": null, "e": 207, "s": 28, "text": "The socket.send() method is an inbuilt application programming interface of class Socket within dgram module which is used to send the message from one socket to another socket." }, { "code": null, "e": 215, "s": 207, "text": "Syntax:" }, { "code": null, "e": 281, "s": 215, "text": "socket.send(msg[, offset, length][, port][, address][, callback])" }, { "code": null, "e": 336, "s": 281, "text": "Parameters: This method takes the following parameter:" }, { "code": null, "e": 361, "s": 336, "text": "msg: Message to be sent." }, { "code": null, "e": 416, "s": 361, "text": "offset: Offset in the buffer where the message starts." }, { "code": null, "e": 456, "s": 416, "text": "length: Number of bytes in the message." }, { "code": null, "e": 480, "s": 456, "text": "port: Destination port." }, { "code": null, "e": 526, "s": 480, "text": "address: Destination host name or IP address." }, { "code": null, "e": 575, "s": 526, "text": "callback: Called when the message has been sent." }, { "code": null, "e": 628, "s": 575, "text": "Return Value: This method does not return any value." }, { "code": null, "e": 658, "s": 628, "text": "Example 1: Filename: index.js" }, { "code": null, "e": 669, "s": 658, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// server.send() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket(\"udp4\");var server = dgram.createSocket(\"udp4\"); // Catching the message eventserver.on(\"message\", function (msg) { // Displaying the client messageprocess.stdout.write(\"UDP String: \" + msg + \"\\n\"); // Exiting processprocess.exit();}) // Binding server with port .bind(1234, () => { // Getting the reference of the server // by using ref() method const size = server.ref(); // Display the result console.log(size.eventNames());}); // Client sending message to server// by using send() methodclient.send(\"Hello\", 0, 7, 1234, \"localhost\");", "e": 1420, "s": 669, "text": null }, { "code": null, "e": 1428, "s": 1420, "text": "Output:" }, { "code": null, "e": 1460, "s": 1428, "text": "[ 'message' ]\nUDP String: Hello" }, { "code": null, "e": 1490, "s": 1460, "text": "Example 2: Filename: index.js" }, { "code": null, "e": 1501, "s": 1490, "text": "Javascript" }, { "code": "// Node.js program to demonstrate the// server.send() method // Importing dgram modulevar dgram = require('dgram'); // Creating and initializing client// and server socketvar client = dgram.createSocket(\"udp4\");var server = dgram.createSocket(\"udp4\"); // Catching the message eventserver.on(\"message\", function (msg) { // Displaying the client message process.stdout.write(\"UDP String: \" + msg + \"\\n\"); // Exiting process process.exit();}); // Catching the listening eventserver.on('listening', () => { // Getting address information for the server const address = server.address(); // Display the result console.log(`server listening ${address.address}:${address.port}`);}); // Binding server with port address// by using bind() methodserver.bind(1234, () => { // Getting the reference of server // by using ref() method const size = server.ref(); // display the result console.log(size.eventNames());}); // Client sending message to server// by using send() methodclient.send(\"Hello\", 0, 7, 1234, \"localhost\", (err) =>{ if(err) throw err; console.log(\"message sent\");});", "e": 2597, "s": 1501, "text": null }, { "code": null, "e": 2605, "s": 2597, "text": "Output:" }, { "code": null, "e": 2693, "s": 2605, "text": "server listening 0.0.0.0:1234\n[ 'message', 'listening' ]\nmessage sent\nUDP String: Hello" }, { "code": null, "e": 2744, "s": 2693, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 2758, "s": 2744, "text": "node index.js" }, { "code": null, "e": 2884, "s": 2758, "text": "Reference: https://nodejs.org/dist/latest-v12.x/docs/api/dgram.html#dgram_socket_send_msg_offset_length_port_address_callback" }, { "code": null, "e": 2893, "s": 2884, "text": "sweetyty" }, { "code": null, "e": 2909, "s": 2893, "text": "Node.js-Methods" }, { "code": null, "e": 2917, "s": 2909, "text": "Node.js" }, { "code": null, "e": 2934, "s": 2917, "text": "Web Technologies" } ]
Storage of integer and character values in C
25 Jul, 2018 Integer and character variables are used so often in the programs, but how these values are actually stored in C are known to few.Below are a few examples to understand this: Taking a positive integer value as char:#include <stdio.h>int main(){ char a = 278; printf("%d", a); return 0;}Output:22 Explanation: First, compiler converts 278 from decimal number system to binary number system(100010110) internally and then takes into consideration only the first 8 bits from the right of that number represented in binary and stores this value in the variable a. It will also give warning for overflow. #include <stdio.h>int main(){ char a = 278; printf("%d", a); return 0;} 22 Explanation: First, compiler converts 278 from decimal number system to binary number system(100010110) internally and then takes into consideration only the first 8 bits from the right of that number represented in binary and stores this value in the variable a. It will also give warning for overflow. Taking a negative integer value as char:#include <stdio.h>int main(){ char a = -129; printf("%d", a); return 0;}Output:127 Explanation: First of all, it should be understood that negative numbers are stored in the 2’s complement form of their positive counterpart. The compiler converts 129 from decimal number system to binary number system(10000001) internally, and then, all the zeroes would be changed to one and one to zeroes(i.e. do one’s complement)(01111110) and one would be added to the one’s complement through binary addition to give the two’s complement of that number (01111111). Now, the rightmost 8 bits of the two’s complement would be taken and stored as it is in the variable a. It will also give warning for overflow. #include <stdio.h>int main(){ char a = -129; printf("%d", a); return 0;} 127 Explanation: First of all, it should be understood that negative numbers are stored in the 2’s complement form of their positive counterpart. The compiler converts 129 from decimal number system to binary number system(10000001) internally, and then, all the zeroes would be changed to one and one to zeroes(i.e. do one’s complement)(01111110) and one would be added to the one’s complement through binary addition to give the two’s complement of that number (01111111). Now, the rightmost 8 bits of the two’s complement would be taken and stored as it is in the variable a. It will also give warning for overflow. Note: The same concept is used to store the integer variables with one difference that the number of bits taken at the end is 16(2 bytes) or 32(4 bytes) bits because the size of int variables is 2 or 4 bytes. C Basics C Language GFacts Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation in C Return values of printf() and scanf() in C/C++ What are the Operators that Can be and Cannot be Overloaded in C++? How are variables scoped in C - Static or Dynamic? G-Fact 19 (Logical and Bitwise Not Operators on Boolean) Difference between YOLO and SSD
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Jul, 2018" }, { "code": null, "e": 229, "s": 54, "text": "Integer and character variables are used so often in the programs, but how these values are actually stored in C are known to few.Below are a few examples to understand this:" }, { "code": null, "e": 665, "s": 229, "text": "Taking a positive integer value as char:#include <stdio.h>int main(){ char a = 278; printf(\"%d\", a); return 0;}Output:22\nExplanation: First, compiler converts 278 from decimal number system to binary number system(100010110) internally and then takes into consideration only the first 8 bits from the right of that number represented in binary and stores this value in the variable a. It will also give warning for overflow." }, { "code": "#include <stdio.h>int main(){ char a = 278; printf(\"%d\", a); return 0;}", "e": 748, "s": 665, "text": null }, { "code": null, "e": 752, "s": 748, "text": "22\n" }, { "code": null, "e": 1056, "s": 752, "text": "Explanation: First, compiler converts 278 from decimal number system to binary number system(100010110) internally and then takes into consideration only the first 8 bits from the right of that number represented in binary and stores this value in the variable a. It will also give warning for overflow." }, { "code": null, "e": 1805, "s": 1056, "text": "Taking a negative integer value as char:#include <stdio.h>int main(){ char a = -129; printf(\"%d\", a); return 0;}Output:127\nExplanation: First of all, it should be understood that negative numbers are stored in the 2’s complement form of their positive counterpart. The compiler converts 129 from decimal number system to binary number system(10000001) internally, and then, all the zeroes would be changed to one and one to zeroes(i.e. do one’s complement)(01111110) and one would be added to the one’s complement through binary addition to give the two’s complement of that number (01111111). Now, the rightmost 8 bits of the two’s complement would be taken and stored as it is in the variable a. It will also give warning for overflow." }, { "code": "#include <stdio.h>int main(){ char a = -129; printf(\"%d\", a); return 0;}", "e": 1889, "s": 1805, "text": null }, { "code": null, "e": 1894, "s": 1889, "text": "127\n" }, { "code": null, "e": 2509, "s": 1894, "text": "Explanation: First of all, it should be understood that negative numbers are stored in the 2’s complement form of their positive counterpart. The compiler converts 129 from decimal number system to binary number system(10000001) internally, and then, all the zeroes would be changed to one and one to zeroes(i.e. do one’s complement)(01111110) and one would be added to the one’s complement through binary addition to give the two’s complement of that number (01111111). Now, the rightmost 8 bits of the two’s complement would be taken and stored as it is in the variable a. It will also give warning for overflow." }, { "code": null, "e": 2718, "s": 2509, "text": "Note: The same concept is used to store the integer variables with one difference that the number of bits taken at the end is 16(2 bytes) or 32(4 bytes) bits because the size of int variables is 2 or 4 bytes." }, { "code": null, "e": 2727, "s": 2718, "text": "C Basics" }, { "code": null, "e": 2738, "s": 2727, "text": "C Language" }, { "code": null, "e": 2745, "s": 2738, "text": "GFacts" }, { "code": null, "e": 2843, "s": 2745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2891, "s": 2843, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 2912, "s": 2891, "text": "Operators in C / C++" }, { "code": null, "e": 2938, "s": 2912, "text": "Exception Handling in C++" }, { "code": null, "e": 2983, "s": 2938, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 3021, "s": 2983, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 3068, "s": 3021, "text": "Return values of printf() and scanf() in C/C++" }, { "code": null, "e": 3136, "s": 3068, "text": "What are the Operators that Can be and Cannot be Overloaded in C++?" }, { "code": null, "e": 3187, "s": 3136, "text": "How are variables scoped in C - Static or Dynamic?" }, { "code": null, "e": 3244, "s": 3187, "text": "G-Fact 19 (Logical and Bitwise Not Operators on Boolean)" } ]
Python | Miscellaneous | Question 4
28 Jun, 2021 What is the output of the following program : print 0.1 + 0.2 == 0.3 (A) True(B) False(C) Machine dependent(D) ErrorAnswer: (B)Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off errors from 0.1 and 0.2 accumulate and hence there is a difference of 5.5511e-17 between (0.1 + 0.2) and 0.3.Quiz of this QuestionPlease comment below if you find anything wrong in the above post amartyaghoshgfg Miscellaneous Python-Miscellaneous Python-Quizzes Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python-Quizzes | Python List Quiz | Question 4 Python-Quizzes | Python List Quiz | Question 5 Python-Quizzes | Python Dictionary Quiz | Question 25 Output of Python Program - Dictionary (set 25) Why do people prefer Selenium with Python? Python-Quizzes | Python Dictionary Quiz | Question 23 Python | Animated Banner showing 'GeeksForGeeks' Python-Quizzes | Data Type | Question 3 Python | Output Type | Question 4 Python-Quizzes | Python Dictionary Quiz | Question 1
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jun, 2021" }, { "code": null, "e": 100, "s": 54, "text": "What is the output of the following program :" }, { "code": "print 0.1 + 0.2 == 0.3", "e": 123, "s": 100, "text": null }, { "code": null, "e": 473, "s": 123, "text": "(A) True(B) False(C) Machine dependent(D) ErrorAnswer: (B)Explanation: Neither of 0.1, 0.2 and 0.3 can be represented accurately in binary. The round off errors from 0.1 and 0.2 accumulate and hence there is a difference of 5.5511e-17 between (0.1 + 0.2) and 0.3.Quiz of this QuestionPlease comment below if you find anything wrong in the above post" }, { "code": null, "e": 489, "s": 473, "text": "amartyaghoshgfg" }, { "code": null, "e": 503, "s": 489, "text": "Miscellaneous" }, { "code": null, "e": 524, "s": 503, "text": "Python-Miscellaneous" }, { "code": null, "e": 539, "s": 524, "text": "Python-Quizzes" }, { "code": null, "e": 637, "s": 539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 684, "s": 637, "text": "Python-Quizzes | Python List Quiz | Question 4" }, { "code": null, "e": 731, "s": 684, "text": "Python-Quizzes | Python List Quiz | Question 5" }, { "code": null, "e": 785, "s": 731, "text": "Python-Quizzes | Python Dictionary Quiz | Question 25" }, { "code": null, "e": 832, "s": 785, "text": "Output of Python Program - Dictionary (set 25)" }, { "code": null, "e": 875, "s": 832, "text": "Why do people prefer Selenium with Python?" }, { "code": null, "e": 929, "s": 875, "text": "Python-Quizzes | Python Dictionary Quiz | Question 23" }, { "code": null, "e": 978, "s": 929, "text": "Python | Animated Banner showing 'GeeksForGeeks'" }, { "code": null, "e": 1018, "s": 978, "text": "Python-Quizzes | Data Type | Question 3" }, { "code": null, "e": 1052, "s": 1018, "text": "Python | Output Type | Question 4" } ]
Matplotlib.dates.drange() in Python
19 Apr, 2020 Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The matplotlib.dates.drange() function returns a sequence of equally spaced Matplotlib dates. The date range starts from ‘dstart’ and go up to, but not including ‘dend’. The space between each date is called delta. Syntax: matplotlib.dates.drange(dstart, dend, delta) Parameters: dstart: Starting point of the date range and is a python’s datetime date.dend: Ending point of the date range and is a python’s datetime date.delta: It represents the spacing between each dates and belongs to python’s datetime.timedelta. dstart: Starting point of the date range and is a python’s datetime date. dend: Ending point of the date range and is a python’s datetime date. delta: It represents the spacing between each dates and belongs to python’s datetime.timedelta. Returns: It returns a numpy array which is a list of floats representing Matplotlib dates. Example 1: import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date_1 = datetime.datetime( 2020, 3, 2)date_2 = datetime.datetime( 2020, 10, 10) time_delta = datetime.timedelta(days = 28)dates = drange(date_1, date_2, time_delta) y_axis = np.arange( len(dates) ) fig, ax = plt.subplots()ax.plot_date(dates, y_axis * y_axis) ax.xaxis.set_major_formatter( DateFormatter('% Y-% m') ) plt.show() Output: Example 2: import datetimeimport matplotlib.pyplot as pltimport matplotlib.dates as mdates date = [datetime.datetime(2020, 8, 24, 0, 0), datetime.datetime(2020, 8, 23, 0, 0), datetime.datetime(2020, 8, 22, 0, 0), datetime.datetime(2020, 8, 21, 0, 0), datetime.datetime(2020, 8, 18, 0, 0), datetime.datetime(2020, 8, 17, 0, 0), datetime.datetime(2020, 8, 16, 0, 0), datetime.datetime(2020, 8, 15, 0, 0), datetime.datetime(2020, 8, 14, 0, 0), datetime.datetime(2020, 8, 11, 0, 0), datetime.datetime(2020, 8, 10, 0, 0), datetime.datetime(2020, 8, 9, 0, 0), datetime.datetime(2020, 8, 8, 0, 0), datetime.datetime(2020, 8, 7, 0, 0), datetime.datetime(2020, 8, 4, 0, 0), datetime.datetime(2020, 8, 3, 0, 0), datetime.datetime(2020, 8, 2, 0, 0), datetime.datetime(2020, 8, 1, 0, 0)] # is a datetime.datetime object # according to typestart_date = date[0] # is a datetime.datetime object according # to type end_date = date[-1]delta = datetime.timedelta(days = 5) # the drange functiondates = mdates.drange(start_date, end_date, -delta)y_data = range(len(dates)) plt.plot(dates, y_data) Output: Python-matplotlib Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack." }, { "code": null, "e": 455, "s": 240, "text": "The matplotlib.dates.drange() function returns a sequence of equally spaced Matplotlib dates. The date range starts from ‘dstart’ and go up to, but not including ‘dend’. The space between each date is called delta." }, { "code": null, "e": 508, "s": 455, "text": "Syntax: matplotlib.dates.drange(dstart, dend, delta)" }, { "code": null, "e": 520, "s": 508, "text": "Parameters:" }, { "code": null, "e": 758, "s": 520, "text": "dstart: Starting point of the date range and is a python’s datetime date.dend: Ending point of the date range and is a python’s datetime date.delta: It represents the spacing between each dates and belongs to python’s datetime.timedelta." }, { "code": null, "e": 832, "s": 758, "text": "dstart: Starting point of the date range and is a python’s datetime date." }, { "code": null, "e": 902, "s": 832, "text": "dend: Ending point of the date range and is a python’s datetime date." }, { "code": null, "e": 998, "s": 902, "text": "delta: It represents the spacing between each dates and belongs to python’s datetime.timedelta." }, { "code": null, "e": 1089, "s": 998, "text": "Returns: It returns a numpy array which is a list of floats representing Matplotlib dates." }, { "code": null, "e": 1100, "s": 1089, "text": "Example 1:" }, { "code": "import datetimeimport matplotlib.pyplot as pltfrom matplotlib.dates import DayLocator, HourLocator, DateFormatter, drangeimport numpy as np date_1 = datetime.datetime( 2020, 3, 2)date_2 = datetime.datetime( 2020, 10, 10) time_delta = datetime.timedelta(days = 28)dates = drange(date_1, date_2, time_delta) y_axis = np.arange( len(dates) ) fig, ax = plt.subplots()ax.plot_date(dates, y_axis * y_axis) ax.xaxis.set_major_formatter( DateFormatter('% Y-% m') ) plt.show()", "e": 1576, "s": 1100, "text": null }, { "code": null, "e": 1584, "s": 1576, "text": "Output:" }, { "code": null, "e": 1595, "s": 1584, "text": "Example 2:" }, { "code": "import datetimeimport matplotlib.pyplot as pltimport matplotlib.dates as mdates date = [datetime.datetime(2020, 8, 24, 0, 0), datetime.datetime(2020, 8, 23, 0, 0), datetime.datetime(2020, 8, 22, 0, 0), datetime.datetime(2020, 8, 21, 0, 0), datetime.datetime(2020, 8, 18, 0, 0), datetime.datetime(2020, 8, 17, 0, 0), datetime.datetime(2020, 8, 16, 0, 0), datetime.datetime(2020, 8, 15, 0, 0), datetime.datetime(2020, 8, 14, 0, 0), datetime.datetime(2020, 8, 11, 0, 0), datetime.datetime(2020, 8, 10, 0, 0), datetime.datetime(2020, 8, 9, 0, 0), datetime.datetime(2020, 8, 8, 0, 0), datetime.datetime(2020, 8, 7, 0, 0), datetime.datetime(2020, 8, 4, 0, 0), datetime.datetime(2020, 8, 3, 0, 0), datetime.datetime(2020, 8, 2, 0, 0), datetime.datetime(2020, 8, 1, 0, 0)] # is a datetime.datetime object # according to typestart_date = date[0] # is a datetime.datetime object according # to type end_date = date[-1]delta = datetime.timedelta(days = 5) # the drange functiondates = mdates.drange(start_date, end_date, -delta)y_data = range(len(dates)) plt.plot(dates, y_data)", "e": 2794, "s": 1595, "text": null }, { "code": null, "e": 2802, "s": 2794, "text": "Output:" }, { "code": null, "e": 2820, "s": 2802, "text": "Python-matplotlib" }, { "code": null, "e": 2827, "s": 2820, "text": "Python" }, { "code": null, "e": 2843, "s": 2827, "text": "Write From Home" } ]
D3.js nest.key() Function
19 Jul, 2020 nest.key() function in D3.js is used to register a new key function which is invoked for each element in the input array. Whenever a new key is registered, it is then pushed in the array to the end. Syntax: nest.keys(key) Parameters: It takes only one parameter i.e the key function. Return: It returns a string identifier. Below given are few examples that explain the function in a better way. Example 1: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style> .originalColor{ height: 100px; width: 100px; } .darkerColor{ height: 100px; width: 100px; }</style><body> <!-- Fetching from CDN of D3.js --> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"></script> <script> let collection=[ {val:"val1"}, {val:"val2"}, {val:"val3"}, {val:"val4"} ] let data=d3.nest().key((d)=>{return d.val}) .entries(collection) console.log(data); </script></body></html> Output: Example 2: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><style> .originalColor{ height: 100px; width: 100px; } .darkerColor{ height: 100px; width: 100px; }</style><body> <!--fetching from CDN of D3.js --> <script type = "text/javascript" src = "https://d3js.org/d3.v4.min.js"> </script> <script> let collection=[ {val:"val1", data:"data1", anotherData:"data1"}, {val:"val2", data:"data2", anotherData:"data2"}, {val:"val3", data:"data3", anotherData:"data3"}, {val:"val4", data:"data4", anotherData:"data4"} ] //key is added let data=d3.nest().key((d)=>{return d.val}) //another key is nested and added .key((d)=>{return d.data}) //another key is added and nested .key((d)=>{return d.anotherData}) .entries(collection) console.log(data); </script></body></html> Output: D3.js JavaScript 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": "\n19 Jul, 2020" }, { "code": null, "e": 227, "s": 28, "text": "nest.key() function in D3.js is used to register a new key function which is invoked for each element in the input array. Whenever a new key is registered, it is then pushed in the array to the end." }, { "code": null, "e": 235, "s": 227, "text": "Syntax:" }, { "code": null, "e": 250, "s": 235, "text": "nest.keys(key)" }, { "code": null, "e": 262, "s": 250, "text": "Parameters:" }, { "code": null, "e": 312, "s": 262, "text": "It takes only one parameter i.e the key function." }, { "code": null, "e": 352, "s": 312, "text": "Return: It returns a string identifier." }, { "code": null, "e": 424, "s": 352, "text": "Below given are few examples that explain the function in a better way." }, { "code": null, "e": 435, "s": 424, "text": "Example 1:" }, { "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></head><style> .originalColor{ height: 100px; width: 100px; } .darkerColor{ height: 100px; width: 100px; }</style><body> <!-- Fetching from CDN of D3.js --> <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"></script> <script> let collection=[ {val:\"val1\"}, {val:\"val2\"}, {val:\"val3\"}, {val:\"val4\"} ] let data=d3.nest().key((d)=>{return d.val}) .entries(collection) console.log(data); </script></body></html>", "e": 1134, "s": 435, "text": null }, { "code": null, "e": 1142, "s": 1134, "text": "Output:" }, { "code": null, "e": 1153, "s": 1142, "text": "Example 2:" }, { "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></head><style> .originalColor{ height: 100px; width: 100px; } .darkerColor{ height: 100px; width: 100px; }</style><body> <!--fetching from CDN of D3.js --> <script type = \"text/javascript\" src = \"https://d3js.org/d3.v4.min.js\"> </script> <script> let collection=[ {val:\"val1\", data:\"data1\", anotherData:\"data1\"}, {val:\"val2\", data:\"data2\", anotherData:\"data2\"}, {val:\"val3\", data:\"data3\", anotherData:\"data3\"}, {val:\"val4\", data:\"data4\", anotherData:\"data4\"} ] //key is added let data=d3.nest().key((d)=>{return d.val}) //another key is nested and added .key((d)=>{return d.data}) //another key is added and nested .key((d)=>{return d.anotherData}) .entries(collection) console.log(data); </script></body></html>", "e": 2223, "s": 1153, "text": null }, { "code": null, "e": 2231, "s": 2223, "text": "Output:" }, { "code": null, "e": 2237, "s": 2231, "text": "D3.js" }, { "code": null, "e": 2248, "s": 2237, "text": "JavaScript" }, { "code": null, "e": 2265, "s": 2248, "text": "Web Technologies" } ]
T-distributed Stochastic Neighbor Embedding(t-SNE) | by Renu Khandelwal | Towards Data Science
In this article, you will learn: Difference between t-SNE and PCA(Principal Component Analysis) Simple to understand explanation of how t-SNE works Understand different parameters available for t-SNE Applying t-SNE and PCA on MNIST What if you have hundreds of features or data points in a dataset, and you want to represent them in a 2-dimensional or 3-dimensional space? Two common techniques to reduce the dimensionality of a dataset while preserving the most information in the dataset are Principal Component Analysis(PCA) t-Distributed Stochastic Neighbour Embedding(t-SNE) Preserve as much significant structure or information of the data present in the high-dimensional data as possible in the low-dimensional representation. Increase the interpretability of the data in the lower dimension Minimizing information loss of data due to dimensionality reduction What are PCA and t-SNE, and what is the difference or similarity between the two? Both PCA and t-SNE are unsupervised dimensionality reduction techniques. Both techniques used to visualize the high dimensional data to a lower-dimensional space. An unsupervised, deterministic algorithm used for feature extraction as well as visualization Applies a linear dimensionality reduction technique where the focus is on keeping the dissimilar points far apart in a lower-dimensional space. Transforms the original data to a new data by preserving the variance in the data using eigenvalues. Outliers impact PCA. An unsupervised, randomized algorithm, used only for visualization Applies a non-linear dimensionality reduction technique where the focus is on keeping the very similar data points close together in lower-dimensional space. Preserves the local structure of the data using student t-distribution to compute the similarity between two points in lower-dimensional space. t-SNE uses a heavy-tailed Student-t distribution to compute the similarity between two points in the low-dimensional space rather than a Gaussian distribution, which helps to address the crowding and optimization problems. Outliers do not impact t-SNE T-distributed Stochastic Neighbor Embedding (t-SNE) is an unsupervised machine learning algorithm for visualization developed by Laurens van der Maaten and Geoffrey Hinton. How does t-SNE work? Step 1: Find the pairwise similarity between nearby points in a high dimensional space. t-SNE converts the high-dimensional Euclidean distances between datapoints xi and xj into conditional probabilities P(j|i). xi would pick xj as its neighbor based on the proportion of its probability density under a Gaussian centered at point xi. σi is the variance of the Gaussian that is centered on datapoint xi The probability density of a pair of a point is proportional to its similarity. For nearby data points, p(j|i) will be relatively high, and for points widely separated, p(j|i) will be minuscule. Symmetrize the conditional probabilities in high dimension space to get the final similarities in high dimensional space. Conditional probabilities are symmetrized by averaging the two probabilities, as shown below. Step 2: Map each point in high dimensional space to a low dimensional map based on the pairwise similarity of points in the high dimensional space. The low dimensional map will be either a 2-dimension or a 3-dimension map yi and yj are the low dimensional counterparts of the high-dimensional datapoints xi and xj. We compute the conditional probability q(j|i)similar to P(j]i) centered under a Gaussian centered at point yi and then symmetrize the probability. Step 3: Find a low-dimensional data representation that minimizes the mismatch between Pij and qij using gradient descent based on Kullback-Leibler divergence(KL Divergence) t-SNE optimizes the points in lower dimensional space using gradient descent. Why use KL divergence? When we minimize the KL divergence, it makes qij physically identical to Pij, so the structure of the data in high dimensional space will be similar to the structure of the data in low dimensional space. Based on the KL divergence equation, If Pij is large, then we need a large value for qij to represent local points with higher similarity. If Pij is small, then we need a smaller value for qij to represent local points that are far apart. Step 4: Use Student-t distribution to compute the similarity between two points in the low-dimensional space. t-SNE uses a heavy-tailed Student-t distribution with one degree of freedom to compute the similarity between two points in the low-dimensional space rather than a Gaussian distribution. T- distribution creates the probability distribution of points in lower dimensions space, and this helps reduce the crowding issue. How do I apply t-SNE on a dataset? Before we write the code in python, let’s understand a few critical parameters for TSNE that we can use n_components: Dimension of the embedded space, this is the lower dimension that we want the high dimension data to be converted to. The default value is 2 for 2-dimensional space. Perplexity: The perplexity is related to the number of nearest neighbors that are used in t-SNE algorithms. Larger datasets usually require a larger perplexity. Perplexity can have a value between 5 and 50. The default value is 30. n_iter: Maximum number of iterations for optimization. Should be at least 250 and the default value is 1000 learning_rate: The learning rate for t-SNE is usually in the range [10.0, 1000.0] with the default value of 200.0. We will apply PCA using sklearn.decomposition.PCA and implement t-SNE on using sklearn.manifold.TSNE on MNIST dataset. Loading the MNIST data Importing required libraries import timeimport numpy as npimport pandas as pd Get the MNIST training and test data and check the shape of the train data (X_train, y_train) , (X_test, y_test) = mnist.load_data()X_train.shape Create an array with a number of images and the pixel count in the image and copy the X_train data to X X = np.zeros((X_train.shape[0], 784))for i in range(X_train.shape[0]): X[i] = X_train[i].flatten() Shuffle the dataset, take 10% of the MNIST train data and store that in a data frame. X = pd.DataFrame(X)Y = pd.DataFrame(y_train)X = X.sample(frac=0.1, random_state=10).reset_index(drop=True)Y = Y.sample(frac=0.1, random_state=10).reset_index(drop=True)df = X After the data is ready, we can apply PCA and t-SNE. PCA is applied using the PCA library from sklearn.decomposition. from sklearn.decomposition import PCAtime_start = time.time()pca = PCA(n_components=2)pca_results = pca.fit_transform(df.values)print ('PCA done! Time elapsed: {} seconds'.format(time.time()-time_start)) PCA generates two dimensions, principal component 1 and principal component 2. Add the two PCA components along with the label to a data frame. pca_df = pd.DataFrame(data = pca_results , columns = ['pca_1', 'pca_2'])pca_df['label'] = Y The label is required only for visualization. Plotting the PCA results fig = plt.figure(figsize = (8,8))ax = fig.add_subplot(1,1,1) ax.set_xlabel('Principal Component 1', fontsize = 15)ax.set_ylabel('Principal Component 2', fontsize = 15)ax.set_title('2 component PCA', fontsize = 20)targets = [0,1,2,3,4,5,6,7,8,9]colors=['yellow', 'black', 'cyan', 'green', 'blue', 'red', 'brown','crimson', 'gold', 'indigo']for target, color in zip(targets,colors): indicesToKeep = pca_df['label'] == target ax.scatter(pca_df.loc[indicesToKeep, 'pca_1'] , pca_df.loc[indicesToKeep, 'pca_2'] , c = color , s = 50)ax.legend(targets)ax.grid() Importing the required libraries for t-SNE and visualization import timefrom sklearn.manifold import TSNEimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport seaborn as snsimport matplotlib.patheffects as PathEffects%matplotlib inline Create an instance of TSNE first with the default parameters and then fit high dimensional image input data into an embedded space and return that transformed output using fit_transform. The dimension of the image data should be of the shape (n_samples, n_features) time_start = time.time()tsne = TSNE(random=0)tsne_results = tsne.fit_transform(df.values)print ('t-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start)) Adding the labels to the data frame, and this will be used only during plotting to label the clusters for visualization. df['label'] = Y Function to visualize the data def plot_scatter(x, colors): # choose a color palette with seaborn. num_classes = len(np.unique(colors)) palette = np.array(sns.color_palette("hls", num_classes)) print(palette) # create a scatter plot. f = plt.figure(figsize=(8, 8)) ax = plt.subplot(aspect='equal') sc = ax.scatter(x[:,0], x[:,1], c=palette[colors.astype(np.int)], cmap=plt.cm.get_cmap('Paired')) plt.xlim(-25, 25) plt.ylim(-25, 25) ax.axis('off') ax.axis('tight')# add the labels for each digit corresponding to the label txts = []for i in range(num_classes):# Position of each label at median of data points.xtext, ytext = np.median(x[colors == i, :], axis=0) txt = ax.text(xtext, ytext, str(i), fontsize=24) txt.set_path_effects([ PathEffects.Stroke(linewidth=5, foreground="w"), PathEffects.Normal()]) txts.append(txt)return f, ax, sc, txts Visualize the -SNE results for MNIST dataset plot_scatter( tsne_results, df['label']) Try with different parameter values and observe the different plots Visualization for different values of perplexity Visualization for different values for n_iter We can see that the clusters generated from t-SNE plots are much more defined than the ones using PCA. PCA is deterministic, whereas t-SNE is not deterministic and is randomized. t-SNE tries to map only local neighbors whereas PCA is just a diagonal rotation of our initial covariance matrix and the eigenvectors represent and preserve the global properties Code is available here PCA and t-SNE are two common dimensionality reduction that uses different techniques to reduce high dimensional data into a lower-dimensional data that can be visualized. scikit-learn.org Visualizing Data using t-SNE by Laurens van der Maaten and Geoffrey Hinton.
[ { "code": null, "e": 205, "s": 172, "text": "In this article, you will learn:" }, { "code": null, "e": 268, "s": 205, "text": "Difference between t-SNE and PCA(Principal Component Analysis)" }, { "code": null, "e": 320, "s": 268, "text": "Simple to understand explanation of how t-SNE works" }, { "code": null, "e": 372, "s": 320, "text": "Understand different parameters available for t-SNE" }, { "code": null, "e": 404, "s": 372, "text": "Applying t-SNE and PCA on MNIST" }, { "code": null, "e": 545, "s": 404, "text": "What if you have hundreds of features or data points in a dataset, and you want to represent them in a 2-dimensional or 3-dimensional space?" }, { "code": null, "e": 666, "s": 545, "text": "Two common techniques to reduce the dimensionality of a dataset while preserving the most information in the dataset are" }, { "code": null, "e": 700, "s": 666, "text": "Principal Component Analysis(PCA)" }, { "code": null, "e": 752, "s": 700, "text": "t-Distributed Stochastic Neighbour Embedding(t-SNE)" }, { "code": null, "e": 906, "s": 752, "text": "Preserve as much significant structure or information of the data present in the high-dimensional data as possible in the low-dimensional representation." }, { "code": null, "e": 971, "s": 906, "text": "Increase the interpretability of the data in the lower dimension" }, { "code": null, "e": 1039, "s": 971, "text": "Minimizing information loss of data due to dimensionality reduction" }, { "code": null, "e": 1121, "s": 1039, "text": "What are PCA and t-SNE, and what is the difference or similarity between the two?" }, { "code": null, "e": 1284, "s": 1121, "text": "Both PCA and t-SNE are unsupervised dimensionality reduction techniques. Both techniques used to visualize the high dimensional data to a lower-dimensional space." }, { "code": null, "e": 1378, "s": 1284, "text": "An unsupervised, deterministic algorithm used for feature extraction as well as visualization" }, { "code": null, "e": 1522, "s": 1378, "text": "Applies a linear dimensionality reduction technique where the focus is on keeping the dissimilar points far apart in a lower-dimensional space." }, { "code": null, "e": 1623, "s": 1522, "text": "Transforms the original data to a new data by preserving the variance in the data using eigenvalues." }, { "code": null, "e": 1644, "s": 1623, "text": "Outliers impact PCA." }, { "code": null, "e": 1711, "s": 1644, "text": "An unsupervised, randomized algorithm, used only for visualization" }, { "code": null, "e": 1869, "s": 1711, "text": "Applies a non-linear dimensionality reduction technique where the focus is on keeping the very similar data points close together in lower-dimensional space." }, { "code": null, "e": 2013, "s": 1869, "text": "Preserves the local structure of the data using student t-distribution to compute the similarity between two points in lower-dimensional space." }, { "code": null, "e": 2236, "s": 2013, "text": "t-SNE uses a heavy-tailed Student-t distribution to compute the similarity between two points in the low-dimensional space rather than a Gaussian distribution, which helps to address the crowding and optimization problems." }, { "code": null, "e": 2265, "s": 2236, "text": "Outliers do not impact t-SNE" }, { "code": null, "e": 2438, "s": 2265, "text": "T-distributed Stochastic Neighbor Embedding (t-SNE) is an unsupervised machine learning algorithm for visualization developed by Laurens van der Maaten and Geoffrey Hinton." }, { "code": null, "e": 2459, "s": 2438, "text": "How does t-SNE work?" }, { "code": null, "e": 2547, "s": 2459, "text": "Step 1: Find the pairwise similarity between nearby points in a high dimensional space." }, { "code": null, "e": 2671, "s": 2547, "text": "t-SNE converts the high-dimensional Euclidean distances between datapoints xi and xj into conditional probabilities P(j|i)." }, { "code": null, "e": 2794, "s": 2671, "text": "xi would pick xj as its neighbor based on the proportion of its probability density under a Gaussian centered at point xi." }, { "code": null, "e": 2862, "s": 2794, "text": "σi is the variance of the Gaussian that is centered on datapoint xi" }, { "code": null, "e": 3057, "s": 2862, "text": "The probability density of a pair of a point is proportional to its similarity. For nearby data points, p(j|i) will be relatively high, and for points widely separated, p(j|i) will be minuscule." }, { "code": null, "e": 3179, "s": 3057, "text": "Symmetrize the conditional probabilities in high dimension space to get the final similarities in high dimensional space." }, { "code": null, "e": 3273, "s": 3179, "text": "Conditional probabilities are symmetrized by averaging the two probabilities, as shown below." }, { "code": null, "e": 3421, "s": 3273, "text": "Step 2: Map each point in high dimensional space to a low dimensional map based on the pairwise similarity of points in the high dimensional space." }, { "code": null, "e": 3495, "s": 3421, "text": "The low dimensional map will be either a 2-dimension or a 3-dimension map" }, { "code": null, "e": 3588, "s": 3495, "text": "yi and yj are the low dimensional counterparts of the high-dimensional datapoints xi and xj." }, { "code": null, "e": 3735, "s": 3588, "text": "We compute the conditional probability q(j|i)similar to P(j]i) centered under a Gaussian centered at point yi and then symmetrize the probability." }, { "code": null, "e": 3909, "s": 3735, "text": "Step 3: Find a low-dimensional data representation that minimizes the mismatch between Pij and qij using gradient descent based on Kullback-Leibler divergence(KL Divergence)" }, { "code": null, "e": 3987, "s": 3909, "text": "t-SNE optimizes the points in lower dimensional space using gradient descent." }, { "code": null, "e": 4010, "s": 3987, "text": "Why use KL divergence?" }, { "code": null, "e": 4214, "s": 4010, "text": "When we minimize the KL divergence, it makes qij physically identical to Pij, so the structure of the data in high dimensional space will be similar to the structure of the data in low dimensional space." }, { "code": null, "e": 4251, "s": 4214, "text": "Based on the KL divergence equation," }, { "code": null, "e": 4353, "s": 4251, "text": "If Pij is large, then we need a large value for qij to represent local points with higher similarity." }, { "code": null, "e": 4453, "s": 4353, "text": "If Pij is small, then we need a smaller value for qij to represent local points that are far apart." }, { "code": null, "e": 4563, "s": 4453, "text": "Step 4: Use Student-t distribution to compute the similarity between two points in the low-dimensional space." }, { "code": null, "e": 4750, "s": 4563, "text": "t-SNE uses a heavy-tailed Student-t distribution with one degree of freedom to compute the similarity between two points in the low-dimensional space rather than a Gaussian distribution." }, { "code": null, "e": 4882, "s": 4750, "text": "T- distribution creates the probability distribution of points in lower dimensions space, and this helps reduce the crowding issue." }, { "code": null, "e": 4917, "s": 4882, "text": "How do I apply t-SNE on a dataset?" }, { "code": null, "e": 5021, "s": 4917, "text": "Before we write the code in python, let’s understand a few critical parameters for TSNE that we can use" }, { "code": null, "e": 5201, "s": 5021, "text": "n_components: Dimension of the embedded space, this is the lower dimension that we want the high dimension data to be converted to. The default value is 2 for 2-dimensional space." }, { "code": null, "e": 5433, "s": 5201, "text": "Perplexity: The perplexity is related to the number of nearest neighbors that are used in t-SNE algorithms. Larger datasets usually require a larger perplexity. Perplexity can have a value between 5 and 50. The default value is 30." }, { "code": null, "e": 5541, "s": 5433, "text": "n_iter: Maximum number of iterations for optimization. Should be at least 250 and the default value is 1000" }, { "code": null, "e": 5656, "s": 5541, "text": "learning_rate: The learning rate for t-SNE is usually in the range [10.0, 1000.0] with the default value of 200.0." }, { "code": null, "e": 5775, "s": 5656, "text": "We will apply PCA using sklearn.decomposition.PCA and implement t-SNE on using sklearn.manifold.TSNE on MNIST dataset." }, { "code": null, "e": 5798, "s": 5775, "text": "Loading the MNIST data" }, { "code": null, "e": 5827, "s": 5798, "text": "Importing required libraries" }, { "code": null, "e": 5876, "s": 5827, "text": "import timeimport numpy as npimport pandas as pd" }, { "code": null, "e": 5951, "s": 5876, "text": "Get the MNIST training and test data and check the shape of the train data" }, { "code": null, "e": 6022, "s": 5951, "text": "(X_train, y_train) , (X_test, y_test) = mnist.load_data()X_train.shape" }, { "code": null, "e": 6126, "s": 6022, "text": "Create an array with a number of images and the pixel count in the image and copy the X_train data to X" }, { "code": null, "e": 6228, "s": 6126, "text": "X = np.zeros((X_train.shape[0], 784))for i in range(X_train.shape[0]): X[i] = X_train[i].flatten()" }, { "code": null, "e": 6314, "s": 6228, "text": "Shuffle the dataset, take 10% of the MNIST train data and store that in a data frame." }, { "code": null, "e": 6489, "s": 6314, "text": "X = pd.DataFrame(X)Y = pd.DataFrame(y_train)X = X.sample(frac=0.1, random_state=10).reset_index(drop=True)Y = Y.sample(frac=0.1, random_state=10).reset_index(drop=True)df = X" }, { "code": null, "e": 6542, "s": 6489, "text": "After the data is ready, we can apply PCA and t-SNE." }, { "code": null, "e": 6607, "s": 6542, "text": "PCA is applied using the PCA library from sklearn.decomposition." }, { "code": null, "e": 6811, "s": 6607, "text": "from sklearn.decomposition import PCAtime_start = time.time()pca = PCA(n_components=2)pca_results = pca.fit_transform(df.values)print ('PCA done! Time elapsed: {} seconds'.format(time.time()-time_start))" }, { "code": null, "e": 6955, "s": 6811, "text": "PCA generates two dimensions, principal component 1 and principal component 2. Add the two PCA components along with the label to a data frame." }, { "code": null, "e": 7059, "s": 6955, "text": "pca_df = pd.DataFrame(data = pca_results , columns = ['pca_1', 'pca_2'])pca_df['label'] = Y" }, { "code": null, "e": 7105, "s": 7059, "text": "The label is required only for visualization." }, { "code": null, "e": 7130, "s": 7105, "text": "Plotting the PCA results" }, { "code": null, "e": 7733, "s": 7130, "text": "fig = plt.figure(figsize = (8,8))ax = fig.add_subplot(1,1,1) ax.set_xlabel('Principal Component 1', fontsize = 15)ax.set_ylabel('Principal Component 2', fontsize = 15)ax.set_title('2 component PCA', fontsize = 20)targets = [0,1,2,3,4,5,6,7,8,9]colors=['yellow', 'black', 'cyan', 'green', 'blue', 'red', 'brown','crimson', 'gold', 'indigo']for target, color in zip(targets,colors): indicesToKeep = pca_df['label'] == target ax.scatter(pca_df.loc[indicesToKeep, 'pca_1'] , pca_df.loc[indicesToKeep, 'pca_2'] , c = color , s = 50)ax.legend(targets)ax.grid()" }, { "code": null, "e": 7794, "s": 7733, "text": "Importing the required libraries for t-SNE and visualization" }, { "code": null, "e": 7992, "s": 7794, "text": "import timefrom sklearn.manifold import TSNEimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3Dimport seaborn as snsimport matplotlib.patheffects as PathEffects%matplotlib inline" }, { "code": null, "e": 8179, "s": 7992, "text": "Create an instance of TSNE first with the default parameters and then fit high dimensional image input data into an embedded space and return that transformed output using fit_transform." }, { "code": null, "e": 8258, "s": 8179, "text": "The dimension of the image data should be of the shape (n_samples, n_features)" }, { "code": null, "e": 8425, "s": 8258, "text": "time_start = time.time()tsne = TSNE(random=0)tsne_results = tsne.fit_transform(df.values)print ('t-SNE done! Time elapsed: {} seconds'.format(time.time()-time_start))" }, { "code": null, "e": 8546, "s": 8425, "text": "Adding the labels to the data frame, and this will be used only during plotting to label the clusters for visualization." }, { "code": null, "e": 8562, "s": 8546, "text": "df['label'] = Y" }, { "code": null, "e": 8593, "s": 8562, "text": "Function to visualize the data" }, { "code": null, "e": 9493, "s": 8593, "text": "def plot_scatter(x, colors): # choose a color palette with seaborn. num_classes = len(np.unique(colors)) palette = np.array(sns.color_palette(\"hls\", num_classes)) print(palette) # create a scatter plot. f = plt.figure(figsize=(8, 8)) ax = plt.subplot(aspect='equal') sc = ax.scatter(x[:,0], x[:,1], c=palette[colors.astype(np.int)], cmap=plt.cm.get_cmap('Paired')) plt.xlim(-25, 25) plt.ylim(-25, 25) ax.axis('off') ax.axis('tight')# add the labels for each digit corresponding to the label txts = []for i in range(num_classes):# Position of each label at median of data points.xtext, ytext = np.median(x[colors == i, :], axis=0) txt = ax.text(xtext, ytext, str(i), fontsize=24) txt.set_path_effects([ PathEffects.Stroke(linewidth=5, foreground=\"w\"), PathEffects.Normal()]) txts.append(txt)return f, ax, sc, txts" }, { "code": null, "e": 9538, "s": 9493, "text": "Visualize the -SNE results for MNIST dataset" }, { "code": null, "e": 9579, "s": 9538, "text": "plot_scatter( tsne_results, df['label'])" }, { "code": null, "e": 9647, "s": 9579, "text": "Try with different parameter values and observe the different plots" }, { "code": null, "e": 9696, "s": 9647, "text": "Visualization for different values of perplexity" }, { "code": null, "e": 9742, "s": 9696, "text": "Visualization for different values for n_iter" }, { "code": null, "e": 9845, "s": 9742, "text": "We can see that the clusters generated from t-SNE plots are much more defined than the ones using PCA." }, { "code": null, "e": 9921, "s": 9845, "text": "PCA is deterministic, whereas t-SNE is not deterministic and is randomized." }, { "code": null, "e": 10100, "s": 9921, "text": "t-SNE tries to map only local neighbors whereas PCA is just a diagonal rotation of our initial covariance matrix and the eigenvectors represent and preserve the global properties" }, { "code": null, "e": 10123, "s": 10100, "text": "Code is available here" }, { "code": null, "e": 10294, "s": 10123, "text": "PCA and t-SNE are two common dimensionality reduction that uses different techniques to reduce high dimensional data into a lower-dimensional data that can be visualized." }, { "code": null, "e": 10311, "s": 10294, "text": "scikit-learn.org" } ]
Conducting Bayesian Inference in Python using PyMC3 | by Dr. Robert Kübler | Towards Data Science
We have covered the intuition and basics of Bayesian inference in my article A gentle Introduction to Bayesian Inference. We then moved on to actually conducting Bayesian inference by hand using a coin example in my article Beginner-friendly Bayesian Inference. If you still feel unsure about this topic, take a look at them, and have fun! 😊 Let us recall the problem definition: Imagine that you flip a coin with 0 on one and 1 on the other side a hundred times and write down the results. You end up with 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0 These are 57 ones and 43 zeroes. We want to answer the following question: What is the probability θ of receiving 1? Again, a simple (and the maximum likelihood) answer is 57/100=57%. This approach yields a single number, but we also want to be able to describe the uncertainty of this result. Is this 57% quite safe, or if it is also likely that θ might be even 65% or 45%? That’s what Bayesian inference is for: we get estimates, including free predictions about the uncertainty of the estimate. Let us reiterate a few mathematical details swiftly because it makes following the PyMC3 code much easier. In math, we want to find the posterior distribution of our parameter: To do Bayesian inference, we always need the likelihood and the prior. Without these two ingredients, we can’t proceed. So, let us quickly revise what these quantities are. The likelihood for a single coin flip (i.e. data = one coin flip) is given by We say that the result of a coin flip such as above, which we call C now, is Bernoulli distributed, often denoted as C~Ber(θ). This is all we need to compute the likelihood term in the Bayes formula. Regarding the prior, let us choose the one from the last article, i.e. a Beta(2, 2) prior. We have and denote this as θ~Beta(2, 2). The 6 is only there to normalize this density, i.e. the integral of f between 0 and 1 is one. Alright, everybody, enough with the formulas! Let us finally work with PyMC3 to solve the initial problem without manual calculations, but with a little bit of programming. Let us first explain why we even need PyMC3, what the output is, and how it helps us solve our Bayesian inference problem. Then, we will dive right into the code! So far, we could easily calculate everything by hand, because the Bernoulli and Beta distributions work together nicely (they are conjugated), meaning that their product is a Beta distribution again. This makes manual computations easy, with no problems at all. We have implicitly omitted to deal with the little part in the denominator of the Bayes formula: p(data). However, this one is a serious source of trouble, in general. This term looks simple but it is extremely hard to calculate for complicated likelihoods and priors, or even for simple likelihoods and priors if they don’t play well together. Anyway, that’s what PyMC3 is there for: Internally, it uses MCMC algorithms or Variational Inference to help us out. Please, don’t be discouraged when you read the Wikipedia articles. It’s difficult. In simple terms, PyMC3 can’t give us a formula for the posterior distribution. However, it can give us as many samples as we like from the posterior distribution without explicitly calculating the denominator. If we can get samples from a distribution, it’s nearly as good as having a formula for it. Why? Because we can estimate a lot of interesting statistics from these samples, such as the mean (take the average of all elements), median, standard deviation, quantiles, ... and even visualize it by plotting a histogram or density plot. The moment you have waited for. First, install PyMC3 via a simple pip install pymc3 . Inside the programming environment of your choice, prepare the imports and the coin toss data. import pymc3 as pmimport arviz as aztosses = [ 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0] So far, so good. The actual model is even shorter than this piece of code, so I will just present it to you and explain it afterward. with pm.Model() as model: # define the prior theta = pm.Beta('theta', 2, 2) # define the likelihood data = pm.Bernoulli('data', theta, observed=tosses) # get the samples trace = pm.sample(return_inferencedata=True) Basically, that’s it, the entire Bayesian inference. Probably you expected more, but this speaks even more for the awesomeness of PyMC3. Don’t be fooled, however: Under the hood, a lot of processes are running, more than I can explain. Anyway, we end up with this variable trace which contains 500 * #cores_of_your_machine samples, 2000 for me. It involves the number of cores because PyMC3 generates samples in parallel, without us having to specify anything. Reasonable defaults, I love it! If you followed this and my older articles that I mentioned in the beginning closely, the code should make kind of sense for you. The only weird part should be the context manager in the first line, with pm.Model() as model: . It’s just a programmatic design choice that the PyMC3 people have made. You open up a model (like you open a file in plain Python) and do things inside this context. In our case, we define distributions and sample. We then start defining our prior θ~Beta(2, 2), which in PyMC3 language is theta = pm.Beta('theta', 2, 2) PyMC3 distributions always want a name, that’s always the first parameter you have to specify. Usually, I just use the variable name again. Then the two parameters for the Beta distribution follow, in our case a=2, b=2. Done with the prior! Then we have to tell the model how the likelihood works. We already established that a coin flip just follows a Bernoulli distribution Ber(θ). The code for this is data = pm.Bernoulli('data', theta, observed=tosses) This way, the model knows that each coin flip is a Bernoulli variable with the parameter θ. In addition, we easily pass the observed data of 0/1 tosses as a list. What confused me when using PyMC3 for the first time: You don’t have to specify the complete likelihood p(data | θ) for all observed data. A single coin flip is enough, as PyMC3 multiplies these small single coin flip likelihoods together for you, i.e. you specify p(single toss| θ) for each toss and PyMC3 computes This is done because we always expect the tosses to be stochastically independent of each other. At last, let the sampling begin! trace = pm.sample() This step can take quite long in general, but for this example, even a weak computer should finish in a few seconds. We obtain some trace object, but just imagine that it contains a lot of numbers from the posterior distribution. Wanna peek inside? Use trace.get_values('theta') . You will receive a numpy array containing the samples you can then play around with. You can use the tool arviz to visualize the posterior distribution, without the need to import matplotlib, seaborn, or pandas. If you type az.plot_posterior(trace, hdi_prob=0.99) you should receive something like You can see that the mean and also the mode of the posterior distribution is around 57%. The 99% HPD (highest posterior density) is a so-called credible interval containing θ with a probability of 99%. The HDP especially is the shortest interval with this property. Looking back to the old article, we can see that we got the same numbers when calculating everything by hand. Nice! So, we can answer the question again: If we are expected to give a single number, we would go for 57%. Otherwise, we are able to say that it’s somewhere between 45% and 69% with a probability of 99%. IMPORTANT: This is a completely different statement than what you can obtain from confidence intervals when tackling this problem the frequentist way. Confidence intervals let you make statements like: “If you compute this interval a lot of times for different data samples from the same distribution, in 99% of the cases the true (fixed) parameter θ lies within the interval.”. This statement is hard to wrap your head around, and actually not what we want to state. But this is a different story. Just remember that a credible interval has an easy inerpretation. In this article, we have yet again analyzed the coin problem which we have solved analytically already in the past. This time, however, we used PyMC3 to solve it for us. The code is extremely short and simple (so is the problem), but yields the same results we expected, which is a nice sanity check. But the real fun starts now: You can start building more complicated models, such as Bayesian linear regression, where each weight is a parameter, for example with a normally distributed prior for each parameter. Doing this, we have credible intervals around each parameter and even around predictions, which is a great thing to have. You could also implement Latent Dirichlet allocation for unsupervised topic modeling for NLP problems in PyMC3 or Facebook’s Prophet for time series forecasting. But you can start smaller. How about you have data that is binomially distributed with parameter n and p, which you want to estimate. You can simulate it via np.random.binomial(n=23, p=0.1, size=100) using numpy, for example. p is a probability again, you know which prior works well for that. n is an integer. Distributions over integers are another binomial distribution, or the Poisson distribution, among others. Just play around a bit! I hope that you learned something new, interesting, and useful today. Thanks for reading! As the last point, if you want to support me in writing more about machine learning andplan to get a Medium subscription anyway, want to support me in writing more about machine learning and plan to get a Medium subscription anyway, why not do it via this link? This would help me a lot! 😊 To be transparent, the price for you does not change, but about half of the subscription fees go directly to me. Thanks a lot, if you consider supporting me! If you have any questions, write me on LinkedIn!
[ { "code": null, "e": 434, "s": 172, "text": "We have covered the intuition and basics of Bayesian inference in my article A gentle Introduction to Bayesian Inference. We then moved on to actually conducting Bayesian inference by hand using a coin example in my article Beginner-friendly Bayesian Inference." }, { "code": null, "e": 514, "s": 434, "text": "If you still feel unsure about this topic, take a look at them, and have fun! 😊" }, { "code": null, "e": 679, "s": 514, "text": "Let us recall the problem definition: Imagine that you flip a coin with 0 on one and 1 on the other side a hundred times and write down the results. You end up with" }, { "code": null, "e": 978, "s": 679, "text": "1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0" }, { "code": null, "e": 1053, "s": 978, "text": "These are 57 ones and 43 zeroes. We want to answer the following question:" }, { "code": null, "e": 1095, "s": 1053, "text": "What is the probability θ of receiving 1?" }, { "code": null, "e": 1476, "s": 1095, "text": "Again, a simple (and the maximum likelihood) answer is 57/100=57%. This approach yields a single number, but we also want to be able to describe the uncertainty of this result. Is this 57% quite safe, or if it is also likely that θ might be even 65% or 45%? That’s what Bayesian inference is for: we get estimates, including free predictions about the uncertainty of the estimate." }, { "code": null, "e": 1583, "s": 1476, "text": "Let us reiterate a few mathematical details swiftly because it makes following the PyMC3 code much easier." }, { "code": null, "e": 1653, "s": 1583, "text": "In math, we want to find the posterior distribution of our parameter:" }, { "code": null, "e": 1694, "s": 1653, "text": "To do Bayesian inference, we always need" }, { "code": null, "e": 1713, "s": 1694, "text": "the likelihood and" }, { "code": null, "e": 1724, "s": 1713, "text": "the prior." }, { "code": null, "e": 1826, "s": 1724, "text": "Without these two ingredients, we can’t proceed. So, let us quickly revise what these quantities are." }, { "code": null, "e": 1904, "s": 1826, "text": "The likelihood for a single coin flip (i.e. data = one coin flip) is given by" }, { "code": null, "e": 2104, "s": 1904, "text": "We say that the result of a coin flip such as above, which we call C now, is Bernoulli distributed, often denoted as C~Ber(θ). This is all we need to compute the likelihood term in the Bayes formula." }, { "code": null, "e": 2203, "s": 2104, "text": "Regarding the prior, let us choose the one from the last article, i.e. a Beta(2, 2) prior. We have" }, { "code": null, "e": 2330, "s": 2203, "text": "and denote this as θ~Beta(2, 2). The 6 is only there to normalize this density, i.e. the integral of f between 0 and 1 is one." }, { "code": null, "e": 2503, "s": 2330, "text": "Alright, everybody, enough with the formulas! Let us finally work with PyMC3 to solve the initial problem without manual calculations, but with a little bit of programming." }, { "code": null, "e": 2666, "s": 2503, "text": "Let us first explain why we even need PyMC3, what the output is, and how it helps us solve our Bayesian inference problem. Then, we will dive right into the code!" }, { "code": null, "e": 2928, "s": 2666, "text": "So far, we could easily calculate everything by hand, because the Bernoulli and Beta distributions work together nicely (they are conjugated), meaning that their product is a Beta distribution again. This makes manual computations easy, with no problems at all." }, { "code": null, "e": 3161, "s": 2928, "text": "We have implicitly omitted to deal with the little part in the denominator of the Bayes formula: p(data). However, this one is a serious source of trouble, in general. This term looks simple but it is extremely hard to calculate for" }, { "code": null, "e": 3205, "s": 3161, "text": "complicated likelihoods and priors, or even" }, { "code": null, "e": 3273, "s": 3205, "text": "for simple likelihoods and priors if they don’t play well together." }, { "code": null, "e": 3473, "s": 3273, "text": "Anyway, that’s what PyMC3 is there for: Internally, it uses MCMC algorithms or Variational Inference to help us out. Please, don’t be discouraged when you read the Wikipedia articles. It’s difficult." }, { "code": null, "e": 3683, "s": 3473, "text": "In simple terms, PyMC3 can’t give us a formula for the posterior distribution. However, it can give us as many samples as we like from the posterior distribution without explicitly calculating the denominator." }, { "code": null, "e": 4014, "s": 3683, "text": "If we can get samples from a distribution, it’s nearly as good as having a formula for it. Why? Because we can estimate a lot of interesting statistics from these samples, such as the mean (take the average of all elements), median, standard deviation, quantiles, ... and even visualize it by plotting a histogram or density plot." }, { "code": null, "e": 4080, "s": 4014, "text": "The moment you have waited for. First, install PyMC3 via a simple" }, { "code": null, "e": 4100, "s": 4080, "text": "pip install pymc3 ." }, { "code": null, "e": 4195, "s": 4100, "text": "Inside the programming environment of your choice, prepare the imports and the coin toss data." }, { "code": null, "e": 4572, "s": 4195, "text": "import pymc3 as pmimport arviz as aztosses = [ 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0]" }, { "code": null, "e": 4706, "s": 4572, "text": "So far, so good. The actual model is even shorter than this piece of code, so I will just present it to you and explain it afterward." }, { "code": null, "e": 4947, "s": 4706, "text": "with pm.Model() as model: # define the prior theta = pm.Beta('theta', 2, 2) # define the likelihood data = pm.Bernoulli('data', theta, observed=tosses) # get the samples trace = pm.sample(return_inferencedata=True)" }, { "code": null, "e": 5183, "s": 4947, "text": "Basically, that’s it, the entire Bayesian inference. Probably you expected more, but this speaks even more for the awesomeness of PyMC3. Don’t be fooled, however: Under the hood, a lot of processes are running, more than I can explain." }, { "code": null, "e": 5440, "s": 5183, "text": "Anyway, we end up with this variable trace which contains 500 * #cores_of_your_machine samples, 2000 for me. It involves the number of cores because PyMC3 generates samples in parallel, without us having to specify anything. Reasonable defaults, I love it!" }, { "code": null, "e": 5570, "s": 5440, "text": "If you followed this and my older articles that I mentioned in the beginning closely, the code should make kind of sense for you." }, { "code": null, "e": 5882, "s": 5570, "text": "The only weird part should be the context manager in the first line, with pm.Model() as model: . It’s just a programmatic design choice that the PyMC3 people have made. You open up a model (like you open a file in plain Python) and do things inside this context. In our case, we define distributions and sample." }, { "code": null, "e": 5956, "s": 5882, "text": "We then start defining our prior θ~Beta(2, 2), which in PyMC3 language is" }, { "code": null, "e": 5987, "s": 5956, "text": "theta = pm.Beta('theta', 2, 2)" }, { "code": null, "e": 6228, "s": 5987, "text": "PyMC3 distributions always want a name, that’s always the first parameter you have to specify. Usually, I just use the variable name again. Then the two parameters for the Beta distribution follow, in our case a=2, b=2. Done with the prior!" }, { "code": null, "e": 6392, "s": 6228, "text": "Then we have to tell the model how the likelihood works. We already established that a coin flip just follows a Bernoulli distribution Ber(θ). The code for this is" }, { "code": null, "e": 6444, "s": 6392, "text": "data = pm.Bernoulli('data', theta, observed=tosses)" }, { "code": null, "e": 6607, "s": 6444, "text": "This way, the model knows that each coin flip is a Bernoulli variable with the parameter θ. In addition, we easily pass the observed data of 0/1 tosses as a list." }, { "code": null, "e": 6923, "s": 6607, "text": "What confused me when using PyMC3 for the first time: You don’t have to specify the complete likelihood p(data | θ) for all observed data. A single coin flip is enough, as PyMC3 multiplies these small single coin flip likelihoods together for you, i.e. you specify p(single toss| θ) for each toss and PyMC3 computes" }, { "code": null, "e": 7020, "s": 6923, "text": "This is done because we always expect the tosses to be stochastically independent of each other." }, { "code": null, "e": 7053, "s": 7020, "text": "At last, let the sampling begin!" }, { "code": null, "e": 7073, "s": 7053, "text": "trace = pm.sample()" }, { "code": null, "e": 7439, "s": 7073, "text": "This step can take quite long in general, but for this example, even a weak computer should finish in a few seconds. We obtain some trace object, but just imagine that it contains a lot of numbers from the posterior distribution. Wanna peek inside? Use trace.get_values('theta') . You will receive a numpy array containing the samples you can then play around with." }, { "code": null, "e": 7578, "s": 7439, "text": "You can use the tool arviz to visualize the posterior distribution, without the need to import matplotlib, seaborn, or pandas. If you type" }, { "code": null, "e": 7618, "s": 7578, "text": "az.plot_posterior(trace, hdi_prob=0.99)" }, { "code": null, "e": 7652, "s": 7618, "text": "you should receive something like" }, { "code": null, "e": 8034, "s": 7652, "text": "You can see that the mean and also the mode of the posterior distribution is around 57%. The 99% HPD (highest posterior density) is a so-called credible interval containing θ with a probability of 99%. The HDP especially is the shortest interval with this property. Looking back to the old article, we can see that we got the same numbers when calculating everything by hand. Nice!" }, { "code": null, "e": 8072, "s": 8034, "text": "So, we can answer the question again:" }, { "code": null, "e": 8234, "s": 8072, "text": "If we are expected to give a single number, we would go for 57%. Otherwise, we are able to say that it’s somewhere between 45% and 69% with a probability of 99%." }, { "code": null, "e": 8799, "s": 8234, "text": "IMPORTANT: This is a completely different statement than what you can obtain from confidence intervals when tackling this problem the frequentist way. Confidence intervals let you make statements like: “If you compute this interval a lot of times for different data samples from the same distribution, in 99% of the cases the true (fixed) parameter θ lies within the interval.”. This statement is hard to wrap your head around, and actually not what we want to state. But this is a different story. Just remember that a credible interval has an easy inerpretation." }, { "code": null, "e": 9100, "s": 8799, "text": "In this article, we have yet again analyzed the coin problem which we have solved analytically already in the past. This time, however, we used PyMC3 to solve it for us. The code is extremely short and simple (so is the problem), but yields the same results we expected, which is a nice sanity check." }, { "code": null, "e": 9597, "s": 9100, "text": "But the real fun starts now: You can start building more complicated models, such as Bayesian linear regression, where each weight is a parameter, for example with a normally distributed prior for each parameter. Doing this, we have credible intervals around each parameter and even around predictions, which is a great thing to have. You could also implement Latent Dirichlet allocation for unsupervised topic modeling for NLP problems in PyMC3 or Facebook’s Prophet for time series forecasting." }, { "code": null, "e": 10038, "s": 9597, "text": "But you can start smaller. How about you have data that is binomially distributed with parameter n and p, which you want to estimate. You can simulate it via np.random.binomial(n=23, p=0.1, size=100) using numpy, for example. p is a probability again, you know which prior works well for that. n is an integer. Distributions over integers are another binomial distribution, or the Poisson distribution, among others. Just play around a bit!" }, { "code": null, "e": 10128, "s": 10038, "text": "I hope that you learned something new, interesting, and useful today. Thanks for reading!" }, { "code": null, "e": 10154, "s": 10128, "text": "As the last point, if you" }, { "code": null, "e": 10257, "s": 10154, "text": "want to support me in writing more about machine learning andplan to get a Medium subscription anyway," }, { "code": null, "e": 10319, "s": 10257, "text": "want to support me in writing more about machine learning and" }, { "code": null, "e": 10361, "s": 10319, "text": "plan to get a Medium subscription anyway," }, { "code": null, "e": 10418, "s": 10361, "text": "why not do it via this link? This would help me a lot! 😊" }, { "code": null, "e": 10531, "s": 10418, "text": "To be transparent, the price for you does not change, but about half of the subscription fees go directly to me." }, { "code": null, "e": 10576, "s": 10531, "text": "Thanks a lot, if you consider supporting me!" } ]
Batch Normalisation Explained. A simple, clear and in-depth guide to... | by Robin Vinod | Towards Data Science
In this article, I take a detailed look at Batch Normalisation and how it works. Batch Normalisation was introduced in 2015 by Loffe and Szegedy and quickly became a standard feature implemented in almost every deep network. Internal Covariate ShiftVanishing and exploding gradientsHow does Batch Normalisation work?Advantages of Batch Normalisation Internal Covariate Shift Vanishing and exploding gradients How does Batch Normalisation work? Advantages of Batch Normalisation The key issue that batch normalisation tackles is internal covariate shift. Internal covariate shift occurs due to the very nature of neural networks. At every epoch of training, weights are updated and different data is being processed, which means that the inputs to a neuron is slightly different every time. As these changes get passed on to the next neuron, it creates a situation where the input distribution of every neuron is different at every epoch. Normally, this is not a big deal, but in deep networks, these small changes in input distribution add up fast and amplify greatly deeper into the network. Ultimately, the input distribution received by the deepest neurons changes greatly between every epoch. As a result, these neurons need to continuously adapt to the changing input distribution, meaning that their learning capabilities are severely bottlenecked. This constantly changing input distribution is called internal covariate shift. Another issue that batch normalisation tackles is vanishing or exploding gradients. Before Rectified Linear Units (ReLUs), saturated activation functions were used. A saturated function is one that has a “flattened” curve towards to the left and right bounds, such as the sigmoid function. In the sigmoid function, the gradient tends towards 0 as the value of x tends towards ±∞. As a neural network is trained, the weights can be pushed towards the saturated ends of the sigmoid curve. As such, the gradient gets smaller and smaller and approaches 0. These small gradients get even smaller when multiplied together deeper into the network. When using backpropagation, the gradient gets exponentially closer to 0. This “vanishing” gradient severely limits the depth of networks. Although this vanishing gradient can be easily managed by using a non-saturated activation function such as ReLU, batch normalisation still has a place as it prevents the weights from being pushed to those saturated regions in the first place, by ensuring no value has gone too high or low. Batch normalisation normalises a layer input by subtracting the mini-batch mean and dividing it by the mini-batch standard deviation. Mini-batch refers to one batch of data supplied for any given epoch, a subset of the whole training data. The normalisation ensures that the inputs have a mean of 0 and a standard deviation of 1, meaning that the input distribution to every neuron will be the same, thereby fixing the problem of internal covariate shift and providing regularisation. However, the representational power of the network has been severely compromised. If each layer is normalised, the weight changes made by the previous layer and noise between data is partially lost, as some non-linear relationships are lost during normalisation. This can lead to suboptimal weights being passed on. To fix this, batch normalisation adds two trainable parameters, gamma γ and beta β, which can scale and shift the normalised value. Stochastic gradient descent can tune γ and β during standard backpropagation to find the optimal distribution such that the noise between data and sparseness of the weight changes are accounted for. Essentially, these parameters scale and shift the normalised input distribution to suit the peculiarities of the given dataset. For example, given that an un-normalised input distribution is best for a given dataset, γ and β will converge to √Var[x] and E[x], such that the original un-normalised x vector is obtained. Hence, batch normalisation ensures that the normalisation is always optimal for the given dataset. Ideally, the normalisation should be with respect to the entire training data set, as this ensures there will be no change in input distribution between different batches. However, since any dataset not in the current batch is outside the scope of backpropagation, stochastic gradient descent would not work, since the statistics used in the normalisation comes from outside the scope. Hence, the normalisation is done with respect to a mini-batch to ensure that standard backpropagation can be done. The only implication is that each batch should be somewhat representative of the distributions of the entire training set, which is a safe assumption if your batch size is not too small. During training, the mean and standard deviation are calculated using samples in the mini-batch. However, in testing, it does not make sense to calculate new values. Hence, batch normalisation uses a running mean and running variance that is calculated during training. There is a need to introduce a new parameter, momentum or decay. running_mean = momentum * running_mean + (1-momentum) * new_meanrunning_var = momentum* running_var + (1-momentum) * new_var Momentum is the importance given to the last seen mini-batch, a.k.a “lag”. If the momentum is set to 0, the running mean and variance come from the last seen mini-batch. However, this may be biased and not the desirable one for testing. Conversely, if momentum is set to 1, it uses the running mean and variance from the first mini-batch. Essentially, momentum controls how much each new mini-batch contributes to the running averages. Ideally, the momentum should be set close to 1 (>0.9) to ensure slow learning of the running mean and variance such that the noise in a mini-batch is ignored. Typically, larger learning rates can cause vanishing/exploding gradients. However, since batch normalisation takes care of that, larger learning rates can be used without worry. Batch normalisation has a regularising effect since it adds noise to the inputs of every layer. This discourages overfitting since the model no longer produces deterministic values for a given training example alone. The power of Batch Normalisation has been repeatedly shown in many areas of Machine Learning. It is a simple drop in solution that will yield a significant improvement in performance for almost any model. [1] Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift
[ { "code": null, "e": 397, "s": 172, "text": "In this article, I take a detailed look at Batch Normalisation and how it works. Batch Normalisation was introduced in 2015 by Loffe and Szegedy and quickly became a standard feature implemented in almost every deep network." }, { "code": null, "e": 522, "s": 397, "text": "Internal Covariate ShiftVanishing and exploding gradientsHow does Batch Normalisation work?Advantages of Batch Normalisation" }, { "code": null, "e": 547, "s": 522, "text": "Internal Covariate Shift" }, { "code": null, "e": 581, "s": 547, "text": "Vanishing and exploding gradients" }, { "code": null, "e": 616, "s": 581, "text": "How does Batch Normalisation work?" }, { "code": null, "e": 650, "s": 616, "text": "Advantages of Batch Normalisation" }, { "code": null, "e": 1110, "s": 650, "text": "The key issue that batch normalisation tackles is internal covariate shift. Internal covariate shift occurs due to the very nature of neural networks. At every epoch of training, weights are updated and different data is being processed, which means that the inputs to a neuron is slightly different every time. As these changes get passed on to the next neuron, it creates a situation where the input distribution of every neuron is different at every epoch." }, { "code": null, "e": 1369, "s": 1110, "text": "Normally, this is not a big deal, but in deep networks, these small changes in input distribution add up fast and amplify greatly deeper into the network. Ultimately, the input distribution received by the deepest neurons changes greatly between every epoch." }, { "code": null, "e": 1607, "s": 1369, "text": "As a result, these neurons need to continuously adapt to the changing input distribution, meaning that their learning capabilities are severely bottlenecked. This constantly changing input distribution is called internal covariate shift." }, { "code": null, "e": 1897, "s": 1607, "text": "Another issue that batch normalisation tackles is vanishing or exploding gradients. Before Rectified Linear Units (ReLUs), saturated activation functions were used. A saturated function is one that has a “flattened” curve towards to the left and right bounds, such as the sigmoid function." }, { "code": null, "e": 2159, "s": 1897, "text": "In the sigmoid function, the gradient tends towards 0 as the value of x tends towards ±∞. As a neural network is trained, the weights can be pushed towards the saturated ends of the sigmoid curve. As such, the gradient gets smaller and smaller and approaches 0." }, { "code": null, "e": 2386, "s": 2159, "text": "These small gradients get even smaller when multiplied together deeper into the network. When using backpropagation, the gradient gets exponentially closer to 0. This “vanishing” gradient severely limits the depth of networks." }, { "code": null, "e": 2677, "s": 2386, "text": "Although this vanishing gradient can be easily managed by using a non-saturated activation function such as ReLU, batch normalisation still has a place as it prevents the weights from being pushed to those saturated regions in the first place, by ensuring no value has gone too high or low." }, { "code": null, "e": 2917, "s": 2677, "text": "Batch normalisation normalises a layer input by subtracting the mini-batch mean and dividing it by the mini-batch standard deviation. Mini-batch refers to one batch of data supplied for any given epoch, a subset of the whole training data." }, { "code": null, "e": 3162, "s": 2917, "text": "The normalisation ensures that the inputs have a mean of 0 and a standard deviation of 1, meaning that the input distribution to every neuron will be the same, thereby fixing the problem of internal covariate shift and providing regularisation." }, { "code": null, "e": 3478, "s": 3162, "text": "However, the representational power of the network has been severely compromised. If each layer is normalised, the weight changes made by the previous layer and noise between data is partially lost, as some non-linear relationships are lost during normalisation. This can lead to suboptimal weights being passed on." }, { "code": null, "e": 3610, "s": 3478, "text": "To fix this, batch normalisation adds two trainable parameters, gamma γ and beta β, which can scale and shift the normalised value." }, { "code": null, "e": 3937, "s": 3610, "text": "Stochastic gradient descent can tune γ and β during standard backpropagation to find the optimal distribution such that the noise between data and sparseness of the weight changes are accounted for. Essentially, these parameters scale and shift the normalised input distribution to suit the peculiarities of the given dataset." }, { "code": null, "e": 4227, "s": 3937, "text": "For example, given that an un-normalised input distribution is best for a given dataset, γ and β will converge to √Var[x] and E[x], such that the original un-normalised x vector is obtained. Hence, batch normalisation ensures that the normalisation is always optimal for the given dataset." }, { "code": null, "e": 4613, "s": 4227, "text": "Ideally, the normalisation should be with respect to the entire training data set, as this ensures there will be no change in input distribution between different batches. However, since any dataset not in the current batch is outside the scope of backpropagation, stochastic gradient descent would not work, since the statistics used in the normalisation comes from outside the scope." }, { "code": null, "e": 4915, "s": 4613, "text": "Hence, the normalisation is done with respect to a mini-batch to ensure that standard backpropagation can be done. The only implication is that each batch should be somewhat representative of the distributions of the entire training set, which is a safe assumption if your batch size is not too small." }, { "code": null, "e": 5250, "s": 4915, "text": "During training, the mean and standard deviation are calculated using samples in the mini-batch. However, in testing, it does not make sense to calculate new values. Hence, batch normalisation uses a running mean and running variance that is calculated during training. There is a need to introduce a new parameter, momentum or decay." }, { "code": null, "e": 5375, "s": 5250, "text": "running_mean = momentum * running_mean + (1-momentum) * new_meanrunning_var = momentum* running_var + (1-momentum) * new_var" }, { "code": null, "e": 5811, "s": 5375, "text": "Momentum is the importance given to the last seen mini-batch, a.k.a “lag”. If the momentum is set to 0, the running mean and variance come from the last seen mini-batch. However, this may be biased and not the desirable one for testing. Conversely, if momentum is set to 1, it uses the running mean and variance from the first mini-batch. Essentially, momentum controls how much each new mini-batch contributes to the running averages." }, { "code": null, "e": 5970, "s": 5811, "text": "Ideally, the momentum should be set close to 1 (>0.9) to ensure slow learning of the running mean and variance such that the noise in a mini-batch is ignored." }, { "code": null, "e": 6148, "s": 5970, "text": "Typically, larger learning rates can cause vanishing/exploding gradients. However, since batch normalisation takes care of that, larger learning rates can be used without worry." }, { "code": null, "e": 6365, "s": 6148, "text": "Batch normalisation has a regularising effect since it adds noise to the inputs of every layer. This discourages overfitting since the model no longer produces deterministic values for a given training example alone." }, { "code": null, "e": 6570, "s": 6365, "text": "The power of Batch Normalisation has been repeatedly shown in many areas of Machine Learning. It is a simple drop in solution that will yield a significant improvement in performance for almost any model." } ]
How to access an associative array by integer index in PHP? - GeeksforGeeks
11 Feb, 2019 There are two types of arrays in PHP, indexed and associative arrays. In case of indexed array strict numeric indexing is followed but in case of associative array there are keys corresponding to each element.The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP. Although the array_keys() function can be used to get an indexed array of keys for an associative array. As the resulting array is indexed the elements of the resulting array can be accessed by integer index. Using this resulting array, the keys of the original array can be accessed by integer index and then the keys can be used to access the elements of the original array. Thus by using the integer index the elements of the original array can be accessed with the help of an additional indexed array of keys. array_keys() function: The array_keys() function takes an array as input and returns an indexed array which consists only the keys of the original array, indexed where indexing is started from zero. Syntax: array array_keys( $arr ) Parameters: The array_keys() function takes an array as input and use only the keys of the array to make the indexed resulting array. Note: The array_keys() function does not change the order of the keys of the original array. If an indexed array is passed then the resulting array will have integers as value. Program: PHP program to access an associative array using integer index. <?php// PHP program to accessing an associative// array by integer index // Sample associative array$arr = array( 'one' => 'geeks', 'two' => 'for', 'three' => 'geeks' ); // Getting the keys of $arr// using array_keys() function$keys = array_keys( $arr ); echo "The keys array: "; print_r($keys); // Getting the size of the sample array$size = sizeof($arr); //Accessing elements of $arr using//integer index using $xecho "The elements of the sample array: " . "\n"; for($x = 0; $x < $size; $x++ ) { echo "key: ". $keys[$x] . ", value: " . $arr[$keys[$x]] . "\n";} ?> The keys array: Array ( [0] => one [1] => two [2] => three ) The elements of the sample array: key: one, value: geeks key: two, value: for key: three, value: geeks Picked PHP PHP Programs Web Technologies 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 ? PHP | Converting string to Date and DateTime Download file from URL using PHP How to fetch data from localserver database and display on HTML table using 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 fetch data from localserver database and display on HTML table using PHP ? Split a comma delimited string into an array in PHP
[ { "code": null, "e": 24163, "s": 24135, "text": "\n11 Feb, 2019" }, { "code": null, "e": 24580, "s": 24163, "text": "There are two types of arrays in PHP, indexed and associative arrays. In case of indexed array strict numeric indexing is followed but in case of associative array there are keys corresponding to each element.The elements of an associative array can only be accessed by the corresponding keys. As there is not strict indexing between the keys, accessing the elements normally by integer index is not possible in PHP." }, { "code": null, "e": 25094, "s": 24580, "text": "Although the array_keys() function can be used to get an indexed array of keys for an associative array. As the resulting array is indexed the elements of the resulting array can be accessed by integer index. Using this resulting array, the keys of the original array can be accessed by integer index and then the keys can be used to access the elements of the original array. Thus by using the integer index the elements of the original array can be accessed with the help of an additional indexed array of keys." }, { "code": null, "e": 25293, "s": 25094, "text": "array_keys() function: The array_keys() function takes an array as input and returns an indexed array which consists only the keys of the original array, indexed where indexing is started from zero." }, { "code": null, "e": 25301, "s": 25293, "text": "Syntax:" }, { "code": null, "e": 25326, "s": 25301, "text": "array array_keys( $arr )" }, { "code": null, "e": 25460, "s": 25326, "text": "Parameters: The array_keys() function takes an array as input and use only the keys of the array to make the indexed resulting array." }, { "code": null, "e": 25637, "s": 25460, "text": "Note: The array_keys() function does not change the order of the keys of the original array. If an indexed array is passed then the resulting array will have integers as value." }, { "code": null, "e": 25710, "s": 25637, "text": "Program: PHP program to access an associative array using integer index." }, { "code": "<?php// PHP program to accessing an associative// array by integer index // Sample associative array$arr = array( 'one' => 'geeks', 'two' => 'for', 'three' => 'geeks' ); // Getting the keys of $arr// using array_keys() function$keys = array_keys( $arr ); echo \"The keys array: \"; print_r($keys); // Getting the size of the sample array$size = sizeof($arr); //Accessing elements of $arr using//integer index using $xecho \"The elements of the sample array: \" . \"\\n\"; for($x = 0; $x < $size; $x++ ) { echo \"key: \". $keys[$x] . \", value: \" . $arr[$keys[$x]] . \"\\n\";} ?>", "e": 26353, "s": 25710, "text": null }, { "code": null, "e": 26531, "s": 26353, "text": "The keys array: Array\n(\n [0] => one\n [1] => two\n [2] => three\n)\nThe elements of the sample array: \nkey: one, value: geeks\nkey: two, value: for\nkey: three, value: geeks\n" }, { "code": null, "e": 26538, "s": 26531, "text": "Picked" }, { "code": null, "e": 26542, "s": 26538, "text": "PHP" }, { "code": null, "e": 26555, "s": 26542, "text": "PHP Programs" }, { "code": null, "e": 26572, "s": 26555, "text": "Web Technologies" }, { "code": null, "e": 26576, "s": 26572, "text": "PHP" }, { "code": null, "e": 26674, "s": 26576, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26683, "s": 26674, "text": "Comments" }, { "code": null, "e": 26696, "s": 26683, "text": "Old Comments" }, { "code": null, "e": 26746, "s": 26696, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26786, "s": 26746, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26831, "s": 26786, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 26864, "s": 26831, "text": "Download file from URL using PHP" }, { "code": null, "e": 26946, "s": 26864, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26996, "s": 26946, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 27036, "s": 26996, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 27088, "s": 27036, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 27170, "s": 27088, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" } ]
Tryit Editor v3.6 - Show Node.js Command Prompt
var mysql = require('mysql'); ​ var con = mysql.createConnection({ host: "localhost", user: "myusername", password: "mypassword", database: "mydb" }); ​ con.connect(function(err) { if (err) throw err; [ { id: 1, name: 'John', address: 'Highway 71'}, { id: 2, name: 'Peter', address: 'Lowstreet 4'}, { id: 3, name: 'Amy', address: 'Apple st 652'}, { id: 4, name: 'Hannah', address: 'Mountain 21'}, { id: 5, name: 'Michael', address: 'Valley 345'}, { id: 6, name: 'Sandy', address: 'Ocean blvd 2'}, { id: 7, name: 'Betty', address: 'Green Grass 1'}, { id: 8, name: 'Richard', address: 'Sky st 331'}, { id: 9, name: 'Susan', address: 'One way 98'}, { id: 10, name: 'Vicky', address: 'Yellow Garden 2'}, { id: 11, name: 'Ben', address: 'Park Lane 38'}, { id: 12, name: 'William', address: 'Central st 954'}, { id: 13, name: 'Chuck', address: 'Main Road 989'}, { id: 14, name: 'Viola', address: 'Sideway 1633'}
[ { "code": null, "e": 30, "s": 0, "text": "var mysql = require('mysql');" }, { "code": null, "e": 32, "s": 30, "text": "​" }, { "code": null, "e": 67, "s": 32, "text": "var con = mysql.createConnection({" }, { "code": null, "e": 88, "s": 67, "text": " host: \"localhost\"," }, { "code": null, "e": 110, "s": 88, "text": " user: \"myusername\"," }, { "code": null, "e": 136, "s": 110, "text": " password: \"mypassword\"," }, { "code": null, "e": 155, "s": 136, "text": " database: \"mydb\"" }, { "code": null, "e": 159, "s": 155, "text": "});" }, { "code": null, "e": 161, "s": 159, "text": "​" }, { "code": null, "e": 189, "s": 161, "text": "con.connect(function(err) {" }, { "code": null, "e": 211, "s": 189, "text": " if (err) throw err;" } ]
JavaScript Array shift() Method
04 Oct, 2021 Below is the example of Array shift() method. Example:<script>function func() { // Original array var array = ["GFG", "Geeks", "for", "Geeks"]; // Checking for condition in array var value = array.shift(); document.write(value); document.write("<br />"); document.write(array); } func();</script> <script>function func() { // Original array var array = ["GFG", "Geeks", "for", "Geeks"]; // Checking for condition in array var value = array.shift(); document.write(value); document.write("<br />"); document.write(array); } func();</script> Output:GFG Geeks, for, Geeks GFG Geeks, for, Geeks The arr.shift() method removes the first element of the array thus reducing the size of the original array by 1. Syntax: arr.shift() Parameters: This method does not accept any parameter. Return value: This function returns the removed first element of the array. If the array is empty then this function returns undefined. Note: This function can also be used with other javascript objects that behave like the array. Below examples illustrate the JavaScript Array shift() method: Example 1: In this example the shift() method removes the first element of the array, therefore it returns 34.var arr = [2, 5, 8, 1, 4]; document.write(value); document.write(arr); Output:34 234,567,4 var arr = [2, 5, 8, 1, 4]; document.write(value); document.write(arr); Output: 34 234,567,4 Example 2: In this example the shift() method tries to remove the first element of the array, but the array is empty, therefore it returns undefined.var arr = []; document.write(value); document.write(arr) Output:undefined var arr = []; document.write(value); document.write(arr) Output: undefined Code for the above method is provided below: Program 1: <script> function func() { // Original array var array = [34,234,567,4]; // Checking for condition in array var value = array.shift(); document.write(value); document.write("<br />"); document.write(array); } func(); </script> Output: 34 234,567,4 Program 2: <script>function func() { // Original array var array = []; // Checking for condition in array var value = array.shift(); document.write(value); document.write("<br />"); document.write(array); } func();</script> Output: undefined Supported Browsers: The browsers supported by JavaScript Array shift() method are listed below: Google Chrome 1 and above Edge 12 and above Firefox 1 and above Internet Explorer 5.5 and above Opera 4 and above Safari 1 and above ysachin2314 javascript-array JavaScript-Methods 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 How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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": "\n04 Oct, 2021" }, { "code": null, "e": 74, "s": 28, "text": "Below is the example of Array shift() method." }, { "code": null, "e": 364, "s": 74, "text": "Example:<script>function func() { // Original array var array = [\"GFG\", \"Geeks\", \"for\", \"Geeks\"]; // Checking for condition in array var value = array.shift(); document.write(value); document.write(\"<br />\"); document.write(array); } func();</script>" }, { "code": "<script>function func() { // Original array var array = [\"GFG\", \"Geeks\", \"for\", \"Geeks\"]; // Checking for condition in array var value = array.shift(); document.write(value); document.write(\"<br />\"); document.write(array); } func();</script>", "e": 646, "s": 364, "text": null }, { "code": null, "e": 675, "s": 646, "text": "Output:GFG\nGeeks, for, Geeks" }, { "code": null, "e": 697, "s": 675, "text": "GFG\nGeeks, for, Geeks" }, { "code": null, "e": 810, "s": 697, "text": "The arr.shift() method removes the first element of the array thus reducing the size of the original array by 1." }, { "code": null, "e": 818, "s": 810, "text": "Syntax:" }, { "code": null, "e": 830, "s": 818, "text": "arr.shift()" }, { "code": null, "e": 885, "s": 830, "text": "Parameters: This method does not accept any parameter." }, { "code": null, "e": 1021, "s": 885, "text": "Return value: This function returns the removed first element of the array. If the array is empty then this function returns undefined." }, { "code": null, "e": 1116, "s": 1021, "text": "Note: This function can also be used with other javascript objects that behave like the array." }, { "code": null, "e": 1179, "s": 1116, "text": "Below examples illustrate the JavaScript Array shift() method:" }, { "code": null, "e": 1381, "s": 1179, "text": "Example 1: In this example the shift() method removes the first element of the array, therefore it returns 34.var arr = [2, 5, 8, 1, 4];\ndocument.write(value);\ndocument.write(arr);\nOutput:34\n234,567,4\n" }, { "code": null, "e": 1453, "s": 1381, "text": "var arr = [2, 5, 8, 1, 4];\ndocument.write(value);\ndocument.write(arr);\n" }, { "code": null, "e": 1461, "s": 1453, "text": "Output:" }, { "code": null, "e": 1475, "s": 1461, "text": "34\n234,567,4\n" }, { "code": null, "e": 1698, "s": 1475, "text": "Example 2: In this example the shift() method tries to remove the first element of the array, but the array is empty, therefore it returns undefined.var arr = [];\ndocument.write(value);\ndocument.write(arr)\nOutput:undefined" }, { "code": null, "e": 1756, "s": 1698, "text": "var arr = [];\ndocument.write(value);\ndocument.write(arr)\n" }, { "code": null, "e": 1764, "s": 1756, "text": "Output:" }, { "code": null, "e": 1774, "s": 1764, "text": "undefined" }, { "code": null, "e": 1819, "s": 1774, "text": "Code for the above method is provided below:" }, { "code": null, "e": 1830, "s": 1819, "text": "Program 1:" }, { "code": "<script> function func() { // Original array var array = [34,234,567,4]; // Checking for condition in array var value = array.shift(); document.write(value); document.write(\"<br />\"); document.write(array); } func(); </script> ", "e": 2097, "s": 1830, "text": null }, { "code": null, "e": 2105, "s": 2097, "text": "Output:" }, { "code": null, "e": 2119, "s": 2105, "text": "34\n234,567,4\n" }, { "code": null, "e": 2130, "s": 2119, "text": "Program 2:" }, { "code": "<script>function func() { // Original array var array = []; // Checking for condition in array var value = array.shift(); document.write(value); document.write(\"<br />\"); document.write(array); } func();</script>", "e": 2382, "s": 2130, "text": null }, { "code": null, "e": 2390, "s": 2382, "text": "Output:" }, { "code": null, "e": 2400, "s": 2390, "text": "undefined" }, { "code": null, "e": 2496, "s": 2400, "text": "Supported Browsers: The browsers supported by JavaScript Array shift() method are listed below:" }, { "code": null, "e": 2522, "s": 2496, "text": "Google Chrome 1 and above" }, { "code": null, "e": 2540, "s": 2522, "text": "Edge 12 and above" }, { "code": null, "e": 2560, "s": 2540, "text": "Firefox 1 and above" }, { "code": null, "e": 2592, "s": 2560, "text": "Internet Explorer 5.5 and above" }, { "code": null, "e": 2610, "s": 2592, "text": "Opera 4 and above" }, { "code": null, "e": 2629, "s": 2610, "text": "Safari 1 and above" }, { "code": null, "e": 2641, "s": 2629, "text": "ysachin2314" }, { "code": null, "e": 2658, "s": 2641, "text": "javascript-array" }, { "code": null, "e": 2677, "s": 2658, "text": "JavaScript-Methods" }, { "code": null, "e": 2688, "s": 2677, "text": "JavaScript" }, { "code": null, "e": 2705, "s": 2688, "text": "Web Technologies" }, { "code": null, "e": 2803, "s": 2705, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2864, "s": 2803, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2936, "s": 2864, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2976, "s": 2936, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3028, "s": 2976, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3069, "s": 3028, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3131, "s": 3069, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3164, "s": 3131, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3225, "s": 3164, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3275, "s": 3225, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to create a Shared Folder between two Local User in Linux?
11 Jul, 2022 This article shows how to set-up a shared folder between two local users in Linux. The shared directory/folder will be accessible to both the users, they will be able to read/write each other’s file. Let us create shared directory /home/shareFolder for user Bob and Alice and add them to a common group named projectA. Note: You can create the uses Bob and Alice using following commands: $ sudo useradd Bob $ sudo passwd Bob $ sudo useradd Alice $ sudo passwd Alice So, start by creating common group using groupadd command.$ sudo groupadd projectA Now, create shared directory and change group for it using chgrp command.$ sudo mkdir /home/sharedFolder/ $ sudo chgrp projectA /home/sharedFolder After this we need to change appropriate permissions for the shared directory using chmod command.$ sudo chmod 770 /home/sharedFolder/ Here 770 permission means:7 – owner has rwx permissions. 7 – directory groups have rwx permissions. 0 – others have no permissions. We also need to set the SGID(Set-Group-ID) bit for the sharedFolder directory, now all newly created subdirectories/files under sharedFolder will inherit sharedFolder permissions.$ sudo chmod +s /home/sharedFolder Finally we add users to the common group with whom to share the folder$ sudo usermod -a -G projectA Bob $ sudo usermod -a -G projectA Alice So, start by creating common group using groupadd command.$ sudo groupadd projectA $ sudo groupadd projectA Now, create shared directory and change group for it using chgrp command.$ sudo mkdir /home/sharedFolder/ $ sudo chgrp projectA /home/sharedFolder $ sudo mkdir /home/sharedFolder/ $ sudo chgrp projectA /home/sharedFolder After this we need to change appropriate permissions for the shared directory using chmod command.$ sudo chmod 770 /home/sharedFolder/ Here 770 permission means:7 – owner has rwx permissions. 7 – directory groups have rwx permissions. 0 – others have no permissions. $ sudo chmod 770 /home/sharedFolder/ Here 770 permission means: 7 – owner has rwx permissions. 7 – directory groups have rwx permissions. 0 – others have no permissions. We also need to set the SGID(Set-Group-ID) bit for the sharedFolder directory, now all newly created subdirectories/files under sharedFolder will inherit sharedFolder permissions.$ sudo chmod +s /home/sharedFolder $ sudo chmod +s /home/sharedFolder Finally we add users to the common group with whom to share the folder$ sudo usermod -a -G projectA Bob $ sudo usermod -a -G projectA Alice $ sudo usermod -a -G projectA Bob $ sudo usermod -a -G projectA Alice Now /home/sharedFolder is accessible to both the user Bob and Alice. But others can’t access this directory. This directory will be accessible to only members of projectA group. Linux-Unix TechTips Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples Compiling with g++ 'crontab' in Linux with Examples UDP Server-Client implementation in C touch command in Linux with Examples How to Find the Wi-Fi Password Using CMD in Windows? Setting up the environment in Java How to Run a Python Script using Docker? Top Programming Languages for Android App Development Docker - COPY Instruction
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jul, 2022" }, { "code": null, "e": 228, "s": 28, "text": "This article shows how to set-up a shared folder between two local users in Linux. The shared directory/folder will be accessible to both the users, they will be able to read/write each other’s file." }, { "code": null, "e": 347, "s": 228, "text": "Let us create shared directory /home/shareFolder for user Bob and Alice and add them to a common group named projectA." }, { "code": null, "e": 417, "s": 347, "text": "Note: You can create the uses Bob and Alice using following commands:" }, { "code": null, "e": 496, "s": 417, "text": "$ sudo useradd Bob\n$ sudo passwd Bob\n$ sudo useradd Alice\n$ sudo passwd Alice\n" }, { "code": null, "e": 1349, "s": 496, "text": "So, start by creating common group using groupadd command.$ sudo groupadd projectA\nNow, create shared directory and change group for it using chgrp command.$ sudo mkdir /home/sharedFolder/\n$ sudo chgrp projectA /home/sharedFolder\nAfter this we need to change appropriate permissions for the shared directory using chmod command.$ sudo chmod 770 /home/sharedFolder/\nHere 770 permission means:7 – owner has rwx permissions.\n7 – directory groups have rwx permissions.\n0 – others have no permissions.\nWe also need to set the SGID(Set-Group-ID) bit for the sharedFolder directory, now all newly created subdirectories/files under sharedFolder will inherit sharedFolder permissions.$ sudo chmod +s /home/sharedFolder \nFinally we add users to the common group with whom to share the folder$ sudo usermod -a -G projectA Bob\n$ sudo usermod -a -G projectA Alice\n" }, { "code": null, "e": 1433, "s": 1349, "text": "So, start by creating common group using groupadd command.$ sudo groupadd projectA\n" }, { "code": null, "e": 1459, "s": 1433, "text": "$ sudo groupadd projectA\n" }, { "code": null, "e": 1607, "s": 1459, "text": "Now, create shared directory and change group for it using chgrp command.$ sudo mkdir /home/sharedFolder/\n$ sudo chgrp projectA /home/sharedFolder\n" }, { "code": null, "e": 1682, "s": 1607, "text": "$ sudo mkdir /home/sharedFolder/\n$ sudo chgrp projectA /home/sharedFolder\n" }, { "code": null, "e": 1950, "s": 1682, "text": "After this we need to change appropriate permissions for the shared directory using chmod command.$ sudo chmod 770 /home/sharedFolder/\nHere 770 permission means:7 – owner has rwx permissions.\n7 – directory groups have rwx permissions.\n0 – others have no permissions.\n" }, { "code": null, "e": 1988, "s": 1950, "text": "$ sudo chmod 770 /home/sharedFolder/\n" }, { "code": null, "e": 2015, "s": 1988, "text": "Here 770 permission means:" }, { "code": null, "e": 2122, "s": 2015, "text": "7 – owner has rwx permissions.\n7 – directory groups have rwx permissions.\n0 – others have no permissions.\n" }, { "code": null, "e": 2338, "s": 2122, "text": "We also need to set the SGID(Set-Group-ID) bit for the sharedFolder directory, now all newly created subdirectories/files under sharedFolder will inherit sharedFolder permissions.$ sudo chmod +s /home/sharedFolder \n" }, { "code": null, "e": 2375, "s": 2338, "text": "$ sudo chmod +s /home/sharedFolder \n" }, { "code": null, "e": 2516, "s": 2375, "text": "Finally we add users to the common group with whom to share the folder$ sudo usermod -a -G projectA Bob\n$ sudo usermod -a -G projectA Alice\n" }, { "code": null, "e": 2587, "s": 2516, "text": "$ sudo usermod -a -G projectA Bob\n$ sudo usermod -a -G projectA Alice\n" }, { "code": null, "e": 2765, "s": 2587, "text": "Now /home/sharedFolder is accessible to both the user Bob and Alice. But others can’t access this directory. This directory will be accessible to only members of projectA group." }, { "code": null, "e": 2776, "s": 2765, "text": "Linux-Unix" }, { "code": null, "e": 2785, "s": 2776, "text": "TechTips" }, { "code": null, "e": 2883, "s": 2785, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2918, "s": 2883, "text": "tar command in Linux with examples" }, { "code": null, "e": 2937, "s": 2918, "text": "Compiling with g++" }, { "code": null, "e": 2970, "s": 2937, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 3008, "s": 2970, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 3045, "s": 3008, "text": "touch command in Linux with Examples" }, { "code": null, "e": 3098, "s": 3045, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 3133, "s": 3098, "text": "Setting up the environment in Java" }, { "code": null, "e": 3174, "s": 3133, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 3228, "s": 3174, "text": "Top Programming Languages for Android App Development" } ]
Sorting in Java
03 Oct, 2021 Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use any kind of algorithms. It is as simple sorting with the help of linear and non-linear data structures present within java. So there is sorting done with the help of brute force in java with the help of loops and there are two in-built methods to sort in Java. Ways of sorting in Java Using loopsUsing sort() method of Arrays classUsing sort method of Collections classSorting on a subarray Using loops Using sort() method of Arrays class Using sort method of Collections class Sorting on a subarray Let us discuss all four of them and propose a code for each one of them. Way 1: Using loops Java // Java Program to sort an elements// by bringing Arrays into play // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom input array int arr[] = { 4, 3, 2, 1 }; // Outer loop for (int i = 0; i < arr.length; i++) { // Inner nested loop pointing 1 index ahead for (int j = i + 1; j < arr.length; j++) { // Checking elements int temp = 0; if (arr[j] < arr[i]) { // Swapping temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // Printing sorted array elements System.out.print(arr[i] + " "); } }} 1 2 3 4 Way 2: Using sort() method of Arrays class Arrays.Sort() works for arrays which can be of primitive data type also which in turn by default sorts in ascending order. Example 1 JAVA // Java program to demonstrate working of// sort() method of Arrays class // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; // Calling the sort() method present // inside Arrays class Arrays.sort(arr); // Printing and display sorted array System.out.printf("Modified arr[] : %s", Arrays.toString(arr)); }} Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102] Example 2 JAVA // A sample Java program to sort an array// in descending order using Arrays.sort().import java.util.Arrays;import java.util.Collections; public class GFG { public static void main(String[] args) { // Note that we have Integer here instead of // int[] as Collections.reverseOrder doesn't // work for primitive types. Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); System.out.printf("Modified arr[] : %s", Arrays.toString(arr)); }} Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2] Way 3: Using sort() method of Collections class Collections.sort() works for objects Collections like ArrayList and LinkedList. Example JAVA // Java program to demonstrate working of Collections.sort()import java.util.*; public class GFG { public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add("Geeks For Geeks"); al.add("Friends"); al.add("Dear"); al.add("Is"); al.add("Superb"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al); // Let us print the sorted list System.out.println("List after the use of" + " Collection.sort() :\n" + al); }} List after the use of Collection.sort() : [Dear, Friends, Geeks For Geeks, Is, Superb] Example 2 JAVA // Java program to demonstrate working of Collections.sort()// to descending order.import java.util.*; public class GFG { public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add("Geeks For Geeks"); al.add("Friends"); al.add("Dear"); al.add("Is"); al.add("Superb"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al, Collections.reverseOrder()); // Let us print the sorted list System.out.println("List after the use of" + " Collection.sort() :\n" + al); }} List after the use of Collection.sort() : [Superb, Is, Geeks For Geeks, Friends, Dear] Way 4: Sorting only a subarray JAVA // Java program to sort a subarray// using Arrays.sort() // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main drive method public static void main(String[] args) { // Custom input array int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sort subarray from index 1 to 4, i.e., // only sort subarray {7, 6, 45, 21} and // keep other elements as it is. Arrays.sort(arr, 1, 5); // Printing sorted array System.out.printf("Modified arr[] : %s", Arrays.toString(arr)); }} Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100] Note: Which sorting algorithm does Java use in sort()? Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort. Which order of sorting is done by default? It by default sorts in ascending order. How to sort array or list in descending order? It can be done with the help of Collections.reverseOrder(). How to write my own sorting function in Java? Please see Java programs for Quick Sort, Merge Sort, Insertion Sort, Selection Sort, Heap Sort, Bubble Sort samyanib solankimayank Java-Arrays Java-Collections Java Java Programs Sorting Sorting Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java How to add an element to an Array in Java? Queue Interface In Java List Interface in Java with Examples PriorityQueue in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 52, "s": 24, "text": "\n03 Oct, 2021" }, { "code": null, "e": 501, "s": 52, "text": "Whenever we do hear sorting algorithms come into play such as selection sort, bubble sort, insertion sort, radix sort, bucket sort, etc but if we look closer here we are not asked to use any kind of algorithms. It is as simple sorting with the help of linear and non-linear data structures present within java. So there is sorting done with the help of brute force in java with the help of loops and there are two in-built methods to sort in Java. " }, { "code": null, "e": 525, "s": 501, "text": "Ways of sorting in Java" }, { "code": null, "e": 631, "s": 525, "text": "Using loopsUsing sort() method of Arrays classUsing sort method of Collections classSorting on a subarray" }, { "code": null, "e": 643, "s": 631, "text": "Using loops" }, { "code": null, "e": 679, "s": 643, "text": "Using sort() method of Arrays class" }, { "code": null, "e": 718, "s": 679, "text": "Using sort method of Collections class" }, { "code": null, "e": 740, "s": 718, "text": "Sorting on a subarray" }, { "code": null, "e": 813, "s": 740, "text": "Let us discuss all four of them and propose a code for each one of them." }, { "code": null, "e": 832, "s": 813, "text": "Way 1: Using loops" }, { "code": null, "e": 837, "s": 832, "text": "Java" }, { "code": "// Java Program to sort an elements// by bringing Arrays into play // Main classclass GFG { // Main driver method public static void main(String[] args) { // Custom input array int arr[] = { 4, 3, 2, 1 }; // Outer loop for (int i = 0; i < arr.length; i++) { // Inner nested loop pointing 1 index ahead for (int j = i + 1; j < arr.length; j++) { // Checking elements int temp = 0; if (arr[j] < arr[i]) { // Swapping temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } // Printing sorted array elements System.out.print(arr[i] + \" \"); } }}", "e": 1619, "s": 837, "text": null }, { "code": null, "e": 1628, "s": 1619, "text": "1 2 3 4 " }, { "code": null, "e": 1673, "s": 1628, "text": "Way 2: Using sort() method of Arrays class " }, { "code": null, "e": 1796, "s": 1673, "text": "Arrays.Sort() works for arrays which can be of primitive data type also which in turn by default sorts in ascending order." }, { "code": null, "e": 1806, "s": 1796, "text": "Example 1" }, { "code": null, "e": 1811, "s": 1806, "text": "JAVA" }, { "code": "// Java program to demonstrate working of// sort() method of Arrays class // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input array int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 }; // Calling the sort() method present // inside Arrays class Arrays.sort(arr); // Printing and display sorted array System.out.printf(\"Modified arr[] : %s\", Arrays.toString(arr)); }}", "e": 2393, "s": 1811, "text": null }, { "code": null, "e": 2442, "s": 2393, "text": "Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]" }, { "code": null, "e": 2452, "s": 2442, "text": "Example 2" }, { "code": null, "e": 2457, "s": 2452, "text": "JAVA" }, { "code": "// A sample Java program to sort an array// in descending order using Arrays.sort().import java.util.Arrays;import java.util.Collections; public class GFG { public static void main(String[] args) { // Note that we have Integer here instead of // int[] as Collections.reverseOrder doesn't // work for primitive types. Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sorts arr[] in descending order Arrays.sort(arr, Collections.reverseOrder()); System.out.printf(\"Modified arr[] : %s\", Arrays.toString(arr)); }}", "e": 3056, "s": 2457, "text": null }, { "code": null, "e": 3103, "s": 3056, "text": "Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]" }, { "code": null, "e": 3152, "s": 3103, "text": "Way 3: Using sort() method of Collections class " }, { "code": null, "e": 3232, "s": 3152, "text": "Collections.sort() works for objects Collections like ArrayList and LinkedList." }, { "code": null, "e": 3240, "s": 3232, "text": "Example" }, { "code": null, "e": 3245, "s": 3240, "text": "JAVA" }, { "code": "// Java program to demonstrate working of Collections.sort()import java.util.*; public class GFG { public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add(\"Geeks For Geeks\"); al.add(\"Friends\"); al.add(\"Dear\"); al.add(\"Is\"); al.add(\"Superb\"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al); // Let us print the sorted list System.out.println(\"List after the use of\" + \" Collection.sort() :\\n\" + al); }}", "e": 3897, "s": 3245, "text": null }, { "code": null, "e": 3984, "s": 3897, "text": "List after the use of Collection.sort() :\n[Dear, Friends, Geeks For Geeks, Is, Superb]" }, { "code": null, "e": 3994, "s": 3984, "text": "Example 2" }, { "code": null, "e": 3999, "s": 3994, "text": "JAVA" }, { "code": "// Java program to demonstrate working of Collections.sort()// to descending order.import java.util.*; public class GFG { public static void main(String[] args) { // Create a list of strings ArrayList<String> al = new ArrayList<String>(); al.add(\"Geeks For Geeks\"); al.add(\"Friends\"); al.add(\"Dear\"); al.add(\"Is\"); al.add(\"Superb\"); /* Collections.sort method is sorting the elements of ArrayList in ascending order. */ Collections.sort(al, Collections.reverseOrder()); // Let us print the sorted list System.out.println(\"List after the use of\" + \" Collection.sort() :\\n\" + al); }}", "e": 4702, "s": 3999, "text": null }, { "code": null, "e": 4789, "s": 4702, "text": "List after the use of Collection.sort() :\n[Superb, Is, Geeks For Geeks, Friends, Dear]" }, { "code": null, "e": 4820, "s": 4789, "text": "Way 4: Sorting only a subarray" }, { "code": null, "e": 4825, "s": 4820, "text": "JAVA" }, { "code": "// Java program to sort a subarray// using Arrays.sort() // Importing Arrays class from java.util packageimport java.util.Arrays; // Main classpublic class GFG { // Main drive method public static void main(String[] args) { // Custom input array int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 }; // Sort subarray from index 1 to 4, i.e., // only sort subarray {7, 6, 45, 21} and // keep other elements as it is. Arrays.sort(arr, 1, 5); // Printing sorted array System.out.printf(\"Modified arr[] : %s\", Arrays.toString(arr)); }}", "e": 5444, "s": 4825, "text": null }, { "code": null, "e": 5491, "s": 5444, "text": "Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]" }, { "code": null, "e": 5497, "s": 5491, "text": "Note:" }, { "code": null, "e": 5749, "s": 5497, "text": "Which sorting algorithm does Java use in sort()? Previously, Java’s Arrays.sort method used Quicksort for arrays of primitives and Merge sort for arrays of objects. In the latest versions of Java, Arrays.sort method and Collection.sort() uses Timsort." }, { "code": null, "e": 5832, "s": 5749, "text": "Which order of sorting is done by default? It by default sorts in ascending order." }, { "code": null, "e": 5939, "s": 5832, "text": "How to sort array or list in descending order? It can be done with the help of Collections.reverseOrder()." }, { "code": null, "e": 6093, "s": 5939, "text": "How to write my own sorting function in Java? Please see Java programs for Quick Sort, Merge Sort, Insertion Sort, Selection Sort, Heap Sort, Bubble Sort" }, { "code": null, "e": 6102, "s": 6093, "text": "samyanib" }, { "code": null, "e": 6116, "s": 6102, "text": "solankimayank" }, { "code": null, "e": 6128, "s": 6116, "text": "Java-Arrays" }, { "code": null, "e": 6145, "s": 6128, "text": "Java-Collections" }, { "code": null, "e": 6150, "s": 6145, "text": "Java" }, { "code": null, "e": 6164, "s": 6150, "text": "Java Programs" }, { "code": null, "e": 6172, "s": 6164, "text": "Sorting" }, { "code": null, "e": 6180, "s": 6172, "text": "Sorting" }, { "code": null, "e": 6185, "s": 6180, "text": "Java" }, { "code": null, "e": 6202, "s": 6185, "text": "Java-Collections" }, { "code": null, "e": 6300, "s": 6202, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6319, "s": 6300, "text": "Interfaces in Java" }, { "code": null, "e": 6362, "s": 6319, "text": "How to add an element to an Array in Java?" }, { "code": null, "e": 6386, "s": 6362, "text": "Queue Interface In Java" }, { "code": null, "e": 6423, "s": 6386, "text": "List Interface in Java with Examples" }, { "code": null, "e": 6445, "s": 6423, "text": "PriorityQueue in Java" }, { "code": null, "e": 6473, "s": 6445, "text": "Initializing a List in Java" }, { "code": null, "e": 6499, "s": 6473, "text": "Java Programming Examples" }, { "code": null, "e": 6543, "s": 6499, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 6577, "s": 6543, "text": "Convert Double to Integer in Java" } ]
Method Overloading with Autoboxing and Widening in Java
28 Mar, 2022 Let us go through the basic pre-requisites such as Method Overloading, Autoboxing, and Unboxing. So method overloading in java is based on the number and type of the parameters passed as an argument to the methods. We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible. Autoboxing is the process of converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. While Unboxing is a process of converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int. In Java, there are two types of variables: Primitive type Reference type. Conversion of primitive type to its corresponding wrapper Object is called Autoboxing and Wrapper Object to its corresponding primitive type is known as Unboxing. In method overloading, you may come across a situation where a signature takes reference type or a primitive type as a formal argument. The compiler first searches a method with parameter(s) of the same data type(s). If you are using wrapper class Object as an actual argument and the compiler does not find the method with parameter(s) of the same reference type (i.e. class or interface type), then it starts searching a method with parameter(s) having the corresponding primitive data type. Example Java // Java Program to Illustrate Autoboxing// While resolving data type as:// (a) reference// (b) primitive // Importing required classesimport java.io.*; // Class 1// Helper classclass Conversion { // Method 1 // Overloading method with primitive formal argument public void method(int i) { // Print statement System.out.println( "Primitive type int formal argument :" + i); } // Method 2 // Overloading method with reference formal argument public void method(Integer i) { // Print statement System.out.println( "Reference type Integer formal argument :" + i); } // Method 2 // Overloading method primitive formal argument // and to be invoked for wrapper Object as overloaded // method with wrapper object of same(Long) type as an // argument is not available. public void method(long i) { // Print statement System.out.println( "Primitive type long formal argument :" + i); }} // Class 2// Main classclass GFG { // main driver method public static void main(String[] args) { // Creating instance of class 1 inside main() method Conversion c = new Conversion(); // Invoking the method with different signature c.method(10); c.method(new Integer(15)); c.method(new Long(100)); // Using short will give, argument mismatch; // possible lossy conversion from int to short // c.method(new Short(15)); }} Output: If the compiler fails to find any method corresponding to autoboxing, then it starts searching a method parameter(s) of the widened primitive data type. Implementation: In the example below, we are invoking the overloaded method with primitive(int) formal argument that has the same data type as the actual argument’s data type. We are invoking another method with the argument of Long wrapper Object. The compiler starts searching for the method having the same reference type (Long wrapper class). Since there is no method having with parameter of Long wrapper class. So, It searches for a method that can accept the parameter bigger than long primitive data type as an argument. In this case, it finds a method with float primitive data type and invokes it. Example Java // Java Program to Illustrate method Overloading// In case of Widening // Importing required classesimport java.io.*; // Class 1// Helper classclass Conversion { // Method // overloaded method public void method(int i) { // Print statement System.out.println( "Primitive type int formal argument :" + i); } // Method 2 // overloaded method primitive formal argument // and to be invoked for wrapper Object as public void method(float i) { // Print statement System.out.println( "Primitive type float formal argument :" + i); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating instance of class 1 Conversion c = new Conversion(); // Invoking(calling) method with signature // has widened data type c.method(10); c.method(new Long(100)); }} Output: Note: Priority Order for Primitive types: Same type > Auto Widening > Boxing > Upcasting(Parent Class) > Super Class Priority Order for Reference types: Same type > Upcasting(Parent Class) > Super Class > Unboxing Geeks, ever wondered what happens if widening and boxing happen together? What method of invocation will the compiler be able to do? Widening of primitive types has taken priority over boxing and var-args. But widening and boxing of primitive types can not work together. Example 1A Java // Java program to illustrate Method Overloading for// Widening and autoboxing Together // Importing required classesimport java.io.*; // Class 1// Helper classpublic class Conversion { // Method // Overloading method with // reference type formal argument public void method(Integer a) { // Print statement System.out.println( "Primitive type byte formal argument :" + a); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of above class Conversion c = new Conversion(); // Calling method defined in above class // inside main() method byte val = 5; c.method(val); }} Output: Note: Geeks, but boxing followed by Upcasting is acceptable if this is passed to a reference of type Object for which we will be proposing another example as follows: Example 1B Java // Java program to illustrate Autoboxing Followed by// Widening in Reference Type Variables // Importing required classesimport java.io.*; // Class 1// helper classpublic class Conversion { // Method // Overloading method with reference type // formal argument public void method(Object b) { // Object b is typecasted to Byte and then printed Byte bt = (Byte)b; // Print statement System.out.println( "reference type formal argument :" + bt); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of class 1 inside main() // method Conversion c = new Conversion(); byte val = 5; // b is first widened to Byte // and then Byte is passed to Object c.method(val); }} reference type formal argument :5 Note: Widening of primitive type gets more priority over var-args. Example Java // Java program to illustrate Method Overloading// for var-args and Widening concept Together // Importing required classesimport java.io.*; // Class 1// Helper classpublic class Conversion { // Overloading method primitive(byte) var-args formal // argument public void method(byte... a) { // Print statement System.out.println( "Primitive type byte formal argument :" + a); } // Method 2 // Overloading method primitive(int) formal arguments public void method(long a, long b) { // Print statement System.out.println( "Widening type long formal argument :" + a); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of class 1 inside main() // method Conversion c = new Conversion(); // Invokes the method having widening // primitive type parameters byte val = 5; c.method(val, val); }} Widening type long formal argument :5 This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Akanksha_Rai sumithananthula11 simmytarika5 simranarora5sos sagar0719kumar Java-Overloading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Mar, 2022" }, { "code": null, "e": 707, "s": 54, "text": "Let us go through the basic pre-requisites such as Method Overloading, Autoboxing, and Unboxing. So method overloading in java is based on the number and type of the parameters passed as an argument to the methods. We can not define more than one method with the same name, Order, and type of the arguments. It would be a compiler error. The compiler does not consider the return type while differentiating the overloaded method. But you cannot declare two methods with the same signature and different return types. It will throw a compile-time error. If both methods have the same parameter types, but different return types, then it is not possible." }, { "code": null, "e": 1052, "s": 707, "text": "Autoboxing is the process of converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. While Unboxing is a process of converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int." }, { "code": null, "e": 1096, "s": 1052, "text": "In Java, there are two types of variables: " }, { "code": null, "e": 1111, "s": 1096, "text": "Primitive type" }, { "code": null, "e": 1127, "s": 1111, "text": "Reference type." }, { "code": null, "e": 1290, "s": 1127, "text": "Conversion of primitive type to its corresponding wrapper Object is called Autoboxing and Wrapper Object to its corresponding primitive type is known as Unboxing." }, { "code": null, "e": 1784, "s": 1290, "text": "In method overloading, you may come across a situation where a signature takes reference type or a primitive type as a formal argument. The compiler first searches a method with parameter(s) of the same data type(s). If you are using wrapper class Object as an actual argument and the compiler does not find the method with parameter(s) of the same reference type (i.e. class or interface type), then it starts searching a method with parameter(s) having the corresponding primitive data type." }, { "code": null, "e": 1793, "s": 1784, "text": "Example " }, { "code": null, "e": 1798, "s": 1793, "text": "Java" }, { "code": "// Java Program to Illustrate Autoboxing// While resolving data type as:// (a) reference// (b) primitive // Importing required classesimport java.io.*; // Class 1// Helper classclass Conversion { // Method 1 // Overloading method with primitive formal argument public void method(int i) { // Print statement System.out.println( \"Primitive type int formal argument :\" + i); } // Method 2 // Overloading method with reference formal argument public void method(Integer i) { // Print statement System.out.println( \"Reference type Integer formal argument :\" + i); } // Method 2 // Overloading method primitive formal argument // and to be invoked for wrapper Object as overloaded // method with wrapper object of same(Long) type as an // argument is not available. public void method(long i) { // Print statement System.out.println( \"Primitive type long formal argument :\" + i); }} // Class 2// Main classclass GFG { // main driver method public static void main(String[] args) { // Creating instance of class 1 inside main() method Conversion c = new Conversion(); // Invoking the method with different signature c.method(10); c.method(new Integer(15)); c.method(new Long(100)); // Using short will give, argument mismatch; // possible lossy conversion from int to short // c.method(new Short(15)); }}", "e": 3311, "s": 1798, "text": null }, { "code": null, "e": 3322, "s": 3314, "text": "Output:" }, { "code": null, "e": 3479, "s": 3326, "text": "If the compiler fails to find any method corresponding to autoboxing, then it starts searching a method parameter(s) of the widened primitive data type." }, { "code": null, "e": 3498, "s": 3481, "text": "Implementation: " }, { "code": null, "e": 4092, "s": 3500, "text": "In the example below, we are invoking the overloaded method with primitive(int) formal argument that has the same data type as the actual argument’s data type. We are invoking another method with the argument of Long wrapper Object. The compiler starts searching for the method having the same reference type (Long wrapper class). Since there is no method having with parameter of Long wrapper class. So, It searches for a method that can accept the parameter bigger than long primitive data type as an argument. In this case, it finds a method with float primitive data type and invokes it." }, { "code": null, "e": 4102, "s": 4094, "text": "Example" }, { "code": null, "e": 4109, "s": 4104, "text": "Java" }, { "code": "// Java Program to Illustrate method Overloading// In case of Widening // Importing required classesimport java.io.*; // Class 1// Helper classclass Conversion { // Method // overloaded method public void method(int i) { // Print statement System.out.println( \"Primitive type int formal argument :\" + i); } // Method 2 // overloaded method primitive formal argument // and to be invoked for wrapper Object as public void method(float i) { // Print statement System.out.println( \"Primitive type float formal argument :\" + i); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating instance of class 1 Conversion c = new Conversion(); // Invoking(calling) method with signature // has widened data type c.method(10); c.method(new Long(100)); }}", "e": 5045, "s": 4109, "text": null }, { "code": null, "e": 5056, "s": 5048, "text": "Output:" }, { "code": null, "e": 5064, "s": 5058, "text": "Note:" }, { "code": null, "e": 5175, "s": 5064, "text": "Priority Order for Primitive types: Same type > Auto Widening > Boxing > Upcasting(Parent Class) > Super Class" }, { "code": null, "e": 5272, "s": 5175, "text": "Priority Order for Reference types: Same type > Upcasting(Parent Class) > Super Class > Unboxing" }, { "code": null, "e": 5547, "s": 5274, "text": "Geeks, ever wondered what happens if widening and boxing happen together? What method of invocation will the compiler be able to do? Widening of primitive types has taken priority over boxing and var-args. But widening and boxing of primitive types can not work together." }, { "code": null, "e": 5564, "s": 5549, "text": "Example 1A " }, { "code": null, "e": 5571, "s": 5566, "text": "Java" }, { "code": "// Java program to illustrate Method Overloading for// Widening and autoboxing Together // Importing required classesimport java.io.*; // Class 1// Helper classpublic class Conversion { // Method // Overloading method with // reference type formal argument public void method(Integer a) { // Print statement System.out.println( \"Primitive type byte formal argument :\" + a); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of above class Conversion c = new Conversion(); // Calling method defined in above class // inside main() method byte val = 5; c.method(val); }}", "e": 6316, "s": 5571, "text": null }, { "code": null, "e": 6327, "s": 6319, "text": "Output:" }, { "code": null, "e": 6498, "s": 6329, "text": "Note: Geeks, but boxing followed by Upcasting is acceptable if this is passed to a reference of type Object for which we will be proposing another example as follows: " }, { "code": null, "e": 6511, "s": 6500, "text": "Example 1B" }, { "code": null, "e": 6518, "s": 6513, "text": "Java" }, { "code": "// Java program to illustrate Autoboxing Followed by// Widening in Reference Type Variables // Importing required classesimport java.io.*; // Class 1// helper classpublic class Conversion { // Method // Overloading method with reference type // formal argument public void method(Object b) { // Object b is typecasted to Byte and then printed Byte bt = (Byte)b; // Print statement System.out.println( \"reference type formal argument :\" + bt); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of class 1 inside main() // method Conversion c = new Conversion(); byte val = 5; // b is first widened to Byte // and then Byte is passed to Object c.method(val); }}", "e": 7378, "s": 6518, "text": null }, { "code": null, "e": 7415, "s": 7381, "text": "reference type formal argument :5" }, { "code": null, "e": 7483, "s": 7415, "text": "Note: Widening of primitive type gets more priority over var-args. " }, { "code": null, "e": 7494, "s": 7485, "text": "Example " }, { "code": null, "e": 7501, "s": 7496, "text": "Java" }, { "code": "// Java program to illustrate Method Overloading// for var-args and Widening concept Together // Importing required classesimport java.io.*; // Class 1// Helper classpublic class Conversion { // Overloading method primitive(byte) var-args formal // argument public void method(byte... a) { // Print statement System.out.println( \"Primitive type byte formal argument :\" + a); } // Method 2 // Overloading method primitive(int) formal arguments public void method(long a, long b) { // Print statement System.out.println( \"Widening type long formal argument :\" + a); }} // Class 2// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an instance of class 1 inside main() // method Conversion c = new Conversion(); // Invokes the method having widening // primitive type parameters byte val = 5; c.method(val, val); }}", "e": 8510, "s": 7501, "text": null }, { "code": null, "e": 8551, "s": 8513, "text": "Widening type long formal argument :5" }, { "code": null, "e": 8976, "s": 8553, "text": "This article is contributed by Nitsdheerendra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 8991, "s": 8978, "text": "Akanksha_Rai" }, { "code": null, "e": 9009, "s": 8991, "text": "sumithananthula11" }, { "code": null, "e": 9022, "s": 9009, "text": "simmytarika5" }, { "code": null, "e": 9038, "s": 9022, "text": "simranarora5sos" }, { "code": null, "e": 9053, "s": 9038, "text": "sagar0719kumar" }, { "code": null, "e": 9070, "s": 9053, "text": "Java-Overloading" }, { "code": null, "e": 9075, "s": 9070, "text": "Java" }, { "code": null, "e": 9080, "s": 9075, "text": "Java" }, { "code": null, "e": 9178, "s": 9080, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9229, "s": 9178, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 9260, "s": 9229, "text": "How to iterate any Map in Java" }, { "code": null, "e": 9290, "s": 9260, "text": "HashMap in Java with Examples" }, { "code": null, "e": 9305, "s": 9290, "text": "Stream In Java" }, { "code": null, "e": 9323, "s": 9305, "text": "ArrayList in Java" }, { "code": null, "e": 9343, "s": 9323, "text": "Collections in Java" }, { "code": null, "e": 9367, "s": 9343, "text": "Singleton Class in Java" }, { "code": null, "e": 9399, "s": 9367, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 9411, "s": 9399, "text": "Set in Java" } ]
Java Program for Iterative Merge Sort
Following is the Java program for Iterative Merge Sort − Live Demo import java.util.Arrays; public class Demo{ public static void merge_sort(int[] my_arr){ if(my_arr == null){ return; } if(my_arr.length > 1){ int mid = my_arr.length / 2; int[] left = new int[mid]; for(int i = 0; i < mid; i++){ left[i] = my_arr[i]; } int[] right = new int[my_arr.length - mid]; for(int i = mid; i < my_arr.length; i++){ right[i - mid] = my_arr[i]; } merge_sort(left); merge_sort(right); int i = 0; int j = 0; int k = 0; while(i < left.length && j < right.length){ if(left[i] < right[j]){ my_arr[k] = left[i]; i++; } else { my_arr[k] = right[j]; j++; } k++; } while(i < left.length){ my_arr[k] = left[i]; i++; k++; } while(j < right.length){ my_arr[k] = right[j]; j++; k++; } } } public static void main(String[] args){ int my_arr[] = {56, 78, 91, 21, 34, 0, 11}; int i=0; merge_sort(my_arr); System.out.println("The array after sorting is "); for(i=0; i<my_arr.length; i++) System.out.print(my_arr[i]+" "); } } The array after sorting is 0 11 21 34 56 78 91 A class named Demo contains the ‘merge_sort’ function, that checks if the array is empty, if yes, returns nothing. If the length of the array is greater than one, the value for ‘mid’ is calculated and the array is iterated over upto the ‘mid’ value. Basically the array is divided into two equal parts and the elements to the left of the array are put into a new array and the elements to the right of the array are put into a different array. Now, these arrays are separated and sorted. Then they are merged together. In the main function, the array is defined and the function is called on this array elements. The output is displayed on the console.
[ { "code": null, "e": 1244, "s": 1187, "text": "Following is the Java program for Iterative Merge Sort −" }, { "code": null, "e": 1255, "s": 1244, "text": " Live Demo" }, { "code": null, "e": 2630, "s": 1255, "text": "import java.util.Arrays;\npublic class Demo{\n public static void merge_sort(int[] my_arr){\n if(my_arr == null){\n return;\n }\n if(my_arr.length > 1){\n int mid = my_arr.length / 2;\n int[] left = new int[mid];\n for(int i = 0; i < mid; i++){\n left[i] = my_arr[i];\n }\n int[] right = new int[my_arr.length - mid];\n for(int i = mid; i < my_arr.length; i++){\n right[i - mid] = my_arr[i];\n }\n merge_sort(left);\n merge_sort(right);\n int i = 0;\n int j = 0;\n int k = 0;\n while(i < left.length && j < right.length){\n if(left[i] < right[j]){\n my_arr[k] = left[i];\n i++;\n } else {\n my_arr[k] = right[j];\n j++;\n }\n k++;\n }\n while(i < left.length){\n my_arr[k] = left[i];\n i++;\n k++;\n }\n while(j < right.length){\n my_arr[k] = right[j];\n j++;\n k++;\n }\n }\n }\n public static void main(String[] args){\n int my_arr[] = {56, 78, 91, 21, 34, 0, 11};\n int i=0;\n merge_sort(my_arr);\n System.out.println(\"The array after sorting is \");\n for(i=0; i<my_arr.length; i++)\n System.out.print(my_arr[i]+\" \");\n }\n}" }, { "code": null, "e": 2677, "s": 2630, "text": "The array after sorting is\n0 11 21 34 56 78 91" }, { "code": null, "e": 3196, "s": 2677, "text": "A class named Demo contains the ‘merge_sort’ function, that checks if the array is empty, if yes, returns nothing. If the length of the array is greater than one, the value for ‘mid’ is calculated and the array is iterated over upto the ‘mid’ value. Basically the array is divided into two equal parts and the elements to the left of the array are put into a new array and the elements to the right of the array are put into a different array. Now, these arrays are separated and sorted. Then they are merged together." }, { "code": null, "e": 3330, "s": 3196, "text": "In the main function, the array is defined and the function is called on this array elements. The output is displayed on the console." } ]
Program to wish Women’s Day
20 Jul, 2021 This article demonstrates the pattern to print the Venus Symbol (International gender symbol for females). C++ Java Python3 C# Javascript // C++ code to wish happY Women's DaY #include <bits/stdc++.h>using namespace std;int main(){ // Initializing size of // design int n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (int i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (int j = 0; j <= 2 * n; j++) { // computing distance of // each point from center float center_dist = sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) cout << "$"; else cout << " "; } // Printing HappY Women's DaY if (i == n) cout << " " << "HappY Women's DaY"; cout << endl; } // Loop to print lower part // Outer loop to control // height for (int i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == (n / 2) + 1) { for (int j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) cout << "$"; else cout << " "; } else { for (int j = 0; j <= 2 * n; j++) { if (j == n) cout << "$"; else cout << " "; } } cout << endl; }} // Java code to wish happY Women's DaYimport java.io.*; class GFG{ public static void main (String[] args) { // Initializing size of // design int n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (int i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (int j = 0; j <= 2 * n; j++) { // computing distance of // each point from center float center_dist =(float) Math.sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) System.out.print("$"); else System.out.print(" "); } // Printing HappY Women's DaY if (i == n) System.out.print(" " + "HappY Women's DaY"); System.out.println(); } // Loop to print lower part // Outer loop to control // height for (int i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == (n / 2) + 1) { for (int j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) System.out.print("$"); else System.out.print(" "); } else { for (int j = 0; j <= 2 * n; j++) { if (j == n) System.out.print("$"); else System.out.print(" "); } } System.out.println(); } } } // This code is contributed by vt_m. # Python 3 code to wish HaPpY Women's DaY import math # Initializing size of# designn = 5 # Loop to print Circle# (Upper part of design)# Outer loop to# control height of# designfor i in range(0, 2 * n + 1): # Inner loop to control # width for j in range(0, 2 * n + 1): # computing distance of # each point from center center_dist = math.sqrt((i - n) * (i - n) + (j - n) * (j - n)) if (center_dist > n - 0.5 and center_dist < n + 0.5): print("$", end = "") else: print(end = " ") # Printing HappY Women's DaY if (i == n): print(" ","HappY Women's DaY",end = "") print("") # Loop to print lower part# Outer loop to control# heightfor i in range(0, n+1) : # Positioning pattern # Loop for Printing # horizontal line if (i == int(n / 2) + 1): for j in range(0, 2 * n + 1): if (j >= (n - int(n / 2)) and j <= (n + int(n / 2))): print("$", end = "") else: print(end = " ") else : for j in range(0, 2 * n + 1): if (j == n): print("$", end = "") else: print(end = " ") print("") # This code is contributed by Smitha. // C# code to wish happY Women's DaYusing System; class GFG{ public static void Main () { // Initializing size of // design int n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (int i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (int j = 0; j <= 2 * n; j++) { // computing distance of // each point from center float center_dist = (float) Math.Sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) Console.Write("$"); else Console.Write(" "); } // Printing HappY Women's DaY if (i == n) Console.Write(" " + "HappY Women's DaY"); Console.WriteLine(); } // Loop to print lower part // Outer loop to control // height for (int i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == (n / 2) + 1) { for (int j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) Console.Write("$"); else Console.Write(" "); } else { for (int j = 0; j <= 2 * n; j++) { if (j == n) Console.Write("$"); else Console.Write(" "); } } Console.WriteLine(); } }} // This code is contributed by vt_m. <script> // Initializing size of // design let n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (let i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (let j = 0; j <= 2 * n; j++) { // computing distance of // each point from center let center_dist = Math.sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) document.write("$"); else document.write(" "); } // Printing HappY Women's DaY if (i == n) document.write(" " + "HappY Women's DaY"); document.write("<br>"); } // Loop to print lower part // Outer loop to control // height for (let i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == Math.floor(n / 2) + 1) { for (let j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) document.write("$"); else document.write(" "); } else { for (let j = 0; j <= 2 * n; j++) { if (j == n) document.write("$"); else document.write(" "); } } document.write("<br>"); }// This code is contributed by rag2127</script> Output: $$$$$ $ $ $ $ $ $ $ $ $ $ HappY Women's DaY $ $ $ $ $ $ $ $ $$$$$ $ $ $ $$$$$ $ $ This article is contributed by Shambhavi Singh and Astha Tyagi. Smitha Dinesh Semwal Akanksha_Rai unknown2108 pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python How JVM Works - JVM Architecture? Python program to add two numbers Variables in Java Data types in Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n20 Jul, 2021" }, { "code": null, "e": 163, "s": 54, "text": "This article demonstrates the pattern to print the Venus Symbol (International gender symbol for females). " }, { "code": null, "e": 167, "s": 163, "text": "C++" }, { "code": null, "e": 172, "s": 167, "text": "Java" }, { "code": null, "e": 180, "s": 172, "text": "Python3" }, { "code": null, "e": 183, "s": 180, "text": "C#" }, { "code": null, "e": 194, "s": 183, "text": "Javascript" }, { "code": "// C++ code to wish happY Women's DaY #include <bits/stdc++.h>using namespace std;int main(){ // Initializing size of // design int n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (int i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (int j = 0; j <= 2 * n; j++) { // computing distance of // each point from center float center_dist = sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) cout << \"$\"; else cout << \" \"; } // Printing HappY Women's DaY if (i == n) cout << \" \" << \"HappY Women's DaY\"; cout << endl; } // Loop to print lower part // Outer loop to control // height for (int i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == (n / 2) + 1) { for (int j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) cout << \"$\"; else cout << \" \"; } else { for (int j = 0; j <= 2 * n; j++) { if (j == n) cout << \"$\"; else cout << \" \"; } } cout << endl; }}", "e": 1714, "s": 194, "text": null }, { "code": "// Java code to wish happY Women's DaYimport java.io.*; class GFG{ public static void main (String[] args) { // Initializing size of // design int n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (int i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (int j = 0; j <= 2 * n; j++) { // computing distance of // each point from center float center_dist =(float) Math.sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) System.out.print(\"$\"); else System.out.print(\" \"); } // Printing HappY Women's DaY if (i == n) System.out.print(\" \" + \"HappY Women's DaY\"); System.out.println(); } // Loop to print lower part // Outer loop to control // height for (int i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == (n / 2) + 1) { for (int j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) System.out.print(\"$\"); else System.out.print(\" \"); } else { for (int j = 0; j <= 2 * n; j++) { if (j == n) System.out.print(\"$\"); else System.out.print(\" \"); } } System.out.println(); } } } // This code is contributed by vt_m.", "e": 3648, "s": 1714, "text": null }, { "code": "# Python 3 code to wish HaPpY Women's DaY import math # Initializing size of# designn = 5 # Loop to print Circle# (Upper part of design)# Outer loop to# control height of# designfor i in range(0, 2 * n + 1): # Inner loop to control # width for j in range(0, 2 * n + 1): # computing distance of # each point from center center_dist = math.sqrt((i - n) * (i - n) + (j - n) * (j - n)) if (center_dist > n - 0.5 and center_dist < n + 0.5): print(\"$\", end = \"\") else: print(end = \" \") # Printing HappY Women's DaY if (i == n): print(\" \",\"HappY Women's DaY\",end = \"\") print(\"\") # Loop to print lower part# Outer loop to control# heightfor i in range(0, n+1) : # Positioning pattern # Loop for Printing # horizontal line if (i == int(n / 2) + 1): for j in range(0, 2 * n + 1): if (j >= (n - int(n / 2)) and j <= (n + int(n / 2))): print(\"$\", end = \"\") else: print(end = \" \") else : for j in range(0, 2 * n + 1): if (j == n): print(\"$\", end = \"\") else: print(end = \" \") print(\"\") # This code is contributed by Smitha.", "e": 4964, "s": 3648, "text": null }, { "code": "// C# code to wish happY Women's DaYusing System; class GFG{ public static void Main () { // Initializing size of // design int n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (int i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (int j = 0; j <= 2 * n; j++) { // computing distance of // each point from center float center_dist = (float) Math.Sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) Console.Write(\"$\"); else Console.Write(\" \"); } // Printing HappY Women's DaY if (i == n) Console.Write(\" \" + \"HappY Women's DaY\"); Console.WriteLine(); } // Loop to print lower part // Outer loop to control // height for (int i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == (n / 2) + 1) { for (int j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) Console.Write(\"$\"); else Console.Write(\" \"); } else { for (int j = 0; j <= 2 * n; j++) { if (j == n) Console.Write(\"$\"); else Console.Write(\" \"); } } Console.WriteLine(); } }} // This code is contributed by vt_m.", "e": 6906, "s": 4964, "text": null }, { "code": "<script> // Initializing size of // design let n = 5; // Loop to print Circle // (Upper part of design) // Outer loop to // control height of // design for (let i = 0; i <= 2 * n; i++) { // Inner loop to control // width for (let j = 0; j <= 2 * n; j++) { // computing distance of // each point from center let center_dist = Math.sqrt((i - n) * (i - n) + (j - n) * (j - n)); if (center_dist > n - 0.5 && center_dist < n + 0.5) document.write(\"$\"); else document.write(\" \"); } // Printing HappY Women's DaY if (i == n) document.write(\" \" + \"HappY Women's DaY\"); document.write(\"<br>\"); } // Loop to print lower part // Outer loop to control // height for (let i = 0; i <= n; i++) { // Positioning pattern // Loop for Printing // horizontal line if (i == Math.floor(n / 2) + 1) { for (let j = 0; j <= 2 * n; j++) if (j >= (n - n / 2) && j <= (n + n / 2)) document.write(\"$\"); else document.write(\" \"); } else { for (let j = 0; j <= 2 * n; j++) { if (j == n) document.write(\"$\"); else document.write(\" \"); } } document.write(\"<br>\"); }// This code is contributed by rag2127</script>", "e": 8734, "s": 6906, "text": null }, { "code": null, "e": 8744, "s": 8734, "text": "Output: " }, { "code": null, "e": 8966, "s": 8744, "text": " $$$$$ \n $ $ \n $ $ \n$ $\n$ $\n$ $ HappY Women's DaY\n$ $\n$ $\n $ $ \n $ $ \n $$$$$ \n $ \n $ \n $ \n $$$$$ \n $ \n $ " }, { "code": null, "e": 9031, "s": 8966, "text": "This article is contributed by Shambhavi Singh and Astha Tyagi. " }, { "code": null, "e": 9052, "s": 9031, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 9065, "s": 9052, "text": "Akanksha_Rai" }, { "code": null, "e": 9077, "s": 9065, "text": "unknown2108" }, { "code": null, "e": 9094, "s": 9077, "text": "pattern-printing" }, { "code": null, "e": 9113, "s": 9094, "text": "School Programming" }, { "code": null, "e": 9130, "s": 9113, "text": "pattern-printing" }, { "code": null, "e": 9228, "s": 9130, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9249, "s": 9228, "text": "Constructors in Java" }, { "code": null, "e": 9268, "s": 9249, "text": "Exceptions in Java" }, { "code": null, "e": 9294, "s": 9268, "text": "Python Exception Handling" }, { "code": null, "e": 9312, "s": 9294, "text": "Python Try Except" }, { "code": null, "e": 9339, "s": 9312, "text": "Ternary Operator in Python" }, { "code": null, "e": 9373, "s": 9339, "text": "How JVM Works - JVM Architecture?" }, { "code": null, "e": 9407, "s": 9373, "text": "Python program to add two numbers" }, { "code": null, "e": 9425, "s": 9407, "text": "Variables in Java" }, { "code": null, "e": 9444, "s": 9425, "text": "Data types in Java" } ]
JavaScript | Convert a string to boolean
28 Mar, 2019 Sometimes it is needed to convert a string representing boolean value “true”, “false” into intrinsic type of JavaScript. Given a string and the task is to convert given string to its boolean value. Example 1: This example uses == operator to convert string to its boolean value. <!DOCTYPE html> <html> <head> <title> Convert string to boolean </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="convertToBoolean()"> Click to convert </button> <h3 id = "div" style="color: green"></h3> <!-- Script to convert string to its boolean value --> <script> function convertToBoolean() { var input = document.getElementById("input"); var x = document.getElementById("div"); var str = input.value; x.innerHTML = str == 'true'; } </script> </body> </html> Output: Before click on the button: After click on the button: Example 2: This example uses === operator to convert string to its boolean value. <!DOCTYPE html> <html> <head> <title> Convert string to boolean </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <input id = "input" type="text" name="input"/> <button onclick="convertToBoolean()"> Click to convert </button> <h3 id = "div" style="color: green"></h3> <!-- Script to convert string to its boolean value --> <script> function convertToBoolean() { var input = document.getElementById("input"); var x = document.getElementById("div"); var str = input.value; x.innerHTML = str === 'true'; } </script> </body> </html> Output: Before click on the button: After click on the button: javascript-string JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Mar, 2019" }, { "code": null, "e": 226, "s": 28, "text": "Sometimes it is needed to convert a string representing boolean value “true”, “false” into intrinsic type of JavaScript. Given a string and the task is to convert given string to its boolean value." }, { "code": null, "e": 307, "s": 226, "text": "Example 1: This example uses == operator to convert string to its boolean value." }, { "code": "<!DOCTYPE html> <html> <head> <title> Convert string to boolean </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"convertToBoolean()\"> Click to convert </button> <h3 id = \"div\" style=\"color: green\"></h3> <!-- Script to convert string to its boolean value --> <script> function convertToBoolean() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var str = input.value; x.innerHTML = str == 'true'; } </script> </body> </html> ", "e": 1087, "s": 307, "text": null }, { "code": null, "e": 1095, "s": 1087, "text": "Output:" }, { "code": null, "e": 1123, "s": 1095, "text": "Before click on the button:" }, { "code": null, "e": 1150, "s": 1123, "text": "After click on the button:" }, { "code": null, "e": 1232, "s": 1150, "text": "Example 2: This example uses === operator to convert string to its boolean value." }, { "code": "<!DOCTYPE html> <html> <head> <title> Convert string to boolean </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <input id = \"input\" type=\"text\" name=\"input\"/> <button onclick=\"convertToBoolean()\"> Click to convert </button> <h3 id = \"div\" style=\"color: green\"></h3> <!-- Script to convert string to its boolean value --> <script> function convertToBoolean() { var input = document.getElementById(\"input\"); var x = document.getElementById(\"div\"); var str = input.value; x.innerHTML = str === 'true'; } </script> </body> </html> ", "e": 2013, "s": 1232, "text": null }, { "code": null, "e": 2021, "s": 2013, "text": "Output:" }, { "code": null, "e": 2049, "s": 2021, "text": "Before click on the button:" }, { "code": null, "e": 2076, "s": 2049, "text": "After click on the button:" }, { "code": null, "e": 2094, "s": 2076, "text": "javascript-string" }, { "code": null, "e": 2105, "s": 2094, "text": "JavaScript" }, { "code": null, "e": 2122, "s": 2105, "text": "Web Technologies" }, { "code": null, "e": 2149, "s": 2122, "text": "Web technologies Questions" }, { "code": null, "e": 2247, "s": 2149, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2308, "s": 2247, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2380, "s": 2308, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2420, "s": 2380, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2461, "s": 2420, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2513, "s": 2461, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2546, "s": 2513, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2608, "s": 2546, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2669, "s": 2608, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2719, "s": 2669, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Python 3 basics
30 Jun, 2022 Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.10.4, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it’s not compiled and the interpreter will check the code line by line. This article can be used to learn the very basics of Python programming language. So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, and Java ( I have taken these 3 because they are the most famous and mostly used languages). Python3 # Python code for "Hello World"# nothing else to type...see how simple is the syntax. print("Hello World") Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope. Let us start with our basics of Python where we will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily. Introduction and Setup If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts. It will look somehow this : If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go. It will look like this : If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts. It will look somehow this : If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go. It will look like this : The ” >>> ” represents the python shell and its ready to take python commands and code. Variables and Data Structures In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String. Python3 # Python program to declare variablesmyNumber = 3print(myNumber) myNumber2 = 4.5print(myNumber2) myNumber ="helloworld"print(myNumber) 3 4.5 helloworld See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set. List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list. Python3 # Python program to illustrate a list # creates a empty listnums = [] # appending data in listnums.append(21)nums.append(40.5)nums.append("String") print(nums) [21, 40.5, 'String'] Python3 # Python program to illustrate a Dictionary # creates a empty listDict = [] # putting integer valuesDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict) #Code submitted by Susobhan AKhuli {1: 'Geeks', 2: 'For', 3: 'Geeks'} Python3 # Python program to illustrate a tuple # creates a tuple which is immutabletup = ('Geeks', 'For', 'Geeks') print(tup) #Code submitted by Susobhan AKhuli ('Geeks', 'For', 'Geeks') Python3 # Python program to illustrate a set # define a set and its elementsmyset = set(["Geeks", "For", "Geeks"]) #as set doesn't have duplicate elements so, 1 geeks will not be printedprint(myset) #Code submitted by Susobhan Akhuli Comments: # is used for single line comment in Python """ this is a comment """ is used for multi line comments Input and Output In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user. Python3 # Python program to illustrate# getting input from username = input("Enter your name: ") # user entered the name 'harssh'print("hello", name) Enter your name: hello harssh Python3 # Python3 program to get input from user # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input("Enter num1: "))num2 = int(input("Enter num2: ")) num3 = num1 * num2print("Product is: ", num3) Output: Enter num1: 8 Enter num2: 6 ('Product is: ', 48) Selection Selection in Python is made using the two keywords ‘if’ and ‘elif’(elseif) and else Python3 # Python program to illustrate# selection statement num1 = 34if(num1>12): print("Num1 is good")elif(num1>35): print("Num2 is not gooooo....")else: print("Num2 is great") Num1 is good Functions You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax: def function-name(arguments): #function body Python3 # Python program to illustrate# functionsdef hello(): print("hello") print("hello again")hello() # calling functionhello() hello hello again hello hello again Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages. Python3 # Python program to illustrate # function with maindef getInteger(): result = int(input("Enter integer: ")) return result def Main(): print("Started") # calling the getInteger function and # storing its returned value in the output variable output = getInteger() print(output) # now we are required to tell Python # for 'Main' function existenceif __name__=="__main__": Main() Started Enter integer: 0 Iteration (Looping) As the name suggests it calls repeating things again and again. We will use the most popular ‘for and while’ loop here. Python3 Python3 # Python program to illustrate# a simple for loop for step in range(5): print(step) # Python program to illustrate# a simple while loopstep = 0while(step < 5): print(step) step = step+1 0 1 2 3 4 Modules Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program. Python3 # Python program to illustrate# math moduleimport math def Main(): num = -85 # fabs is used to get the absolute # value of a decimal num = math.fabs(num) print(num) if __name__=="__main__": Main() 85.0 These are some of the most basics of the Python programming language and I will be covering both the intermediate and advanced level Python topics in my upcoming articles. This article is contributed by Harsh Wardhan Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Your article will be reviewed first by Geeks for Geeks team before publishing. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. prabaltiwari09 tejshreelavatre Kiran Kotari kainanjali80 karthikbhatp susobhanakhuli Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas How to get column names in Pandas dataframe Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? Iterate over a list in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 617, "s": 52, "text": "Python was developed by Guido van Rossum in the early 1990s and its latest version is 3.10.4, we can simply call it Python3. Python 3.0 was released in 2008. and is interpreted language i.e it’s not compiled and the interpreter will check the code line by line. This article can be used to learn the very basics of Python programming language. So before moving on further.. let’s do the most popular ‘HelloWorld’ tradition and hence compare Python’s Syntax with C, C++, and Java ( I have taken these 3 because they are the most famous and mostly used languages). " }, { "code": null, "e": 625, "s": 617, "text": "Python3" }, { "code": "# Python code for \"Hello World\"# nothing else to type...see how simple is the syntax. print(\"Hello World\") ", "e": 739, "s": 625, "text": null }, { "code": null, "e": 1045, "s": 739, "text": "Note: Please note that Python for its scope doesn’t depend on the braces ( { } ), instead it uses indentation for its scope. Let us start with our basics of Python where we will be covering the basics in some small sections. Just go through them and trust me you’ll learn the basics of Python very easily." }, { "code": null, "e": 1068, "s": 1045, "text": "Introduction and Setup" }, { "code": null, "e": 1480, "s": 1068, "text": "If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts. It will look somehow this : If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go. It will look like this : " }, { "code": null, "e": 1699, "s": 1480, "text": "If you are on Windows OS download Python by Clicking here and now install from the setup and in the start menu type IDLE.IDLE, you can think it as an Python’s IDE to run the Python Scripts. It will look somehow this : " }, { "code": null, "e": 1893, "s": 1699, "text": "If you are on Linux/Unix-like just open the terminal and on 99% linux OS Python comes preinstalled with the OS.Just type ‘python3’ in terminal and you are ready to go. It will look like this : " }, { "code": null, "e": 1981, "s": 1893, "text": "The ” >>> ” represents the python shell and its ready to take python commands and code." }, { "code": null, "e": 2011, "s": 1981, "text": "Variables and Data Structures" }, { "code": null, "e": 2322, "s": 2011, "text": "In other programming languages like C, C++, and Java, you will need to declare the type of variables but in Python you don’t need to do that. Just type in the variable and when values will be given to it, then it will automatically know whether the value given would be an int, float, or char or even a String." }, { "code": null, "e": 2330, "s": 2322, "text": "Python3" }, { "code": "# Python program to declare variablesmyNumber = 3print(myNumber) myNumber2 = 4.5print(myNumber2) myNumber =\"helloworld\"print(myNumber)", "e": 2469, "s": 2330, "text": null }, { "code": null, "e": 2486, "s": 2469, "text": "3\n4.5\nhelloworld" }, { "code": null, "e": 2698, "s": 2486, "text": "See, how simple is it, just create a variable and assign it any value you want and then use the print function to print it. Python have 4 types of built in Data Structures namely List, Dictionary, Tuple and Set." }, { "code": null, "e": 3033, "s": 2698, "text": "List is the most basic Data Structure in python. List is a mutable data structure i.e items can be added to list later after the list creation. It’s like you are going to shop at the local market and made a list of some items and later on you can add more and more items to the list.append() function is used to add data to the list. " }, { "code": null, "e": 3041, "s": 3033, "text": "Python3" }, { "code": "# Python program to illustrate a list # creates a empty listnums = [] # appending data in listnums.append(21)nums.append(40.5)nums.append(\"String\") print(nums)", "e": 3209, "s": 3041, "text": null }, { "code": null, "e": 3230, "s": 3209, "text": "[21, 40.5, 'String']" }, { "code": null, "e": 3238, "s": 3230, "text": "Python3" }, { "code": "# Python program to illustrate a Dictionary # creates a empty listDict = [] # putting integer valuesDict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict) #Code submitted by Susobhan AKhuli", "e": 3431, "s": 3238, "text": null }, { "code": null, "e": 3466, "s": 3431, "text": "{1: 'Geeks', 2: 'For', 3: 'Geeks'}" }, { "code": null, "e": 3474, "s": 3466, "text": "Python3" }, { "code": "# Python program to illustrate a tuple # creates a tuple which is immutabletup = ('Geeks', 'For', 'Geeks') print(tup) #Code submitted by Susobhan AKhuli", "e": 3632, "s": 3474, "text": null }, { "code": null, "e": 3658, "s": 3632, "text": "('Geeks', 'For', 'Geeks')" }, { "code": null, "e": 3666, "s": 3658, "text": "Python3" }, { "code": "# Python program to illustrate a set # define a set and its elementsmyset = set([\"Geeks\", \"For\", \"Geeks\"]) #as set doesn't have duplicate elements so, 1 geeks will not be printedprint(myset) #Code submitted by Susobhan Akhuli", "e": 3895, "s": 3666, "text": null }, { "code": null, "e": 3905, "s": 3895, "text": "Comments:" }, { "code": null, "e": 4007, "s": 3905, "text": "# is used for single line comment in Python\n\"\"\" this is a comment \"\"\" is used for multi line comments" }, { "code": null, "e": 4024, "s": 4007, "text": "Input and Output" }, { "code": null, "e": 4187, "s": 4024, "text": "In this section, we will learn how to take input from the user and hence manipulate it or simply display it. input() function is used to take input from the user." }, { "code": null, "e": 4195, "s": 4187, "text": "Python3" }, { "code": "# Python program to illustrate# getting input from username = input(\"Enter your name: \") # user entered the name 'harssh'print(\"hello\", name)", "e": 4340, "s": 4195, "text": null }, { "code": null, "e": 4370, "s": 4340, "text": "Enter your name: hello harssh" }, { "code": null, "e": 4378, "s": 4370, "text": "Python3" }, { "code": "# Python3 program to get input from user # accepting integer from the user# the return type of input() function is string ,# so we need to convert the input to integernum1 = int(input(\"Enter num1: \"))num2 = int(input(\"Enter num2: \")) num3 = num1 * num2print(\"Product is: \", num3)", "e": 4662, "s": 4378, "text": null }, { "code": null, "e": 4670, "s": 4662, "text": "Output:" }, { "code": null, "e": 4719, "s": 4670, "text": "Enter num1: 8 Enter num2: 6 ('Product is: ', 48)" }, { "code": null, "e": 4729, "s": 4719, "text": "Selection" }, { "code": null, "e": 4813, "s": 4729, "text": "Selection in Python is made using the two keywords ‘if’ and ‘elif’(elseif) and else" }, { "code": null, "e": 4821, "s": 4813, "text": "Python3" }, { "code": "# Python program to illustrate# selection statement num1 = 34if(num1>12): print(\"Num1 is good\")elif(num1>35): print(\"Num2 is not gooooo....\")else: print(\"Num2 is great\")", "e": 4999, "s": 4821, "text": null }, { "code": null, "e": 5012, "s": 4999, "text": "Num1 is good" }, { "code": null, "e": 5022, "s": 5012, "text": "Functions" }, { "code": null, "e": 5198, "s": 5022, "text": "You can think of functions like a bunch of code that is intended to do a particular task in the whole Python script. Python used the keyword ‘def’ to define a function.Syntax:" }, { "code": null, "e": 5254, "s": 5198, "text": "def function-name(arguments):\n #function body" }, { "code": null, "e": 5262, "s": 5254, "text": "Python3" }, { "code": "# Python program to illustrate# functionsdef hello(): print(\"hello\") print(\"hello again\")hello() # calling functionhello()", "e": 5391, "s": 5262, "text": null }, { "code": null, "e": 5427, "s": 5391, "text": "hello\nhello again\nhello\nhello again" }, { "code": null, "e": 5556, "s": 5427, "text": "Now as we know any program starts from a ‘main’ function...lets create a main function like in many other programming languages." }, { "code": null, "e": 5564, "s": 5556, "text": "Python3" }, { "code": "# Python program to illustrate # function with maindef getInteger(): result = int(input(\"Enter integer: \")) return result def Main(): print(\"Started\") # calling the getInteger function and # storing its returned value in the output variable output = getInteger() print(output) # now we are required to tell Python # for 'Main' function existenceif __name__==\"__main__\": Main()", "e": 5970, "s": 5564, "text": null }, { "code": null, "e": 5995, "s": 5970, "text": "Started\nEnter integer: 0" }, { "code": null, "e": 6015, "s": 5995, "text": "Iteration (Looping)" }, { "code": null, "e": 6135, "s": 6015, "text": "As the name suggests it calls repeating things again and again. We will use the most popular ‘for and while’ loop here." }, { "code": null, "e": 6143, "s": 6135, "text": "Python3" }, { "code": null, "e": 6151, "s": 6143, "text": "Python3" }, { "code": "# Python program to illustrate# a simple for loop for step in range(5): print(step)", "e": 6243, "s": 6151, "text": null }, { "code": "# Python program to illustrate# a simple while loopstep = 0while(step < 5): print(step) step = step+1", "e": 6351, "s": 6243, "text": null }, { "code": null, "e": 6361, "s": 6351, "text": "0\n1\n2\n3\n4" }, { "code": null, "e": 6369, "s": 6361, "text": "Modules" }, { "code": null, "e": 6641, "s": 6369, "text": "Python has a very rich module library that has several functions to do many tasks. You can read more about Python’s standard library by Clicking here‘import’ keyword is used to import a particular module into your python code. For instance consider the following program." }, { "code": null, "e": 6649, "s": 6641, "text": "Python3" }, { "code": "# Python program to illustrate# math moduleimport math def Main(): num = -85 # fabs is used to get the absolute # value of a decimal num = math.fabs(num) print(num) if __name__==\"__main__\": Main()", "e": 6877, "s": 6649, "text": null }, { "code": null, "e": 6882, "s": 6877, "text": "85.0" }, { "code": null, "e": 7054, "s": 6882, "text": "These are some of the most basics of the Python programming language and I will be covering both the intermediate and advanced level Python topics in my upcoming articles." }, { "code": null, "e": 7444, "s": 7054, "text": "This article is contributed by Harsh Wardhan Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Your article will be reviewed first by Geeks for Geeks team before publishing." }, { "code": null, "e": 7569, "s": 7444, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7584, "s": 7569, "text": "prabaltiwari09" }, { "code": null, "e": 7600, "s": 7584, "text": "tejshreelavatre" }, { "code": null, "e": 7613, "s": 7600, "text": "Kiran Kotari" }, { "code": null, "e": 7626, "s": 7613, "text": "kainanjali80" }, { "code": null, "e": 7639, "s": 7626, "text": "karthikbhatp" }, { "code": null, "e": 7654, "s": 7639, "text": "susobhanakhuli" }, { "code": null, "e": 7661, "s": 7654, "text": "Python" }, { "code": null, "e": 7759, "s": 7661, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7787, "s": 7759, "text": "Read JSON file using Python" }, { "code": null, "e": 7809, "s": 7787, "text": "Python map() function" }, { "code": null, "e": 7859, "s": 7809, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 7903, "s": 7859, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 7945, "s": 7903, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 7967, "s": 7945, "text": "Enumerate() in Python" }, { "code": null, "e": 8002, "s": 7967, "text": "Read a file line by line in Python" }, { "code": null, "e": 8028, "s": 8002, "text": "Python String | replace()" }, { "code": null, "e": 8060, "s": 8028, "text": "How to Install PIP on Windows ?" } ]
Remove key value from Map in Scala
13 Aug, 2019 The deletion of Scala map keys can be obtained by utilizing – operator. This operator is utilized to delete the set of keys of the map.Syntax: def -(elem1: A, elem2: A, elems: A*): Map[A, B] It returns a new map containing all the elements of the given Map except the set of keys which are deleted using the above operator.Example #1: // Scala program of deleting // keys // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map("geeks" -> 5, "for" -> 3) // Applying - operator val result = m1.-("for") // Displays output println(result) }} Map(geeks -> 5) In above example here for key is deleted.Example #2: // Scala program of deleting // keys // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 2) // Applying - operator val result = m1.-("for", "geeks") // Displays output println(result) }} Map(cs -> 2) Scala Scala-Map Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Type Casting in Scala Class and Object in Scala Scala Tutorial – Learn Scala with Step By Step Guide Scala Lists Operators in Scala Scala String substring() method with example Scala | Arrays Scala Constructors Enumeration in Scala Inheritance in Scala
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2019" }, { "code": null, "e": 171, "s": 28, "text": "The deletion of Scala map keys can be obtained by utilizing – operator. This operator is utilized to delete the set of keys of the map.Syntax:" }, { "code": null, "e": 220, "s": 171, "text": "def -(elem1: A, elem2: A, elems: A*): Map[A, B]\n" }, { "code": null, "e": 364, "s": 220, "text": "It returns a new map containing all the elements of the given Map except the set of keys which are deleted using the above operator.Example #1:" }, { "code": "// Scala program of deleting // keys // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3) // Applying - operator val result = m1.-(\"for\") // Displays output println(result) }}", "e": 711, "s": 364, "text": null }, { "code": null, "e": 728, "s": 711, "text": "Map(geeks -> 5)\n" }, { "code": null, "e": 781, "s": 728, "text": "In above example here for key is deleted.Example #2:" }, { "code": "// Scala program of deleting // keys // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(\"geeks\" -> 5, \"for\" -> 3, \"cs\" -> 2) // Applying - operator val result = m1.-(\"for\", \"geeks\") // Displays output println(result) }}", "e": 1148, "s": 781, "text": null }, { "code": null, "e": 1162, "s": 1148, "text": "Map(cs -> 2)\n" }, { "code": null, "e": 1168, "s": 1162, "text": "Scala" }, { "code": null, "e": 1178, "s": 1168, "text": "Scala-Map" }, { "code": null, "e": 1184, "s": 1178, "text": "Scala" }, { "code": null, "e": 1282, "s": 1184, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1304, "s": 1282, "text": "Type Casting in Scala" }, { "code": null, "e": 1330, "s": 1304, "text": "Class and Object in Scala" }, { "code": null, "e": 1383, "s": 1330, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 1395, "s": 1383, "text": "Scala Lists" }, { "code": null, "e": 1414, "s": 1395, "text": "Operators in Scala" }, { "code": null, "e": 1459, "s": 1414, "text": "Scala String substring() method with example" }, { "code": null, "e": 1474, "s": 1459, "text": "Scala | Arrays" }, { "code": null, "e": 1493, "s": 1474, "text": "Scala Constructors" }, { "code": null, "e": 1514, "s": 1493, "text": "Enumeration in Scala" } ]
Multiple barplots in R
24 Sep, 2021 Bar plots are a visual representation of the grouped data. It is the most commonly used plot in data analysis activity. In multiple bar plots, we have various bar plots in the form of horizontal and vertical rectangular bars. In these multiple bar plots, the bar represents the relationship between numeric and categorical variables. Let’s learn to create a multiple bar plot with the help of the following examples. The geom_bar() function is used to create bar charts for categorical data x, and histograms for continuous data y. It is inbuilt in the ggplot2 package, we don’t need to install it separately. Syntax: geom_bar( mapping = NULL, data = NULL, stat = “count”, position = “stack”,..) Parameter: mapping: mapping can be created by “aes()” i.e. aesthetic mapping in this mapping we provide the column name as an argument to map onto the plot. The default mapping in geom_bar is NULL. data: data is a data frame that we will be using during the plotting. stat: stat stands for statistics and its default value is count, i.e. we are creating bars based on the number of counts. position: position argument specify how the bars will be placed during the visual representation of the figure. The default value of the position is stack. Here, the position parameter is set to an appropriate value to produce bar plots that are side by side to each other. Example : R # creating multiple bar plots in Rlibrary(ggplot2) # creating a dummy datasetnumber <- c(12,22,11,26,10,20,21,18) gender <- c("Male","Female","Male","Female", "Female","Male","Female","Male") friend_or_not <- c("Unknown","Friend","Unknown", "Friend","Unknown","Friend", "Unknown","Friend") # creating data framecircle <- data.frame(number,gender,friend_or_not) # creating plot using the above dataggplot(circle, aes(gender, number, fill = friend_or_not)) + geom_bar(stat="identity", position = "dodge") + labs(title="Multiple Bar plots") Output: A multiple bar plot using geom_bar() We can use barplot() function to create a Bar plot in R programming language. Below is the syntax of creating a bar plot. We can use the same bar plot syntax with some modifications to create multiple bar plots. Syntax: barplot(data,main,xlab,ylab,..) Parameter: data: data is where we put our dataset name or table name. We can also supply a vector or matrix as an argument in data. main: main is used to display the title of the bar chart. xlab: xlab takes a string as an argument and sets the x-axis label. ylab: ylab takes a string as an argument and sets the y-axis label. To put the graphs, side by side, besides parameter of the boxplot() is set to TRUE. Example: R # creating multiple bar plots in R # creating a dummy data framebarplot1=c(10,2,5,4,6,5,8,10,5,9)barplot2=c(9,5,6,4,7,1,2,6,2,6)barplot3=c(4,2,9,4,3,5,7,10,10,3)data <- data.frame(barplot1,barplot2,barplot3) # plotting multiple bar plotsbarplot(as.matrix(data), main="Multiple Bar Plots", # setting y label only # because x-label will be our # barplots name ylab="Count", # to plot the bars vertically beside=TRUE,) Output: Multiple Bar plots anikakapoor Picked R-Charts R-ggplot R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 445, "s": 28, "text": "Bar plots are a visual representation of the grouped data. It is the most commonly used plot in data analysis activity. In multiple bar plots, we have various bar plots in the form of horizontal and vertical rectangular bars. In these multiple bar plots, the bar represents the relationship between numeric and categorical variables. Let’s learn to create a multiple bar plot with the help of the following examples." }, { "code": null, "e": 639, "s": 445, "text": "The geom_bar() function is used to create bar charts for categorical data x, and histograms for continuous data y. It is inbuilt in the ggplot2 package, we don’t need to install it separately. " }, { "code": null, "e": 725, "s": 639, "text": "Syntax: geom_bar( mapping = NULL, data = NULL, stat = “count”, position = “stack”,..)" }, { "code": null, "e": 736, "s": 725, "text": "Parameter:" }, { "code": null, "e": 923, "s": 736, "text": "mapping: mapping can be created by “aes()” i.e. aesthetic mapping in this mapping we provide the column name as an argument to map onto the plot. The default mapping in geom_bar is NULL." }, { "code": null, "e": 993, "s": 923, "text": "data: data is a data frame that we will be using during the plotting." }, { "code": null, "e": 1115, "s": 993, "text": "stat: stat stands for statistics and its default value is count, i.e. we are creating bars based on the number of counts." }, { "code": null, "e": 1271, "s": 1115, "text": "position: position argument specify how the bars will be placed during the visual representation of the figure. The default value of the position is stack." }, { "code": null, "e": 1389, "s": 1271, "text": "Here, the position parameter is set to an appropriate value to produce bar plots that are side by side to each other." }, { "code": null, "e": 1399, "s": 1389, "text": "Example :" }, { "code": null, "e": 1401, "s": 1399, "text": "R" }, { "code": "# creating multiple bar plots in Rlibrary(ggplot2) # creating a dummy datasetnumber <- c(12,22,11,26,10,20,21,18) gender <- c(\"Male\",\"Female\",\"Male\",\"Female\", \"Female\",\"Male\",\"Female\",\"Male\") friend_or_not <- c(\"Unknown\",\"Friend\",\"Unknown\", \"Friend\",\"Unknown\",\"Friend\", \"Unknown\",\"Friend\") # creating data framecircle <- data.frame(number,gender,friend_or_not) # creating plot using the above dataggplot(circle, aes(gender, number, fill = friend_or_not)) + geom_bar(stat=\"identity\", position = \"dodge\") + labs(title=\"Multiple Bar plots\")", "e": 1988, "s": 1401, "text": null }, { "code": null, "e": 1996, "s": 1988, "text": "Output:" }, { "code": null, "e": 2033, "s": 1996, "text": "A multiple bar plot using geom_bar()" }, { "code": null, "e": 2245, "s": 2033, "text": "We can use barplot() function to create a Bar plot in R programming language. Below is the syntax of creating a bar plot. We can use the same bar plot syntax with some modifications to create multiple bar plots." }, { "code": null, "e": 2285, "s": 2245, "text": "Syntax: barplot(data,main,xlab,ylab,..)" }, { "code": null, "e": 2296, "s": 2285, "text": "Parameter:" }, { "code": null, "e": 2417, "s": 2296, "text": "data: data is where we put our dataset name or table name. We can also supply a vector or matrix as an argument in data." }, { "code": null, "e": 2475, "s": 2417, "text": "main: main is used to display the title of the bar chart." }, { "code": null, "e": 2543, "s": 2475, "text": "xlab: xlab takes a string as an argument and sets the x-axis label." }, { "code": null, "e": 2611, "s": 2543, "text": "ylab: ylab takes a string as an argument and sets the y-axis label." }, { "code": null, "e": 2695, "s": 2611, "text": "To put the graphs, side by side, besides parameter of the boxplot() is set to TRUE." }, { "code": null, "e": 2704, "s": 2695, "text": "Example:" }, { "code": null, "e": 2706, "s": 2704, "text": "R" }, { "code": "# creating multiple bar plots in R # creating a dummy data framebarplot1=c(10,2,5,4,6,5,8,10,5,9)barplot2=c(9,5,6,4,7,1,2,6,2,6)barplot3=c(4,2,9,4,3,5,7,10,10,3)data <- data.frame(barplot1,barplot2,barplot3) # plotting multiple bar plotsbarplot(as.matrix(data), main=\"Multiple Bar Plots\", # setting y label only # because x-label will be our # barplots name ylab=\"Count\", # to plot the bars vertically beside=TRUE,)", "e": 3189, "s": 2706, "text": null }, { "code": null, "e": 3197, "s": 3189, "text": "Output:" }, { "code": null, "e": 3216, "s": 3197, "text": "Multiple Bar plots" }, { "code": null, "e": 3230, "s": 3218, "text": "anikakapoor" }, { "code": null, "e": 3237, "s": 3230, "text": "Picked" }, { "code": null, "e": 3246, "s": 3237, "text": "R-Charts" }, { "code": null, "e": 3255, "s": 3246, "text": "R-ggplot" }, { "code": null, "e": 3264, "s": 3255, "text": "R-Graphs" }, { "code": null, "e": 3272, "s": 3264, "text": "R-plots" }, { "code": null, "e": 3283, "s": 3272, "text": "R Language" }, { "code": null, "e": 3381, "s": 3283, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3433, "s": 3381, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 3491, "s": 3433, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 3543, "s": 3491, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3601, "s": 3543, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3633, "s": 3601, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 3668, "s": 3633, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 3712, "s": 3668, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 3750, "s": 3712, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3799, "s": 3750, "text": "How to filter R DataFrame by values in a column?" } ]
Introduction to Tensor with Tensorflow
06 Dec, 2020 TensorFlow is an open-source software library for dataflow programming across a range of tasks. It is a symbolic math library, and also used for machine learning applications such as neural networks. Google open-sourced TensorFlow in November 2015. Since then, TensorFlow has become the most starred machine learning repository on Github. (https://github.com/tensorflow/tensorflow) Why TensorFlow? TensorFlow’s popularity is due to many things, but primarily because of the computational graph concept, automatic differentiation, and the adaptability of the Tensorflow python API structure. This makes solving real problems with TensorFlow accessible to most programmers. Google’s Tensorflow engine has a unique way of solving problems. This unique way allows for solving machine learning problems very efficiently. We will cover the basic steps to understand how Tensorflow operates. What is Tensor in Tensorflow TensorFlow, as the name indicates, is a framework to define and run computations involving tensors. A tensor is a generalization of vectors and matrices to potentially higher dimensions. Internally, TensorFlow represents tensors as n-dimensional arrays of base datatypes. Each element in the Tensor has the same data type, and the data type is always known. The shape (that is, the number of dimensions it has and the size of each dimension) might be only partially known. Most operations produce tensors of fully-known shapes if the shapes of their inputs are also fully known, but in some cases it’s only possible to find the shape of a tensor at graph execution time. Here we will introduce the general flow of Tensorflow Algorithms. Import or generate dataAll of our machine learning algorithms will depend on data. In practice, we will either generate data or use an outside source of data. Sometimes it is better to rely on generated data because we will want to know the expected outcome. And also tensorflow comes preloaded with famous datasets like MNIST, CIFAR-10, etc.Transform and normalize dataThe data is usually not in the correct dimension or type that our Tensorflow algorithms expect. We will have to transform our data before we can use it. Most algorithms also expect normalized data. Tensorflow has built in functions that can normalize the data for you.data = tf.nn.batch_norm_with_global_normalization(...)Set algorithm parametersOur algorithms usually have a set of parameters that we hold constant throughout the procedure. For example, this can be the number of iterations, the learning rate, or other fixed parameters of our choosing. It is considered good form to initialize these together so the reader or user can easily find them.learning_rate = 0.001 iterations = 1000Initialize variables and placeholdersTensorflow depends on us telling it what it can and cannot modify. Tensorflow will modify the variables during optimization to minimize a loss function. To accomplish this, we feed in data through placeholders. We need to initialize both of these, variables and placeholders with size and type, so that Tensorflow knows what to expect.a_var = tf.constant(42) x_input = tf.placeholder(tf.float32, [None, input_size]) y_input = tf.placeholder(tf.fload32, [None, num_classes])Define the model structureAfter we have the data, and initialized our variables and placeholders, we have to define the model. This is done by building a computational graph. We tell Tensorflow what operations must be done on the variables and placeholders to arrive at our model predictions.y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix)Declare the loss functionsAfter defining the model, we must be able to evaluate the output. This is where we declare the loss function. The loss function is very important as it tells us how far off our predictions are from the actual values.loss = tf.reduce_mean(tf.square(y_actual – y_pred))Initialize and train the modelNow that we have everything in place, we create an instance or our graph and feed in the data through the placeholders and let Tensorflow change the variables to better predict our training data. Here is one way to initialize the computational graph.with tf.Session(graph=graph) as session: ... session.run(...) ...Note that we can also initiate our graph withsession = tf.Session(graph=graph) session.run(...)Evaluate the model(Optional)Once we have built and trained the model, we should evaluate the model by looking at how well it does on new data through some specified criteria.Predict new outcomes(Optional)It is also important to know how to make predictions on new, unseen, data. We can do this with all of our models, once we have them trained. Import or generate dataAll of our machine learning algorithms will depend on data. In practice, we will either generate data or use an outside source of data. Sometimes it is better to rely on generated data because we will want to know the expected outcome. And also tensorflow comes preloaded with famous datasets like MNIST, CIFAR-10, etc. All of our machine learning algorithms will depend on data. In practice, we will either generate data or use an outside source of data. Sometimes it is better to rely on generated data because we will want to know the expected outcome. And also tensorflow comes preloaded with famous datasets like MNIST, CIFAR-10, etc. Transform and normalize dataThe data is usually not in the correct dimension or type that our Tensorflow algorithms expect. We will have to transform our data before we can use it. Most algorithms also expect normalized data. Tensorflow has built in functions that can normalize the data for you.data = tf.nn.batch_norm_with_global_normalization(...) The data is usually not in the correct dimension or type that our Tensorflow algorithms expect. We will have to transform our data before we can use it. Most algorithms also expect normalized data. Tensorflow has built in functions that can normalize the data for you. data = tf.nn.batch_norm_with_global_normalization(...) Set algorithm parametersOur algorithms usually have a set of parameters that we hold constant throughout the procedure. For example, this can be the number of iterations, the learning rate, or other fixed parameters of our choosing. It is considered good form to initialize these together so the reader or user can easily find them.learning_rate = 0.001 iterations = 1000 Our algorithms usually have a set of parameters that we hold constant throughout the procedure. For example, this can be the number of iterations, the learning rate, or other fixed parameters of our choosing. It is considered good form to initialize these together so the reader or user can easily find them. learning_rate = 0.001 iterations = 1000 Initialize variables and placeholdersTensorflow depends on us telling it what it can and cannot modify. Tensorflow will modify the variables during optimization to minimize a loss function. To accomplish this, we feed in data through placeholders. We need to initialize both of these, variables and placeholders with size and type, so that Tensorflow knows what to expect.a_var = tf.constant(42) x_input = tf.placeholder(tf.float32, [None, input_size]) y_input = tf.placeholder(tf.fload32, [None, num_classes]) Tensorflow depends on us telling it what it can and cannot modify. Tensorflow will modify the variables during optimization to minimize a loss function. To accomplish this, we feed in data through placeholders. We need to initialize both of these, variables and placeholders with size and type, so that Tensorflow knows what to expect. a_var = tf.constant(42) x_input = tf.placeholder(tf.float32, [None, input_size]) y_input = tf.placeholder(tf.fload32, [None, num_classes]) Define the model structureAfter we have the data, and initialized our variables and placeholders, we have to define the model. This is done by building a computational graph. We tell Tensorflow what operations must be done on the variables and placeholders to arrive at our model predictions.y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix) After we have the data, and initialized our variables and placeholders, we have to define the model. This is done by building a computational graph. We tell Tensorflow what operations must be done on the variables and placeholders to arrive at our model predictions. y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix) Declare the loss functionsAfter defining the model, we must be able to evaluate the output. This is where we declare the loss function. The loss function is very important as it tells us how far off our predictions are from the actual values.loss = tf.reduce_mean(tf.square(y_actual – y_pred)) After defining the model, we must be able to evaluate the output. This is where we declare the loss function. The loss function is very important as it tells us how far off our predictions are from the actual values. loss = tf.reduce_mean(tf.square(y_actual – y_pred)) Initialize and train the modelNow that we have everything in place, we create an instance or our graph and feed in the data through the placeholders and let Tensorflow change the variables to better predict our training data. Here is one way to initialize the computational graph.with tf.Session(graph=graph) as session: ... session.run(...) ...Note that we can also initiate our graph withsession = tf.Session(graph=graph) session.run(...) Now that we have everything in place, we create an instance or our graph and feed in the data through the placeholders and let Tensorflow change the variables to better predict our training data. Here is one way to initialize the computational graph. with tf.Session(graph=graph) as session: ... session.run(...) ... Note that we can also initiate our graph with session = tf.Session(graph=graph) session.run(...) Evaluate the model(Optional)Once we have built and trained the model, we should evaluate the model by looking at how well it does on new data through some specified criteria. Once we have built and trained the model, we should evaluate the model by looking at how well it does on new data through some specified criteria. Predict new outcomes(Optional)It is also important to know how to make predictions on new, unseen, data. We can do this with all of our models, once we have them trained. It is also important to know how to make predictions on new, unseen, data. We can do this with all of our models, once we have them trained. In Tensorflow, we have to setup the data, variables, placeholders, and model before we tell the program to train and change the variables to improve the predictions. Tensorflow accomplishes this through the computational graph. We tell it to minimize a loss function and Tensorflow does this by modifying the variables in the model. Tensorflow knows how to modify the variables because it keeps track of the computations in the model and automatically computes the gradients for every variable. Because of this, we can see how easy it can be to make changes and try different data sources. Overall, algorithms are designed to be cyclic in TensorFlow. We set up this cycle as a computational graph and (1) feed in data through the placeholders, (2) calculate the output of the computational graph, (3) compare the output to the desired output with a loss function, (4) modify the model variables according to the automatic back propagation, and finally (5) repeat the process until a stopping criteria is met. Now starts the practical session with tensorflow and implementing tensors using it. First, we need to import the required libraries. import tensorflow as tf from tensorflow.python.framework import ops ops.reset_default_graph() Then to start the graph session sess = tf.Session() Now comes the main part i.e. to create tensors. TensorFlow has built in function to create tensors for use in variables. For example, we can create a zero filled tensor of predefined shape using the tf.zeros() function as follows. my_tensor = tf.zeros([1,20]) We can evaluate tensors with calling a run() method on our session. sess.run(my_tensor) TensorFlow algorithms need to know which objects are variables and which are constants. So we create a variable using the TensorFlow function tf.Variable(). Note that you can not run sess.run(my_var), this would result in an error. Because TensorFlow operates with computational graphs, we have to create a variable initialization operation in order to evaluate variables. For this script, we can initialize one variable at a time by calling the variable method my_var.initializer. my_var = tf.Variable(tf.zeros([1,20])) sess.run(my_var.initializer) sess.run(my_var) Output: array([[ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]], dtype=float32) Now let’s create our variable to handle dimensions of having specific shape then initialize the variables with all ‘1’ or ‘0’ row_dim = 2 col_dim = 3 zero_var = tf.Variable(tf.zeros([row_dim, col_dim])) ones_var = tf.Variable(tf.ones([row_dim, col_dim])) Now evaluate the values of them we can run initializer methods on our variables again. sess.run(zero_var.initializer) sess.run(ones_var.initializer) print(sess.run(zero_var)) print(sess.run(ones_var)) Output: [[ 0. 0. 0.] [ 0. 0. 0.]] [[ 1. 1. 1.] [ 1. 1. 1.]] And this list will go on. The rest will be for you study, follow this jupyter notebook by me to get more information about the tensors from here. Visualizing the Variable Creation in TensorBoard To visualize the creation of variables in Tensorboard, we will reset the computational graph and create a global initializing operation. # Reset graphops.reset_default_graph() # Start a graph sessionsess = tf.Session() # Create variablemy_var = tf.Variable(tf.zeros([1,20])) # Add summaries to tensorboardmerged = tf.summary.merge_all() # Initialize graph writer:writer = tf.summary.FileWriter("/tmp/variable_logs", graph=sess.graph) # Initialize operationinitialize_op = tf.global_variables_initializer() # Run initialization of variablesess.run(initialize_op) Now run the following command in cmd. tensorboard --logdir=/tmp And it will tell us the URL we can navigate our browser to see Tensorboard, to achieve your loss graphs. Code to create all types of tensor and evaluate them. import tensorflow as tffrom tensorflow.python.framework import opsops.reset_default_graph() # Introduce tensors in tf # Get graph handlesess = tf.Session() my_tensor = tf.zeros([1,20]) # Declare a variablemy_var = tf.Variable(tf.zeros([1,20])) # Different kinds of variablesrow_dim = 2col_dim = 3 # Zero initialized variablezero_var = tf.Variable(tf.zeros([row_dim, col_dim])) # One initialized variableones_var = tf.Variable(tf.ones([row_dim, col_dim])) # shaped like other variablesess.run(zero_var.initializer)sess.run(ones_var.initializer)zero_similar = tf.Variable(tf.zeros_like(zero_var))ones_similar = tf.Variable(tf.ones_like(ones_var)) sess.run(ones_similar.initializer)sess.run(zero_similar.initializer) # Fill shape with a constantfill_var = tf.Variable(tf.fill([row_dim, col_dim], -1)) # Create a variable from a constantconst_var = tf.Variable(tf.constant([8, 6, 7, 5, 3, 0, 9]))# This can also be used to fill an array:const_fill_var = tf.Variable(tf.constant(-1, shape=[row_dim, col_dim])) # Sequence generationlinear_var = tf.Variable(tf.linspace(start=0.0, stop=1.0, num=3)) # Generates [0.0, 0.5, 1.0] includes the end sequence_var = tf.Variable(tf.range(start=6, limit=15, delta=3)) # Generates [6, 9, 12] doesn't include the end # Random Numbers # Random Normalrnorm_var = tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0) # Add summaries to tensorboardmerged = tf.summary.merge_all() # Initialize graph writer: writer = tf.summary.FileWriter("/tmp/variable_logs", graph=sess.graph) # Initialize operationinitialize_op = tf.global_variables_initializer() # Run initialization of variablesess.run(initialize_op) Output: Reference Link: 1)Tensorflow documentation Akanksha_Rai shubham_singh nidhi_biet Tensorflow GBlog Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You! Geek Streak - 24 Days POTD Challenge What is Hashing | A Complete Tutorial How to Learn Data Science in 10 weeks? Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2020" }, { "code": null, "e": 410, "s": 28, "text": "TensorFlow is an open-source software library for dataflow programming across a range of tasks. It is a symbolic math library, and also used for machine learning applications such as neural networks. Google open-sourced TensorFlow in November 2015. Since then, TensorFlow has become the most starred machine learning repository on Github. (https://github.com/tensorflow/tensorflow)" }, { "code": null, "e": 700, "s": 410, "text": "Why TensorFlow? TensorFlow’s popularity is due to many things, but primarily because of the computational graph concept, automatic differentiation, and the adaptability of the Tensorflow python API structure. This makes solving real problems with TensorFlow accessible to most programmers." }, { "code": null, "e": 913, "s": 700, "text": "Google’s Tensorflow engine has a unique way of solving problems. This unique way allows for solving machine learning problems very efficiently. We will cover the basic steps to understand how Tensorflow operates." }, { "code": null, "e": 942, "s": 913, "text": "What is Tensor in Tensorflow" }, { "code": null, "e": 1613, "s": 942, "text": "TensorFlow, as the name indicates, is a framework to define and run computations involving tensors. A tensor is a generalization of vectors and matrices to potentially higher dimensions. Internally, TensorFlow represents tensors as n-dimensional arrays of base datatypes. Each element in the Tensor has the same data type, and the data type is always known. The shape (that is, the number of dimensions it has and the size of each dimension) might be only partially known. Most operations produce tensors of fully-known shapes if the shapes of their inputs are also fully known, but in some cases it’s only possible to find the shape of a tensor at graph execution time." }, { "code": null, "e": 1679, "s": 1613, "text": "Here we will introduce the general flow of Tensorflow Algorithms." }, { "code": null, "e": 4686, "s": 1679, "text": "Import or generate dataAll of our machine learning algorithms will depend on data. In practice, we will either generate data or use an outside source of data. Sometimes it is better to rely on generated data because we will want to know the expected outcome. And also tensorflow comes preloaded with famous datasets like MNIST, CIFAR-10, etc.Transform and normalize dataThe data is usually not in the correct dimension or type that our Tensorflow algorithms expect. We will have to transform our data before we can use it. Most algorithms also expect normalized data. Tensorflow has built in functions that can normalize the data for you.data = tf.nn.batch_norm_with_global_normalization(...)Set algorithm parametersOur algorithms usually have a set of parameters that we hold constant throughout the procedure. For example, this can be the number of iterations, the learning rate, or other fixed parameters of our choosing. It is considered good form to initialize these together so the reader or user can easily find them.learning_rate = 0.001 iterations = 1000Initialize variables and placeholdersTensorflow depends on us telling it what it can and cannot modify. Tensorflow will modify the variables during optimization to minimize a loss function. To accomplish this, we feed in data through placeholders. We need to initialize both of these, variables and placeholders with size and type, so that Tensorflow knows what to expect.a_var = tf.constant(42) x_input = tf.placeholder(tf.float32, [None, input_size]) y_input = tf.placeholder(tf.fload32, [None, num_classes])Define the model structureAfter we have the data, and initialized our variables and placeholders, we have to define the model. This is done by building a computational graph. We tell Tensorflow what operations must be done on the variables and placeholders to arrive at our model predictions.y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix)Declare the loss functionsAfter defining the model, we must be able to evaluate the output. This is where we declare the loss function. The loss function is very important as it tells us how far off our predictions are from the actual values.loss = tf.reduce_mean(tf.square(y_actual – y_pred))Initialize and train the modelNow that we have everything in place, we create an instance or our graph and feed in the data through the placeholders and let Tensorflow change the variables to better predict our training data. Here is one way to initialize the computational graph.with tf.Session(graph=graph) as session:\n ...\n session.run(...)\n ...Note that we can also initiate our graph withsession = tf.Session(graph=graph) session.run(...)Evaluate the model(Optional)Once we have built and trained the model, we should evaluate the model by looking at how well it does on new data through some specified criteria.Predict new outcomes(Optional)It is also important to know how to make predictions on new, unseen, data. We can do this with all of our models, once we have them trained." }, { "code": null, "e": 5029, "s": 4686, "text": "Import or generate dataAll of our machine learning algorithms will depend on data. In practice, we will either generate data or use an outside source of data. Sometimes it is better to rely on generated data because we will want to know the expected outcome. And also tensorflow comes preloaded with famous datasets like MNIST, CIFAR-10, etc." }, { "code": null, "e": 5349, "s": 5029, "text": "All of our machine learning algorithms will depend on data. In practice, we will either generate data or use an outside source of data. Sometimes it is better to rely on generated data because we will want to know the expected outcome. And also tensorflow comes preloaded with famous datasets like MNIST, CIFAR-10, etc." }, { "code": null, "e": 5700, "s": 5349, "text": "Transform and normalize dataThe data is usually not in the correct dimension or type that our Tensorflow algorithms expect. We will have to transform our data before we can use it. Most algorithms also expect normalized data. Tensorflow has built in functions that can normalize the data for you.data = tf.nn.batch_norm_with_global_normalization(...)" }, { "code": null, "e": 5969, "s": 5700, "text": "The data is usually not in the correct dimension or type that our Tensorflow algorithms expect. We will have to transform our data before we can use it. Most algorithms also expect normalized data. Tensorflow has built in functions that can normalize the data for you." }, { "code": null, "e": 6024, "s": 5969, "text": "data = tf.nn.batch_norm_with_global_normalization(...)" }, { "code": null, "e": 6397, "s": 6024, "text": "Set algorithm parametersOur algorithms usually have a set of parameters that we hold constant throughout the procedure. For example, this can be the number of iterations, the learning rate, or other fixed parameters of our choosing. It is considered good form to initialize these together so the reader or user can easily find them.learning_rate = 0.001 iterations = 1000" }, { "code": null, "e": 6706, "s": 6397, "text": "Our algorithms usually have a set of parameters that we hold constant throughout the procedure. For example, this can be the number of iterations, the learning rate, or other fixed parameters of our choosing. It is considered good form to initialize these together so the reader or user can easily find them." }, { "code": null, "e": 6747, "s": 6706, "text": "learning_rate = 0.001 iterations = 1000" }, { "code": null, "e": 7260, "s": 6747, "text": "Initialize variables and placeholdersTensorflow depends on us telling it what it can and cannot modify. Tensorflow will modify the variables during optimization to minimize a loss function. To accomplish this, we feed in data through placeholders. We need to initialize both of these, variables and placeholders with size and type, so that Tensorflow knows what to expect.a_var = tf.constant(42) x_input = tf.placeholder(tf.float32, [None, input_size]) y_input = tf.placeholder(tf.fload32, [None, num_classes])" }, { "code": null, "e": 7596, "s": 7260, "text": "Tensorflow depends on us telling it what it can and cannot modify. Tensorflow will modify the variables during optimization to minimize a loss function. To accomplish this, we feed in data through placeholders. We need to initialize both of these, variables and placeholders with size and type, so that Tensorflow knows what to expect." }, { "code": null, "e": 7737, "s": 7596, "text": "a_var = tf.constant(42) x_input = tf.placeholder(tf.float32, [None, input_size]) y_input = tf.placeholder(tf.fload32, [None, num_classes])" }, { "code": null, "e": 8087, "s": 7737, "text": "Define the model structureAfter we have the data, and initialized our variables and placeholders, we have to define the model. This is done by building a computational graph. We tell Tensorflow what operations must be done on the variables and placeholders to arrive at our model predictions.y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix)" }, { "code": null, "e": 8354, "s": 8087, "text": "After we have the data, and initialized our variables and placeholders, we have to define the model. This is done by building a computational graph. We tell Tensorflow what operations must be done on the variables and placeholders to arrive at our model predictions." }, { "code": null, "e": 8412, "s": 8354, "text": "y_pred = tf.add(tf.mul(x_input, weight_matrix), b_matrix)" }, { "code": null, "e": 8706, "s": 8412, "text": "Declare the loss functionsAfter defining the model, we must be able to evaluate the output. This is where we declare the loss function. The loss function is very important as it tells us how far off our predictions are from the actual values.loss = tf.reduce_mean(tf.square(y_actual – y_pred))" }, { "code": null, "e": 8923, "s": 8706, "text": "After defining the model, we must be able to evaluate the output. This is where we declare the loss function. The loss function is very important as it tells us how far off our predictions are from the actual values." }, { "code": null, "e": 8975, "s": 8923, "text": "loss = tf.reduce_mean(tf.square(y_actual – y_pred))" }, { "code": null, "e": 9420, "s": 8975, "text": "Initialize and train the modelNow that we have everything in place, we create an instance or our graph and feed in the data through the placeholders and let Tensorflow change the variables to better predict our training data. Here is one way to initialize the computational graph.with tf.Session(graph=graph) as session:\n ...\n session.run(...)\n ...Note that we can also initiate our graph withsession = tf.Session(graph=graph) session.run(...)" }, { "code": null, "e": 9671, "s": 9420, "text": "Now that we have everything in place, we create an instance or our graph and feed in the data through the placeholders and let Tensorflow change the variables to better predict our training data. Here is one way to initialize the computational graph." }, { "code": null, "e": 9740, "s": 9671, "text": "with tf.Session(graph=graph) as session:\n ...\n session.run(...)\n ..." }, { "code": null, "e": 9786, "s": 9740, "text": "Note that we can also initiate our graph with" }, { "code": null, "e": 9838, "s": 9786, "text": "session = tf.Session(graph=graph) session.run(...)" }, { "code": null, "e": 10013, "s": 9838, "text": "Evaluate the model(Optional)Once we have built and trained the model, we should evaluate the model by looking at how well it does on new data through some specified criteria." }, { "code": null, "e": 10160, "s": 10013, "text": "Once we have built and trained the model, we should evaluate the model by looking at how well it does on new data through some specified criteria." }, { "code": null, "e": 10331, "s": 10160, "text": "Predict new outcomes(Optional)It is also important to know how to make predictions on new, unseen, data. We can do this with all of our models, once we have them trained." }, { "code": null, "e": 10472, "s": 10331, "text": "It is also important to know how to make predictions on new, unseen, data. We can do this with all of our models, once we have them trained." }, { "code": null, "e": 11062, "s": 10472, "text": "In Tensorflow, we have to setup the data, variables, placeholders, and model before we tell the program to train and change the variables to improve the predictions. Tensorflow accomplishes this through the computational graph. We tell it to minimize a loss function and Tensorflow does this by modifying the variables in the model. Tensorflow knows how to modify the variables because it keeps track of the computations in the model and automatically computes the gradients for every variable. Because of this, we can see how easy it can be to make changes and try different data sources." }, { "code": null, "e": 11481, "s": 11062, "text": "Overall, algorithms are designed to be cyclic in TensorFlow. We set up this cycle as a computational graph and (1) feed in data through the placeholders, (2) calculate the output of the computational graph, (3) compare the output to the desired output with a loss function, (4) modify the model variables according to the automatic back propagation, and finally (5) repeat the process until a stopping criteria is met." }, { "code": null, "e": 11565, "s": 11481, "text": "Now starts the practical session with tensorflow and implementing tensors using it." }, { "code": null, "e": 11614, "s": 11565, "text": "First, we need to import the required libraries." }, { "code": null, "e": 11708, "s": 11614, "text": "import tensorflow as tf\nfrom tensorflow.python.framework import ops\nops.reset_default_graph()" }, { "code": null, "e": 11740, "s": 11708, "text": "Then to start the graph session" }, { "code": null, "e": 11760, "s": 11740, "text": "sess = tf.Session()" }, { "code": null, "e": 11808, "s": 11760, "text": "Now comes the main part i.e. to create tensors." }, { "code": null, "e": 11991, "s": 11808, "text": "TensorFlow has built in function to create tensors for use in variables. For example, we can create a zero filled tensor of predefined shape using the tf.zeros() function as follows." }, { "code": null, "e": 12020, "s": 11991, "text": "my_tensor = tf.zeros([1,20])" }, { "code": null, "e": 12088, "s": 12020, "text": "We can evaluate tensors with calling a run() method on our session." }, { "code": null, "e": 12108, "s": 12088, "text": "sess.run(my_tensor)" }, { "code": null, "e": 12590, "s": 12108, "text": "TensorFlow algorithms need to know which objects are variables and which are constants. So we create a variable using the TensorFlow function tf.Variable(). Note that you can not run sess.run(my_var), this would result in an error. Because TensorFlow operates with computational graphs, we have to create a variable initialization operation in order to evaluate variables. For this script, we can initialize one variable at a time by calling the variable method my_var.initializer." }, { "code": null, "e": 12676, "s": 12590, "text": "my_var = tf.Variable(tf.zeros([1,20]))\nsess.run(my_var.initializer)\nsess.run(my_var)\n" }, { "code": null, "e": 12684, "s": 12676, "text": "Output:" }, { "code": null, "e": 12839, "s": 12684, "text": "array([[ 0., 0., 0., 0., 0., 0., 0., \n 0., 0., 0., 0., 0., 0., 0., \n 0., 0., 0., 0., 0., 0.]], dtype=float32)" }, { "code": null, "e": 12965, "s": 12839, "text": "Now let’s create our variable to handle dimensions of having specific shape then initialize the variables with all ‘1’ or ‘0’" }, { "code": null, "e": 13095, "s": 12965, "text": "row_dim = 2\ncol_dim = 3\nzero_var = tf.Variable(tf.zeros([row_dim, col_dim]))\nones_var = tf.Variable(tf.ones([row_dim, col_dim]))\n" }, { "code": null, "e": 13182, "s": 13095, "text": "Now evaluate the values of them we can run initializer methods on our variables again." }, { "code": null, "e": 13296, "s": 13182, "text": "sess.run(zero_var.initializer)\nsess.run(ones_var.initializer)\nprint(sess.run(zero_var))\nprint(sess.run(ones_var))" }, { "code": null, "e": 13304, "s": 13296, "text": "Output:" }, { "code": null, "e": 13366, "s": 13304, "text": "[[ 0. 0. 0.]\n [ 0. 0. 0.]]\n[[ 1. 1. 1.]\n [ 1. 1. 1.]]" }, { "code": null, "e": 13512, "s": 13366, "text": "And this list will go on. The rest will be for you study, follow this jupyter notebook by me to get more information about the tensors from here." }, { "code": null, "e": 13561, "s": 13512, "text": "Visualizing the Variable Creation in TensorBoard" }, { "code": null, "e": 13698, "s": 13561, "text": "To visualize the creation of variables in Tensorboard, we will reset the computational graph and create a global initializing operation." }, { "code": "# Reset graphops.reset_default_graph() # Start a graph sessionsess = tf.Session() # Create variablemy_var = tf.Variable(tf.zeros([1,20])) # Add summaries to tensorboardmerged = tf.summary.merge_all() # Initialize graph writer:writer = tf.summary.FileWriter(\"/tmp/variable_logs\", graph=sess.graph) # Initialize operationinitialize_op = tf.global_variables_initializer() # Run initialization of variablesess.run(initialize_op)", "e": 14129, "s": 13698, "text": null }, { "code": null, "e": 14167, "s": 14129, "text": "Now run the following command in cmd." }, { "code": null, "e": 14193, "s": 14167, "text": "tensorboard --logdir=/tmp" }, { "code": null, "e": 14298, "s": 14193, "text": "And it will tell us the URL we can navigate our browser to see Tensorboard, to achieve your loss graphs." }, { "code": null, "e": 14352, "s": 14298, "text": "Code to create all types of tensor and evaluate them." }, { "code": "import tensorflow as tffrom tensorflow.python.framework import opsops.reset_default_graph() # Introduce tensors in tf # Get graph handlesess = tf.Session() my_tensor = tf.zeros([1,20]) # Declare a variablemy_var = tf.Variable(tf.zeros([1,20])) # Different kinds of variablesrow_dim = 2col_dim = 3 # Zero initialized variablezero_var = tf.Variable(tf.zeros([row_dim, col_dim])) # One initialized variableones_var = tf.Variable(tf.ones([row_dim, col_dim])) # shaped like other variablesess.run(zero_var.initializer)sess.run(ones_var.initializer)zero_similar = tf.Variable(tf.zeros_like(zero_var))ones_similar = tf.Variable(tf.ones_like(ones_var)) sess.run(ones_similar.initializer)sess.run(zero_similar.initializer) # Fill shape with a constantfill_var = tf.Variable(tf.fill([row_dim, col_dim], -1)) # Create a variable from a constantconst_var = tf.Variable(tf.constant([8, 6, 7, 5, 3, 0, 9]))# This can also be used to fill an array:const_fill_var = tf.Variable(tf.constant(-1, shape=[row_dim, col_dim])) # Sequence generationlinear_var = tf.Variable(tf.linspace(start=0.0, stop=1.0, num=3)) # Generates [0.0, 0.5, 1.0] includes the end sequence_var = tf.Variable(tf.range(start=6, limit=15, delta=3)) # Generates [6, 9, 12] doesn't include the end # Random Numbers # Random Normalrnorm_var = tf.random_normal([row_dim, col_dim], mean=0.0, stddev=1.0) # Add summaries to tensorboardmerged = tf.summary.merge_all() # Initialize graph writer: writer = tf.summary.FileWriter(\"/tmp/variable_logs\", graph=sess.graph) # Initialize operationinitialize_op = tf.global_variables_initializer() # Run initialization of variablesess.run(initialize_op)", "e": 16013, "s": 14352, "text": null }, { "code": null, "e": 16021, "s": 16013, "text": "Output:" }, { "code": null, "e": 16037, "s": 16021, "text": "Reference Link:" }, { "code": null, "e": 16064, "s": 16037, "text": "1)Tensorflow documentation" }, { "code": null, "e": 16077, "s": 16064, "text": "Akanksha_Rai" }, { "code": null, "e": 16091, "s": 16077, "text": "shubham_singh" }, { "code": null, "e": 16102, "s": 16091, "text": "nidhi_biet" }, { "code": null, "e": 16113, "s": 16102, "text": "Tensorflow" }, { "code": null, "e": 16119, "s": 16113, "text": "GBlog" }, { "code": null, "e": 16126, "s": 16119, "text": "Python" }, { "code": null, "e": 16224, "s": 16126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16249, "s": 16224, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 16304, "s": 16249, "text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!" }, { "code": null, "e": 16341, "s": 16304, "text": "Geek Streak - 24 Days POTD Challenge" }, { "code": null, "e": 16379, "s": 16341, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16418, "s": 16379, "text": "How to Learn Data Science in 10 weeks?" }, { "code": null, "e": 16446, "s": 16418, "text": "Read JSON file using Python" }, { "code": null, "e": 16496, "s": 16446, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 16518, "s": 16496, "text": "Python map() function" } ]
MapReduce - Algorithm
The MapReduce algorithm contains two important tasks, namely Map and Reduce. The map task is done by means of Mapper Class The reduce task is done by means of Reducer Class. Mapper class takes the input, tokenizes it, maps and sorts it. The output of Mapper class is used as input by Reducer class, which in turn searches matching pairs and reduces them. MapReduce implements various mathematical algorithms to divide a task into small parts and assign them to multiple systems. In technical terms, MapReduce algorithm helps in sending the Map & Reduce tasks to appropriate servers in a cluster. These mathematical algorithms may include the following − Sorting Searching Indexing TF-IDF Sorting is one of the basic MapReduce algorithms to process and analyze data. MapReduce implements sorting algorithm to automatically sort the output key-value pairs from the mapper by their keys. Sorting methods are implemented in the mapper class itself. Sorting methods are implemented in the mapper class itself. In the Shuffle and Sort phase, after tokenizing the values in the mapper class, the Context class (user-defined class) collects the matching valued keys as a collection. In the Shuffle and Sort phase, after tokenizing the values in the mapper class, the Context class (user-defined class) collects the matching valued keys as a collection. To collect similar key-value pairs (intermediate keys), the Mapper class takes the help of RawComparator class to sort the key-value pairs. To collect similar key-value pairs (intermediate keys), the Mapper class takes the help of RawComparator class to sort the key-value pairs. The set of intermediate key-value pairs for a given Reducer is automatically sorted by Hadoop to form key-values (K2, {V2, V2, ...}) before they are presented to the Reducer. The set of intermediate key-value pairs for a given Reducer is automatically sorted by Hadoop to form key-values (K2, {V2, V2, ...}) before they are presented to the Reducer. Searching plays an important role in MapReduce algorithm. It helps in the combiner phase (optional) and in the Reducer phase. Let us try to understand how Searching works with the help of an example. The following example shows how MapReduce employs Searching algorithm to find out the details of the employee who draws the highest salary in a given employee dataset. Let us assume we have employee data in four different files − A, B, C, and D. Let us also assume there are duplicate employee records in all four files because of importing the employee data from all database tables repeatedly. See the following illustration. Let us assume we have employee data in four different files − A, B, C, and D. Let us also assume there are duplicate employee records in all four files because of importing the employee data from all database tables repeatedly. See the following illustration. The Map phase processes each input file and provides the employee data in key-value pairs (<k, v> : <emp name, salary>). See the following illustration. The Map phase processes each input file and provides the employee data in key-value pairs (<k, v> : <emp name, salary>). See the following illustration. The combiner phase (searching technique) will accept the input from the Map phase as a key-value pair with employee name and salary. Using searching technique, the combiner will check all the employee salary to find the highest salaried employee in each file. See the following snippet. The combiner phase (searching technique) will accept the input from the Map phase as a key-value pair with employee name and salary. Using searching technique, the combiner will check all the employee salary to find the highest salaried employee in each file. See the following snippet. <k: employee name, v: salary> Max= the salary of an first employee. Treated as max salary if(v(second employee).salary > Max){ Max = v(salary); } else{ Continue checking; } The expected result is as follows − <satish, 26000> <gopal, 50000> <kiran, 45000> <manisha, 45000> Reducer phase − Form each file, you will find the highest salaried employee. To avoid redundancy, check all the <k, v> pairs and eliminate duplicate entries, if any. The same algorithm is used in between the four <k, v> pairs, which are coming from four input files. The final output should be as follows − Reducer phase − Form each file, you will find the highest salaried employee. To avoid redundancy, check all the <k, v> pairs and eliminate duplicate entries, if any. The same algorithm is used in between the four <k, v> pairs, which are coming from four input files. The final output should be as follows − <gopal, 50000> Normally indexing is used to point to a particular data and its address. It performs batch indexing on the input files for a particular Mapper. The indexing technique that is normally used in MapReduce is known as inverted index. Search engines like Google and Bing use inverted indexing technique. Let us try to understand how Indexing works with the help of a simple example. The following text is the input for inverted indexing. Here T[0], T[1], and t[2] are the file names and their content are in double quotes. T[0] = "it is what it is" T[1] = "what is it" T[2] = "it is a banana" After applying the Indexing algorithm, we get the following output − "a": {2} "banana": {2} "is": {0, 1, 2} "it": {0, 1, 2} "what": {0, 1} Here "a": {2} implies the term "a" appears in the T[2] file. Similarly, "is": {0, 1, 2} implies the term "is" appears in the files T[0], T[1], and T[2]. TF-IDF is a text processing algorithm which is short for Term Frequency − Inverse Document Frequency. It is one of the common web analysis algorithms. Here, the term 'frequency' refers to the number of times a term appears in a document. It measures how frequently a particular term occurs in a document. It is calculated by the number of times a word appears in a document divided by the total number of words in that document. TF(the) = (Number of times term the ‘the’ appears in a document) / (Total number of terms in the document) It measures the importance of a term. It is calculated by the number of documents in the text database divided by the number of documents where a specific term appears. While computing TF, all the terms are considered equally important. That means, TF counts the term frequency for normal words like “is”, “a”, “what”, etc. Thus we need to know the frequent terms while scaling up the rare ones, by computing the following − IDF(the) = log_e(Total number of documents / Number of documents with term ‘the’ in it). The algorithm is explained below with the help of a small example. Consider a document containing 1000 words, wherein the word hive appears 50 times. The TF for hive is then (50 / 1000) = 0.05. Now, assume we have 10 million documents and the word hive appears in 1000 of these. Then, the IDF is calculated as log(10,000,000 / 1,000) = 4. The TF-IDF weight is the product of these quantities − 0.05 × 4 = 0.20.
[ { "code": null, "e": 2001, "s": 1924, "text": "The MapReduce algorithm contains two important tasks, namely Map and Reduce." }, { "code": null, "e": 2047, "s": 2001, "text": "The map task is done by means of Mapper Class" }, { "code": null, "e": 2098, "s": 2047, "text": "The reduce task is done by means of Reducer Class." }, { "code": null, "e": 2280, "s": 2098, "text": "Mapper class takes the input, tokenizes it, maps and sorts it. The output of Mapper class is used as input by Reducer class, which in turn searches matching pairs and reduces them." }, { "code": null, "e": 2521, "s": 2280, "text": "MapReduce implements various mathematical algorithms to divide a task into small parts and assign them to multiple systems. In technical terms, MapReduce algorithm helps in sending the Map & Reduce tasks to appropriate servers in a cluster." }, { "code": null, "e": 2579, "s": 2521, "text": "These mathematical algorithms may include the following −" }, { "code": null, "e": 2587, "s": 2579, "text": "Sorting" }, { "code": null, "e": 2597, "s": 2587, "text": "Searching" }, { "code": null, "e": 2606, "s": 2597, "text": "Indexing" }, { "code": null, "e": 2613, "s": 2606, "text": "TF-IDF" }, { "code": null, "e": 2810, "s": 2613, "text": "Sorting is one of the basic MapReduce algorithms to process and analyze data. MapReduce implements sorting algorithm to automatically sort the output key-value pairs from the mapper by their keys." }, { "code": null, "e": 2870, "s": 2810, "text": "Sorting methods are implemented in the mapper class itself." }, { "code": null, "e": 2930, "s": 2870, "text": "Sorting methods are implemented in the mapper class itself." }, { "code": null, "e": 3100, "s": 2930, "text": "In the Shuffle and Sort phase, after tokenizing the values in the mapper class, the Context class (user-defined class) collects the matching valued keys as a collection." }, { "code": null, "e": 3270, "s": 3100, "text": "In the Shuffle and Sort phase, after tokenizing the values in the mapper class, the Context class (user-defined class) collects the matching valued keys as a collection." }, { "code": null, "e": 3410, "s": 3270, "text": "To collect similar key-value pairs (intermediate keys), the Mapper class takes the help of RawComparator class to sort the key-value pairs." }, { "code": null, "e": 3550, "s": 3410, "text": "To collect similar key-value pairs (intermediate keys), the Mapper class takes the help of RawComparator class to sort the key-value pairs." }, { "code": null, "e": 3725, "s": 3550, "text": "The set of intermediate key-value pairs for a given Reducer is automatically sorted by Hadoop to form key-values (K2, {V2, V2, ...}) before they are presented to the Reducer." }, { "code": null, "e": 3900, "s": 3725, "text": "The set of intermediate key-value pairs for a given Reducer is automatically sorted by Hadoop to form key-values (K2, {V2, V2, ...}) before they are presented to the Reducer." }, { "code": null, "e": 4100, "s": 3900, "text": "Searching plays an important role in MapReduce algorithm. It helps in the combiner phase (optional) and in the Reducer phase. Let us try to understand how Searching works with the help of an example." }, { "code": null, "e": 4268, "s": 4100, "text": "The following example shows how MapReduce employs Searching algorithm to find out the details of the employee who draws the highest salary in a given employee dataset." }, { "code": null, "e": 4528, "s": 4268, "text": "Let us assume we have employee data in four different files − A, B, C, and D. Let us also assume there are duplicate employee records in all four files because of importing the employee data from all database tables repeatedly. See the following illustration." }, { "code": null, "e": 4788, "s": 4528, "text": "Let us assume we have employee data in four different files − A, B, C, and D. Let us also assume there are duplicate employee records in all four files because of importing the employee data from all database tables repeatedly. See the following illustration." }, { "code": null, "e": 4941, "s": 4788, "text": "The Map phase processes each input file and provides the employee data in key-value pairs (<k, v> : <emp name, salary>). See the following illustration." }, { "code": null, "e": 5094, "s": 4941, "text": "The Map phase processes each input file and provides the employee data in key-value pairs (<k, v> : <emp name, salary>). See the following illustration." }, { "code": null, "e": 5381, "s": 5094, "text": "The combiner phase (searching technique) will accept the input from the Map phase as a key-value pair with employee name and salary. Using searching technique, the combiner will check all the employee salary to find the highest salaried employee in each file. See the following snippet." }, { "code": null, "e": 5668, "s": 5381, "text": "The combiner phase (searching technique) will accept the input from the Map phase as a key-value pair with employee name and salary. Using searching technique, the combiner will check all the employee salary to find the highest salaried employee in each file. See the following snippet." }, { "code": null, "e": 5849, "s": 5668, "text": "<k: employee name, v: salary>\nMax= the salary of an first employee. Treated as max salary\n\nif(v(second employee).salary > Max){\n Max = v(salary);\n}\n\nelse{\n Continue checking;\n}" }, { "code": null, "e": 5885, "s": 5849, "text": "The expected result is as follows −" }, { "code": null, "e": 5901, "s": 5885, "text": "<satish, 26000>" }, { "code": null, "e": 5916, "s": 5901, "text": "<gopal, 50000>" }, { "code": null, "e": 5931, "s": 5916, "text": "<kiran, 45000>" }, { "code": null, "e": 5948, "s": 5931, "text": "<manisha, 45000>" }, { "code": null, "e": 6255, "s": 5948, "text": "Reducer phase − Form each file, you will find the highest salaried employee. To avoid redundancy, check all the <k, v> pairs and eliminate duplicate entries, if any. The same algorithm is used in between the four <k, v> pairs, which are coming from four input files. The final output should be as follows −" }, { "code": null, "e": 6562, "s": 6255, "text": "Reducer phase − Form each file, you will find the highest salaried employee. To avoid redundancy, check all the <k, v> pairs and eliminate duplicate entries, if any. The same algorithm is used in between the four <k, v> pairs, which are coming from four input files. The final output should be as follows −" }, { "code": null, "e": 6578, "s": 6562, "text": "<gopal, 50000>\n" }, { "code": null, "e": 6722, "s": 6578, "text": "Normally indexing is used to point to a particular data and its address. It performs batch indexing on the input files for a particular Mapper." }, { "code": null, "e": 6956, "s": 6722, "text": "The indexing technique that is normally used in MapReduce is known as inverted index. Search engines like Google and Bing use inverted indexing technique. Let us try to understand how Indexing works with the help of a simple example." }, { "code": null, "e": 7096, "s": 6956, "text": "The following text is the input for inverted indexing. Here T[0], T[1], and t[2] are the file names and their content are in double quotes." }, { "code": null, "e": 7167, "s": 7096, "text": "T[0] = \"it is what it is\"\nT[1] = \"what is it\"\nT[2] = \"it is a banana\"\n" }, { "code": null, "e": 7236, "s": 7167, "text": "After applying the Indexing algorithm, we get the following output −" }, { "code": null, "e": 7307, "s": 7236, "text": "\"a\": {2}\n\"banana\": {2}\n\"is\": {0, 1, 2}\n\"it\": {0, 1, 2}\n\"what\": {0, 1}\n" }, { "code": null, "e": 7460, "s": 7307, "text": "Here \"a\": {2} implies the term \"a\" appears in the T[2] file. Similarly, \"is\": {0, 1, 2} implies the term \"is\" appears in the files T[0], T[1], and T[2]." }, { "code": null, "e": 7698, "s": 7460, "text": "TF-IDF is a text processing algorithm which is short for Term Frequency − Inverse Document Frequency. It is one of the common web analysis algorithms. Here, the term 'frequency' refers to the number of times a term appears in a document." }, { "code": null, "e": 7889, "s": 7698, "text": "It measures how frequently a particular term occurs in a document. It is calculated by the number of times a word appears in a document divided by the total number of words in that document." }, { "code": null, "e": 7997, "s": 7889, "text": "TF(the) = (Number of times term the ‘the’ appears in a document) / (Total number of terms in the document)\n" }, { "code": null, "e": 8166, "s": 7997, "text": "It measures the importance of a term. It is calculated by the number of documents in the text database divided by the number of documents where a specific term appears." }, { "code": null, "e": 8422, "s": 8166, "text": "While computing TF, all the terms are considered equally important. That means, TF counts the term frequency for normal words like “is”, “a”, “what”, etc. Thus we need to know the frequent terms while scaling up the rare ones, by computing the following −" }, { "code": null, "e": 8512, "s": 8422, "text": "IDF(the) = log_e(Total number of documents / Number of documents with term ‘the’ in it).\n" }, { "code": null, "e": 8579, "s": 8512, "text": "The algorithm is explained below with the help of a small example." }, { "code": null, "e": 8706, "s": 8579, "text": "Consider a document containing 1000 words, wherein the word hive appears 50 times. The TF for hive is then (50 / 1000) = 0.05." }, { "code": null, "e": 8851, "s": 8706, "text": "Now, assume we have 10 million documents and the word hive appears in 1000 of these. Then, the IDF is calculated as log(10,000,000 / 1,000) = 4." } ]
Plot a bar using matplotlib using a dictionary
First, we can define our dictionary and then, convert that dictionary into keys and values. Finally, we can use the data to plot a bar chart. Create a dictionary, i.e., data, where milk and water are the keys. Create a dictionary, i.e., data, where milk and water are the keys. Get the list of keys of the dictionary. Get the list of keys of the dictionary. Get the list of values of the dictionary. Get the list of values of the dictionary. Plot the bar using plt.bar(). Plot the bar using plt.bar(). Using plt.show(), show the figure. Using plt.show(), show the figure. import matplotlib.pyplot as plt data = {'milk': 60, 'water': 10} names = list(data.keys()) values = list(data.values()) plt.bar(range(len(data)), values, tick_label=names) plt.show()
[ { "code": null, "e": 1204, "s": 1062, "text": "First, we can define our dictionary and then, convert that dictionary into keys and values. Finally, we can use the data to plot a bar chart." }, { "code": null, "e": 1272, "s": 1204, "text": "Create a dictionary, i.e., data, where milk and water are the keys." }, { "code": null, "e": 1340, "s": 1272, "text": "Create a dictionary, i.e., data, where milk and water are the keys." }, { "code": null, "e": 1380, "s": 1340, "text": "Get the list of keys of the dictionary." }, { "code": null, "e": 1420, "s": 1380, "text": "Get the list of keys of the dictionary." }, { "code": null, "e": 1462, "s": 1420, "text": "Get the list of values of the dictionary." }, { "code": null, "e": 1504, "s": 1462, "text": "Get the list of values of the dictionary." }, { "code": null, "e": 1534, "s": 1504, "text": "Plot the bar using plt.bar()." }, { "code": null, "e": 1564, "s": 1534, "text": "Plot the bar using plt.bar()." }, { "code": null, "e": 1599, "s": 1564, "text": "Using plt.show(), show the figure." }, { "code": null, "e": 1634, "s": 1599, "text": "Using plt.show(), show the figure." }, { "code": null, "e": 1819, "s": 1634, "text": "import matplotlib.pyplot as plt\n\ndata = {'milk': 60, 'water': 10}\nnames = list(data.keys())\nvalues = list(data.values())\n\nplt.bar(range(len(data)), values, tick_label=names)\nplt.show()" } ]
M1 competes with 20 cores Xeon®on TensorFlow training | Towards Data Science
In the first part of M1 Benchmark article I was comparing a MacBook Air M1 with an iMac 27" core i5, a 8 cores Xeon(R) Platinum, a K80 GPU instance and a T4 GPU instance on three TensorFlow models. While the GPU was not as efficient as expected, maybe because of the very early version of TensorFlow not yet entirely optimized for M1, it was clearly showing very impressive CPU performances beating by far the iMac and 8 cores Xeon(R) Platinum instance. While it’s usually unfair to compare an entry price laptop with such high-end configurations, the M1 has an advantage; it has 8 physical cores. The iMac 27" Core i5 has 4 cores and the 8 cores Xeon(R) Platinum is like every instance counting the vCPU, so only has 4 physical cores. I’ve doubled checked core id, siblings and physical id to make sure by following this paper. In this article, I compare the M1 with more powerful configurations having 8 to 20 physical cores (16 to 40 hyper-threaded cores). The AMD EPYC configurations are instances while the Xeon(R) Silver is a BareMetal, meaning a true physical dedicated server. The Xeon(R) server has two CPUs with 10 cores (20 threads) each, so totalize 20 physical cores (40 threads). It uses TensorFlow 2.3.1 to benefit from some compilation options. At startup it displays the following: This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA I also compared with the Intel(R) MKL delivered with Anaconda. Both are showing similar performances. The MacBook Air is using Apple Silicon native version of TensorFlow capable to benefit from the full potential of the M1 (even if part 1 article shows that GPU does look yet optimized). As a reminder (as shown in this previous article) here are the M1 specs. 8-core CPU (4 high performances at 3.2 GHz, 4 high efficiency at 2.06 GHz) 8-core GPU (128 execution units, 24 576 threads, 2.6 TFlops) 16-core Neural Engine dedicated to linear algebra Unified Memory Architecture 4 266 MT/s (34 128 MB/s data transfer) You can find the models and the dataset used in the previous article. The following plots shows the results for trainings on CPU. In CPU training, the MacBook Air M1 exceeds by far the performances of the two AMD EPYC and of the 20/40 cores Intel(R) Xeon(R) Silver on MLP and LSTM. Only the convnet gives a very small advantage to the Xeon(R) for 128 and 512 samples batch size and the AMD EPYC 16/32 is only slightly better for 512 samples batch size. The following plot shows how many times other devices are slower than M1 CPU. For MLP and LSTM M1 is about 5 to 13 times faster than 8/16 cores AMD EPYC, 3 to 12 times faster than 16/32 cores AMD EPYC and 2 to 10 times faster than 20/40 cores Xeon(R) Silver BareMetal. For CNN, M1 is roughly 2.5 times faster than the others for 32 samples batch size, 2 times faster than AMD EPYC on the other batch size and only 10% to 20% slower than 20/40 cores Xeon(R) Silver on 128 and 512 samples batch size. Let’s check the CPU consumption for the Xeon(R) during training. Half of the cores are loaded at about 70% meaning the hyper-threading is useless in this case, only the physical cores are used. Now let’s check the M1 CPU history during the whole benchmark. It’s surprisingly showing that only 4 cores are really used but only at 50% during MLP and CNN training. The maximum load happened during the LSTM training; this is also the only case where the 4 other cores are loaded up to 50%. We can suppose the most loaded are the “high performance” cores at 3.2 GHz. So how does the M1 can, by only partially using half of its cores, achieve such superior performances, beating by far a 20/40 cores Xeon(R) Silver using a TensorFlow version compiled with AVX-512 instructions? The M1 “performance” cores have a frequency 50% higher than the Xeon(R) but this one has 20 physical cores, making this frequency difference not sufficient to explain such performance gap. As Apple is never disclosing details of its processor’s designs, it’s difficult to know how the different parts of M1 are really used. Anyway, we can try to formulate some hypothesis. The M1 CPU includes “ML Accelerators” as mentioned here, they are used by ML Compute BNNS primitives when training Neural Networks models on CPU. If we refer to this article we can suppose “ML Accelerators” is the generic name for AMX2 (Apple Matrix Co-processor), so it’s maybe more something like a mini NPU capable to accelerate linear algebra computing and especially matrix multiplications. But unlike the Neural Engine it’s built to work with the CPU instead of being a standalone component, so reducing the latencies and improving the throughput for intensive matrix computing. This can explain why the maximum gap is observed on LSTM as this type of unit is not only vector based but require much more iterative processing. The combination of a CPU and a high throughput matrix computing unit seems very efficient for such models The Universal Memory design enables a much faster data access for each core and every component of the SoC coupled with a better CPU design enabling more efficient parallel processing Again, these are hypothesis and only Apple can explain how it really works. From these tests, it appears that for training MLP and LSTM, M1 CPU is by far much faster than all the high-end servers tested for training CNN, M1 is only slightly slower than the high-end servers tested Of course, these metrics can only be considered for similar neural network types and depths as used in this test. For big trainings and intensive computing lasting for more than 20 minutes, I will still go for cloud-based solutions as they provide cards built for such long heavy load and enable sending several jobs simultaneously. But this scenario is only for some specific research representing only 10% of my work, mostly for professional usage in some specific business area. As a machine learning engineer, for my day-to-day personal research, M1 Mac is clearly the best and the most cost-efficient option today. Thank you for reading.
[ { "code": null, "e": 369, "s": 171, "text": "In the first part of M1 Benchmark article I was comparing a MacBook Air M1 with an iMac 27\" core i5, a 8 cores Xeon(R) Platinum, a K80 GPU instance and a T4 GPU instance on three TensorFlow models." }, { "code": null, "e": 625, "s": 369, "text": "While the GPU was not as efficient as expected, maybe because of the very early version of TensorFlow not yet entirely optimized for M1, it was clearly showing very impressive CPU performances beating by far the iMac and 8 cores Xeon(R) Platinum instance." }, { "code": null, "e": 769, "s": 625, "text": "While it’s usually unfair to compare an entry price laptop with such high-end configurations, the M1 has an advantage; it has 8 physical cores." }, { "code": null, "e": 1000, "s": 769, "text": "The iMac 27\" Core i5 has 4 cores and the 8 cores Xeon(R) Platinum is like every instance counting the vCPU, so only has 4 physical cores. I’ve doubled checked core id, siblings and physical id to make sure by following this paper." }, { "code": null, "e": 1131, "s": 1000, "text": "In this article, I compare the M1 with more powerful configurations having 8 to 20 physical cores (16 to 40 hyper-threaded cores)." }, { "code": null, "e": 1256, "s": 1131, "text": "The AMD EPYC configurations are instances while the Xeon(R) Silver is a BareMetal, meaning a true physical dedicated server." }, { "code": null, "e": 1365, "s": 1256, "text": "The Xeon(R) server has two CPUs with 10 cores (20 threads) each, so totalize 20 physical cores (40 threads)." }, { "code": null, "e": 1470, "s": 1365, "text": "It uses TensorFlow 2.3.1 to benefit from some compilation options. At startup it displays the following:" }, { "code": null, "e": 1646, "s": 1470, "text": "This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN)to use the following CPU instructions in performance-critical operations: AVX2 AVX512F FMA" }, { "code": null, "e": 1748, "s": 1646, "text": "I also compared with the Intel(R) MKL delivered with Anaconda. Both are showing similar performances." }, { "code": null, "e": 1934, "s": 1748, "text": "The MacBook Air is using Apple Silicon native version of TensorFlow capable to benefit from the full potential of the M1 (even if part 1 article shows that GPU does look yet optimized)." }, { "code": null, "e": 2007, "s": 1934, "text": "As a reminder (as shown in this previous article) here are the M1 specs." }, { "code": null, "e": 2082, "s": 2007, "text": "8-core CPU (4 high performances at 3.2 GHz, 4 high efficiency at 2.06 GHz)" }, { "code": null, "e": 2143, "s": 2082, "text": "8-core GPU (128 execution units, 24 576 threads, 2.6 TFlops)" }, { "code": null, "e": 2193, "s": 2143, "text": "16-core Neural Engine dedicated to linear algebra" }, { "code": null, "e": 2260, "s": 2193, "text": "Unified Memory Architecture 4 266 MT/s (34 128 MB/s data transfer)" }, { "code": null, "e": 2330, "s": 2260, "text": "You can find the models and the dataset used in the previous article." }, { "code": null, "e": 2390, "s": 2330, "text": "The following plots shows the results for trainings on CPU." }, { "code": null, "e": 2713, "s": 2390, "text": "In CPU training, the MacBook Air M1 exceeds by far the performances of the two AMD EPYC and of the 20/40 cores Intel(R) Xeon(R) Silver on MLP and LSTM. Only the convnet gives a very small advantage to the Xeon(R) for 128 and 512 samples batch size and the AMD EPYC 16/32 is only slightly better for 512 samples batch size." }, { "code": null, "e": 2791, "s": 2713, "text": "The following plot shows how many times other devices are slower than M1 CPU." }, { "code": null, "e": 3212, "s": 2791, "text": "For MLP and LSTM M1 is about 5 to 13 times faster than 8/16 cores AMD EPYC, 3 to 12 times faster than 16/32 cores AMD EPYC and 2 to 10 times faster than 20/40 cores Xeon(R) Silver BareMetal. For CNN, M1 is roughly 2.5 times faster than the others for 32 samples batch size, 2 times faster than AMD EPYC on the other batch size and only 10% to 20% slower than 20/40 cores Xeon(R) Silver on 128 and 512 samples batch size." }, { "code": null, "e": 3277, "s": 3212, "text": "Let’s check the CPU consumption for the Xeon(R) during training." }, { "code": null, "e": 3406, "s": 3277, "text": "Half of the cores are loaded at about 70% meaning the hyper-threading is useless in this case, only the physical cores are used." }, { "code": null, "e": 3469, "s": 3406, "text": "Now let’s check the M1 CPU history during the whole benchmark." }, { "code": null, "e": 3775, "s": 3469, "text": "It’s surprisingly showing that only 4 cores are really used but only at 50% during MLP and CNN training. The maximum load happened during the LSTM training; this is also the only case where the 4 other cores are loaded up to 50%. We can suppose the most loaded are the “high performance” cores at 3.2 GHz." }, { "code": null, "e": 4174, "s": 3775, "text": "So how does the M1 can, by only partially using half of its cores, achieve such superior performances, beating by far a 20/40 cores Xeon(R) Silver using a TensorFlow version compiled with AVX-512 instructions? The M1 “performance” cores have a frequency 50% higher than the Xeon(R) but this one has 20 physical cores, making this frequency difference not sufficient to explain such performance gap." }, { "code": null, "e": 4358, "s": 4174, "text": "As Apple is never disclosing details of its processor’s designs, it’s difficult to know how the different parts of M1 are really used. Anyway, we can try to formulate some hypothesis." }, { "code": null, "e": 5196, "s": 4358, "text": "The M1 CPU includes “ML Accelerators” as mentioned here, they are used by ML Compute BNNS primitives when training Neural Networks models on CPU. If we refer to this article we can suppose “ML Accelerators” is the generic name for AMX2 (Apple Matrix Co-processor), so it’s maybe more something like a mini NPU capable to accelerate linear algebra computing and especially matrix multiplications. But unlike the Neural Engine it’s built to work with the CPU instead of being a standalone component, so reducing the latencies and improving the throughput for intensive matrix computing. This can explain why the maximum gap is observed on LSTM as this type of unit is not only vector based but require much more iterative processing. The combination of a CPU and a high throughput matrix computing unit seems very efficient for such models" }, { "code": null, "e": 5380, "s": 5196, "text": "The Universal Memory design enables a much faster data access for each core and every component of the SoC coupled with a better CPU design enabling more efficient parallel processing" }, { "code": null, "e": 5456, "s": 5380, "text": "Again, these are hypothesis and only Apple can explain how it really works." }, { "code": null, "e": 5490, "s": 5456, "text": "From these tests, it appears that" }, { "code": null, "e": 5583, "s": 5490, "text": "for training MLP and LSTM, M1 CPU is by far much faster than all the high-end servers tested" }, { "code": null, "e": 5661, "s": 5583, "text": "for training CNN, M1 is only slightly slower than the high-end servers tested" }, { "code": null, "e": 5775, "s": 5661, "text": "Of course, these metrics can only be considered for similar neural network types and depths as used in this test." }, { "code": null, "e": 6143, "s": 5775, "text": "For big trainings and intensive computing lasting for more than 20 minutes, I will still go for cloud-based solutions as they provide cards built for such long heavy load and enable sending several jobs simultaneously. But this scenario is only for some specific research representing only 10% of my work, mostly for professional usage in some specific business area." }, { "code": null, "e": 6281, "s": 6143, "text": "As a machine learning engineer, for my day-to-day personal research, M1 Mac is clearly the best and the most cost-efficient option today." } ]
MicroPython on ESP Using Jupyter Notebook | by Marcelo Rovai | Towards Data Science
Let’s play with MicroPython on an ESP using a Jupyter Notebook in order to get data from sensors and taking action in a physical world. On a previous article, we explored how to control a Raspberry Pi using Jupyter Notebook: Physical Computing Using Jupyter Notebook It was a great experience, and once the project worked very well I thought, “how about to also test Jupyter Notebook on an ESP8266 (or even on ESP32) using MicroPython?”. As we all know, the Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. For “much more”, we have also explored “Physical Computing”. So far on my projects, I have mostly explored IoT and physical computing projects using ESP8266–01, 8266–12E (NodeMCU) and ESP32 programmed by an Arduino IDE, using its C/C++ type language. But another great tool to be used on programming those devices is MicroPython: MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments. It aims to be as compatible with normal Python as possible to allow you to transfer code with ease from the desktop to a microcontroller or embedded system. Also, I think that using Jupyter Notebook to program an ESP device using MicroPython, can be a great tool to teach Physical Computing to kids and also help scientists to quickly access real-world playing with sensors on acquiring data. This is what we will try to accomplish in this tutorial: Outputting a digital signal to Turn On/Off a LED Reading a digital input from a button Output a PWM signal to fade a LED Controlling a Servo Motor position using a PWM output Reading Analog signal (Luminosity using LDR ) Reading Temperature vai 1-Wire (DS18B20) Reading Temperature and Humidity (DHT22) Displaying data using an OLED via I2C bus. The first thing to be done with a fresh NodeMCU (or ESP32), is to erase what is loaded in its memory, “flashing” a new firmware, that will be the MicroPython interpreter. A. Getting the new FW: Go to the site: MicroPython downloads and download the appropriated FW for your device: For example, for ESP8266, the latest version is: esp8266-20180511-v1.9.4.bin (Latest 01Jun18) (you can find details how to install the FW here) The ideal is to create a directory where you will work with MicroPython. For example, in case of a mac, starting from your root directory: cd Documentsmkdir MicroPythoncd MicroPython B. Move the downloaded ESP8266 firmware to this recently created directory. At this point: Connect the NodeMCU or ESP32 to your PC using the serial USB cable. C. Check where is the serial port that is being used by your device using the command: ls /dev/tty.* In my case, I got: /dev/tty.SLAB_USBtoUART D. Install esptool (tool used to flash/erase FW on devices) pip install esptool E. Erase the NodeMCU flash: esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash F. Flash the new FW: esptool.py --port /dev/tty.SLAB_USBtoUART --baud 460800 write_flash --flash_size=detect 0 esp8266-20180511-v1.9.4.bin Once you have the Firmware installed, you can play with REPL* on Terminal using the command "Screen": screen /dev/tty.SLAB_USBtoUART 115200>>> print (‘hello ESP8266’)>>> hello ESP8266 If you are at REPL, use: [Ctrl+C] to break a pgm and [Ctrl+A] [K] [Y] to quit and return to the terminal. * REPL stands for “Read Evaluate Print Loop”, and is the name given to the interactive MicroPython prompt that you can access on the ESP8266. You can learn more about REPL here. To interact with a MicroPython ESP8266 or ESP32 over its serial REPL, we will need to install a specific Jupyter Kernel. This is necessary to be done only once. From Jupyter Documentation website, we can list all “ Community-maintained kernels”. There, we will be sent to : Jupyter MicroPython Kernel Once we have Python 3 installed on our machine (in my case it is a Mac), clone the repository to a directory using the shell command (ie on a command line): git clone https://github.com/goatchurchprime/jupyter_micropython_kernel.git Next, install the library (in editable mode) into Python3 using the shell command: pip install -e jupyter_micropython_kernel This creates a small file pointing to this directory in the python/../site-packages directory and makes it possible to “git update” the library later as it gets improved. Things can go wrong here, and you might need “pip3” or “sudo pip” if you have numerous different versions of python installed. Install the kernel into Jupyter itself using the shell command: python -m jupyter_micropython_kernel.install This creates the small file “.local/share/jupyter/kernels/micropython/kernel.json” that jupyter uses to reference it’s kernels. To find out where your kernelspecs are stored, you can type: jupyter kernelspec list The Terminal PrintScreen show you the list of kernels that I have installed on my machine. Note that in my case I installed the MicroPython kernel using PIP3 command and so, the Kernel is not in the same directory that the other ones (I got an error when trying to install my kernel using PIP). Now run Jupyter notebooks: jupyter notebook In the notebook click the "New" Notebook button in the upper right, you should see the kernel display name listed: "MicroPython — USB". On the first cell, you will need to define the port and baud rate that will be used (115200 works fine): %serialconnect to --port=/dev/tty.SLAB_USBtoUART --baud=115200 As a response, the cell will return: Connecting to --port=/dev/tty.SLAB_USBtoUART --baud=115200Ready. And that’s it! When “Ready” appears, you should be able to execute MicroPython commands by running the cells. Let’s try: print ('hello esp8266') You should receive the response of your ESP8266 as on output on the cell: hello esp8266 As usual, let’s start our journey to Physical computing, “blinking a LED”. Below the typical pinout of NodeMCU (ESP8266–12E V1.0): The available pins are: 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, which correspond to the actual GPIO pin numbers of ESP8266 chip. Note that many end-user boards use their own adhoc pin numbering (marked e.g. D0, D1, ...). Install a LED on NodeMCU pin 0 (D3) and test it, turning it ON and OFF: # import library to deal with pins:from machine import Pin# define pin 0 as outputled = Pin(0, Pin.OUT)# define value of "led" as "1" or "True" to turn on the LEDled.value(1)# define value of "led" as "0" or "False" to turn off the LEDled.value(0)# also you can use .on() or .off methods to control the pin:led.on()led.off() Now, Let’s import a time library and blink the LED: from time import sleepfor i in range(5): led.on() sleep(0.5) led.off() sleep(0.5) The simple sensor data that you can read on a NodeMCU can be got with a push-button. Let’s install a push-button between pin 13 (D7) and GND as shown in the diagram. Our push-button will be connected in a way that pin 13 normal state will be “High” (so we will use an internal Pull-up resistor to guarantee this state). When pressed, pin 13 will be “Low”. # define pin 13 as an input and activate an internal Pull-up resistor:button = Pin(13, Pin.IN, Pin.PULL_UP)# Read button state:print(button.value()) When you run the above cell (w/o pressing the button), the result will be: 1 Pressing the button, run the cell again: # Read button state:print(button.value()) The result is now: 0 Note that stop pressing the button does not return the “cell value” to “1”. To see “1”, you must run the cell again. Let’s now do a small program to turn ON the LED only if the button is pressed: print (button.value())if button.value() == 0: led.on()else: led.off() PWM can be enabled on all pins except Pin(16). There is a single frequency for all channels, with a range between 1 and 1000 (measured in Hz). The duty cycle is between 0 and 1023 inclusive. Start calling the appropriate library: from machine import Pin, PWM several commands are available: pwm0 = PWM(Pin(0)) # create PWM object from a pinpwm0.freq() # get current frequencypwm0.freq(1000) # set frequencypwm0.duty() # get current duty cyclepwm0.duty(200) # set duty cyclepwm0.deinit() # turn off PWM on the pin Or you can set configure the pin at once: pwm2 = PWM(Pin(2), freq=500, duty=512) Let’s dimming the LED connected to Pin 0 from OFF to ON: from machine import Pin, PWMpwm0 = PWM(Pin(0), freq=1000, duty=0)for i in range (0,1023,20): pwm0.duty(i) sleep(0.1) pwm0.duty(0) pwm0.deinit() And how about to control a Servo Motor? Let’s install a small hobby servo on our NodeMCU as shown in the diagram. Note that I am connecting the Servo VCC to NodeMCU +3.3V. This is OK for this tutorial, but on real projects, you must connect the Servo VCC to an external +5V Power supply (do not forget to connect the GNDs to NodeMCU GND). The servo data pin will be connected to NodeMCU pin 14 (D5). Servos usually work with frequency of 50Hz and then a duty cycle between about 40 and 115 will position them from 0 to 180 degrees respectively. A duty cycle of 77 will position the servo on its center value (90 degrees). servo = PWM(Pin(14), freq=50) Test the servo on different positions: # Minimum position (angle 0)servo.duty(40)# Maximun position (angle 180)servo.duty(40)# center position (angle 90)servo.duty(40) You can also create a simple swapping program to test your servo: # swipping servostep = 2for i in range (40, 115, step): servo.duty(i) sleep (0.1) step = -1*stepfor i in range (115, 40, step): servo.duty(i) sleep (0.1) servo.duty(77) Below the result: I am not using the sonar here, so I will leave to you to develop a code to use it. It’s simple alheady! Try it! The ESP8266 has a single pin A0 which can be used to read analog voltages and convert them to a digital value. You can construct such an ADC pin object using: from machine import ADCadc = ADC(0) Next, you can read the value of A0 pin using: adc.read() The Analog pin could be used to read, for example, a variable value got from a potentiometer as a voltage divider. This can be translated as an output for dimming the LED or move the servo to a specific position. You can try it based on what we have learned so far. Another useful example is to capture data from an analog sensor, as temperature (LM35), ultraviolet (UV) radiation or luminosity using an LDR (“Light Dependent Resistor). An LDR decreases its resistance when the luminosity increase. So, you can create a voltage divider with an LDR and a resistor as shown in the diagram. Reading the analog voltage directly over the resistor, we will get a signal directly proportional to luminosity. Leave the sensor exposed to light and read the ADC value. Now, cover the sensor and get a lower value. In my case: Maximum Light ==> adc value > 850 Minimun Light ==> adc value < 40 The 1-wire bus is a serial bus that uses just a single wire for communication (in addition to wires for ground and power). The DS18B20 temperature sensor is a very popular 1-wire device, and here we show how to use the "onewire" module to read from such a device. For the following code to work you need to have at least one DS18B20 temperature sensor with its data line connected to GPIO 2 (D4). You must also power the sensors and connect a 4.7k Ohm resistor between the data pin and the power pin as shown in the diagram. Import the libraries: import onewire, ds18x20 Define which pin the 1-wire device will be connected. In our case ==> pin 2 (D4) dat = Pin(2) Create the onewire object: ds = ds18x20.DS18X20(onewire.OneWire(dat)) Scan for devices on the bus. Remember that you can have multiple devices connected at same bus. sensors = ds.scan()print('found devices:', sensors) “sensors” is an array with the address of all 1-wire sensors connected. We will use "sensors[0]” to point to our sensor. Note that you must execute the convert_temp() function to initiate a temperature reading, then wait at least 750ms before reading the value (do not forget to import time library). To read the value use: ds.read_temp(sensors[0]): ds.convert_temp()time.sleep_ms(750)print(ds.read_temp(sensors[0])) DHT (Digital Humidity & Temperature) sensors are low-cost digital sensors with capacitive humidity sensors and thermistors to measure the surrounding air. They feature a chip that handles analog to digital conversion and provides a digital interface using only a single data wire. Newer sensors additionally provide an I2C interface. The DHT11 (blue) and DHT22 (white) sensors provide the same digital interface, however, the DHT22 requires a separate object as it has a more complex calculation. DHT22 have 1 decimal place resolution for both humidity and temperature readings. DHT11 have whole number for both. A custom protocol is used to get the measurements from the sensor. The payload consists of a humidity value, a temperature value, and a checksum. Connect the DHT22 as shown in the diagram. The data pin will be connected to NodeMCU pin 12 (D6). To use the DHT interface, construct the objects referring to their data pin. Start calling the library: from dht import DHT22 Define the appropriated pin and construct the object: data = DHT22(Pin(12)) Get the Temperature and Humidity values: data.measure()temp = data.temperature()hum = data.humidity()print('Temp: {}oC'.format(temp))print('Hum: {}%'.format(hum)) The DHT11 can be called no more than once per second and the DHT22 once every two seconds for most accurate results. Sensor accuracy will degrade over time. Each sensor supports a different operating range. Refer to the product datasheets for specifics. DHT22 sensors are now sold under the name AM2302 and are otherwise identical. I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires: SCL and SDA, the clock and data lines respectively. I2C objects are created attached to a specific bus. They can be initialized when created or initialized later on. First, let’s import the library: from machine import I2C Considering a device on Pin 4 (SDA) and Pin 5 (SCL), let’s create an i2c object: i2c = I2C(scl=Pin(5), sda=Pin(4)) Now, you should scan the I2C bus for eventual devices there. The function below will do this, returning the number of connected devices and its address: def scanI2c(): print('Scan i2c bus...') devices = i2c.scan() if len(devices) == 0: print("No i2c device !") else: print('i2c devices found:',len(devices)) for device in devices: print("Decimal address: ",device," | Hexa address: ",hex(device)) Let’s install an I2C OLED display on our NodeMCU as shown in the diagram. The display is the SSD 1306 (128 x 64). Running the scan function: scanI2c() We will get as a result that 1device was found at address 0x3c. This address will be used for an oled object creation as below: import ssd1306i2c = I2C(scl=Pin(5), sda=Pin(4))oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c) Some methods to manage the display: poweroff(), turns off the screen. Convenient for battery operation.contrast(), to adjust the contrastinvert(), invert the colors of the screen (finally white and black!)show(), to refresh the viewfill(), to fill the screen in black (1) or white (0)pixel(), to turn on a particular pixelscroll(), scroll the screen.text(), to display on text at the indicated x, y positionDraw lines hline(), vline() or any line line()Draw a rect rect rectangle() or rectangle filled fill_rect() Let’s test our display: oled.fill(0)oled.text("Hello esp8266", 0, 0)oled.show() And now, let’s display the DHT22 sensor data on put OLED: data.measure()temp = data.temperature()hum = data.humidity()oled.fill(0)oled.text("Temp: " + str(temp) + "oC", 0, 0)oled.text("Hum: " + str(hum) + "%",0, 16)oled.show() This article deliveres the bits and pieces for you to build a more robust project, using MicroPython as a programming language and Jupyter Notebook as a tool for quick development and analysis. Of course, if you want to run a program written in MicroPython on a NodeMCU independent of your PC and Jupyter, you must save your code as a “main.py” file for example, in any text editor and download it on your device using: “ Ampy”, that is a utility developed by Adafruit, to interact with a MicroPython board over a serial connection. Ampy is meant to be a simple command line tool to manipulate files and run code on a MicroPython board over its serial connection. With ampy you can send files from your computer to a MicroPython board’s file system, download files from a board to your computer, and even send a Python script to a board to be executed. Installation: sudo pip3 install adafruit-ampy Ampy is made to talk to a MicroPython board over its serial connection. You will need your board connected and any drivers to access it serial port installed. Then, for example, to list the files on the board run a command like: ampy --port /dev/tty.SLAB_USBtoUART ls For convenience, you can set an AMPY_PORT environment variable which will be used if the port parameter is not specified. For example on Linux or OSX: export AMPY_PORT=/dev/tty.SLAB_USBtoUART So, from now one, you can simplify commands: List internal NodeMCU files: ampy ls You can read a file installed on your nodeMCU using: ampy get boot.py Once you create a file using your text editor (nano for example), you can install it on your NodeMCU using: ampy put main.py Now, when you press “Reset” button on your NodeMcu, the program that will run first is “main.py”. For Windows, please see the Adafruit instructions here. As always, I hope this project can help others find their way into the exciting world of electronics! For details and final code, please visit my GitHub depository: Pyhon4DS/Micropython For more projects, please visit my blog: MJRoBot.org Saludos from the south of the world! See you in my next article! Thank you, Marcelo No rights reserved by the author.
[ { "code": null, "e": 307, "s": 171, "text": "Let’s play with MicroPython on an ESP using a Jupyter Notebook in order to get data from sensors and taking action in a physical world." }, { "code": null, "e": 438, "s": 307, "text": "On a previous article, we explored how to control a Raspberry Pi using Jupyter Notebook: Physical Computing Using Jupyter Notebook" }, { "code": null, "e": 609, "s": 438, "text": "It was a great experience, and once the project worked very well I thought, “how about to also test Jupyter Notebook on an ESP8266 (or even on ESP32) using MicroPython?”." }, { "code": null, "e": 1001, "s": 609, "text": "As we all know, the Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text. Uses include data cleaning and transformation, numerical simulation, statistical modeling, data visualization, machine learning, and much more. For “much more”, we have also explored “Physical Computing”." }, { "code": null, "e": 1270, "s": 1001, "text": "So far on my projects, I have mostly explored IoT and physical computing projects using ESP8266–01, 8266–12E (NodeMCU) and ESP32 programmed by an Arduino IDE, using its C/C++ type language. But another great tool to be used on programming those devices is MicroPython:" }, { "code": null, "e": 1652, "s": 1270, "text": "MicroPython is a lean and efficient implementation of the Python 3 programming language that includes a small subset of the Python standard library and is optimised to run on microcontrollers and in constrained environments. It aims to be as compatible with normal Python as possible to allow you to transfer code with ease from the desktop to a microcontroller or embedded system." }, { "code": null, "e": 1888, "s": 1652, "text": "Also, I think that using Jupyter Notebook to program an ESP device using MicroPython, can be a great tool to teach Physical Computing to kids and also help scientists to quickly access real-world playing with sensors on acquiring data." }, { "code": null, "e": 1945, "s": 1888, "text": "This is what we will try to accomplish in this tutorial:" }, { "code": null, "e": 1994, "s": 1945, "text": "Outputting a digital signal to Turn On/Off a LED" }, { "code": null, "e": 2032, "s": 1994, "text": "Reading a digital input from a button" }, { "code": null, "e": 2066, "s": 2032, "text": "Output a PWM signal to fade a LED" }, { "code": null, "e": 2120, "s": 2066, "text": "Controlling a Servo Motor position using a PWM output" }, { "code": null, "e": 2166, "s": 2120, "text": "Reading Analog signal (Luminosity using LDR )" }, { "code": null, "e": 2207, "s": 2166, "text": "Reading Temperature vai 1-Wire (DS18B20)" }, { "code": null, "e": 2248, "s": 2207, "text": "Reading Temperature and Humidity (DHT22)" }, { "code": null, "e": 2291, "s": 2248, "text": "Displaying data using an OLED via I2C bus." }, { "code": null, "e": 2462, "s": 2291, "text": "The first thing to be done with a fresh NodeMCU (or ESP32), is to erase what is loaded in its memory, “flashing” a new firmware, that will be the MicroPython interpreter." }, { "code": null, "e": 2485, "s": 2462, "text": "A. Getting the new FW:" }, { "code": null, "e": 2573, "s": 2485, "text": "Go to the site: MicroPython downloads and download the appropriated FW for your device:" }, { "code": null, "e": 2622, "s": 2573, "text": "For example, for ESP8266, the latest version is:" }, { "code": null, "e": 2667, "s": 2622, "text": "esp8266-20180511-v1.9.4.bin (Latest 01Jun18)" }, { "code": null, "e": 2717, "s": 2667, "text": "(you can find details how to install the FW here)" }, { "code": null, "e": 2856, "s": 2717, "text": "The ideal is to create a directory where you will work with MicroPython. For example, in case of a mac, starting from your root directory:" }, { "code": null, "e": 2900, "s": 2856, "text": "cd Documentsmkdir MicroPythoncd MicroPython" }, { "code": null, "e": 2976, "s": 2900, "text": "B. Move the downloaded ESP8266 firmware to this recently created directory." }, { "code": null, "e": 3059, "s": 2976, "text": "At this point: Connect the NodeMCU or ESP32 to your PC using the serial USB cable." }, { "code": null, "e": 3146, "s": 3059, "text": "C. Check where is the serial port that is being used by your device using the command:" }, { "code": null, "e": 3160, "s": 3146, "text": "ls /dev/tty.*" }, { "code": null, "e": 3179, "s": 3160, "text": "In my case, I got:" }, { "code": null, "e": 3203, "s": 3179, "text": "/dev/tty.SLAB_USBtoUART" }, { "code": null, "e": 3263, "s": 3203, "text": "D. Install esptool (tool used to flash/erase FW on devices)" }, { "code": null, "e": 3283, "s": 3263, "text": "pip install esptool" }, { "code": null, "e": 3311, "s": 3283, "text": "E. Erase the NodeMCU flash:" }, { "code": null, "e": 3365, "s": 3311, "text": "esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash" }, { "code": null, "e": 3386, "s": 3365, "text": "F. Flash the new FW:" }, { "code": null, "e": 3504, "s": 3386, "text": "esptool.py --port /dev/tty.SLAB_USBtoUART --baud 460800 write_flash --flash_size=detect 0 esp8266-20180511-v1.9.4.bin" }, { "code": null, "e": 3606, "s": 3504, "text": "Once you have the Firmware installed, you can play with REPL* on Terminal using the command \"Screen\":" }, { "code": null, "e": 3689, "s": 3606, "text": "screen /dev/tty.SLAB_USBtoUART 115200>>> print (‘hello ESP8266’)>>> hello ESP8266" }, { "code": null, "e": 3714, "s": 3689, "text": "If you are at REPL, use:" }, { "code": null, "e": 3742, "s": 3714, "text": "[Ctrl+C] to break a pgm and" }, { "code": null, "e": 3795, "s": 3742, "text": "[Ctrl+A] [K] [Y] to quit and return to the terminal." }, { "code": null, "e": 3973, "s": 3795, "text": "* REPL stands for “Read Evaluate Print Loop”, and is the name given to the interactive MicroPython prompt that you can access on the ESP8266. You can learn more about REPL here." }, { "code": null, "e": 4094, "s": 3973, "text": "To interact with a MicroPython ESP8266 or ESP32 over its serial REPL, we will need to install a specific Jupyter Kernel." }, { "code": null, "e": 4134, "s": 4094, "text": "This is necessary to be done only once." }, { "code": null, "e": 4247, "s": 4134, "text": "From Jupyter Documentation website, we can list all “ Community-maintained kernels”. There, we will be sent to :" }, { "code": null, "e": 4274, "s": 4247, "text": "Jupyter MicroPython Kernel" }, { "code": null, "e": 4431, "s": 4274, "text": "Once we have Python 3 installed on our machine (in my case it is a Mac), clone the repository to a directory using the shell command (ie on a command line):" }, { "code": null, "e": 4507, "s": 4431, "text": "git clone https://github.com/goatchurchprime/jupyter_micropython_kernel.git" }, { "code": null, "e": 4590, "s": 4507, "text": "Next, install the library (in editable mode) into Python3 using the shell command:" }, { "code": null, "e": 4632, "s": 4590, "text": "pip install -e jupyter_micropython_kernel" }, { "code": null, "e": 4803, "s": 4632, "text": "This creates a small file pointing to this directory in the python/../site-packages directory and makes it possible to “git update” the library later as it gets improved." }, { "code": null, "e": 4930, "s": 4803, "text": "Things can go wrong here, and you might need “pip3” or “sudo pip” if you have numerous different versions of python installed." }, { "code": null, "e": 4994, "s": 4930, "text": "Install the kernel into Jupyter itself using the shell command:" }, { "code": null, "e": 5039, "s": 4994, "text": "python -m jupyter_micropython_kernel.install" }, { "code": null, "e": 5167, "s": 5039, "text": "This creates the small file “.local/share/jupyter/kernels/micropython/kernel.json” that jupyter uses to reference it’s kernels." }, { "code": null, "e": 5228, "s": 5167, "text": "To find out where your kernelspecs are stored, you can type:" }, { "code": null, "e": 5252, "s": 5228, "text": "jupyter kernelspec list" }, { "code": null, "e": 5547, "s": 5252, "text": "The Terminal PrintScreen show you the list of kernels that I have installed on my machine. Note that in my case I installed the MicroPython kernel using PIP3 command and so, the Kernel is not in the same directory that the other ones (I got an error when trying to install my kernel using PIP)." }, { "code": null, "e": 5574, "s": 5547, "text": "Now run Jupyter notebooks:" }, { "code": null, "e": 5591, "s": 5574, "text": "jupyter notebook" }, { "code": null, "e": 5727, "s": 5591, "text": "In the notebook click the \"New\" Notebook button in the upper right, you should see the kernel display name listed: \"MicroPython — USB\"." }, { "code": null, "e": 5832, "s": 5727, "text": "On the first cell, you will need to define the port and baud rate that will be used (115200 works fine):" }, { "code": null, "e": 5895, "s": 5832, "text": "%serialconnect to --port=/dev/tty.SLAB_USBtoUART --baud=115200" }, { "code": null, "e": 5932, "s": 5895, "text": "As a response, the cell will return:" }, { "code": null, "e": 5997, "s": 5932, "text": "Connecting to --port=/dev/tty.SLAB_USBtoUART --baud=115200Ready." }, { "code": null, "e": 6107, "s": 5997, "text": "And that’s it! When “Ready” appears, you should be able to execute MicroPython commands by running the cells." }, { "code": null, "e": 6118, "s": 6107, "text": "Let’s try:" }, { "code": null, "e": 6142, "s": 6118, "text": "print ('hello esp8266')" }, { "code": null, "e": 6216, "s": 6142, "text": "You should receive the response of your ESP8266 as on output on the cell:" }, { "code": null, "e": 6230, "s": 6216, "text": "hello esp8266" }, { "code": null, "e": 6305, "s": 6230, "text": "As usual, let’s start our journey to Physical computing, “blinking a LED”." }, { "code": null, "e": 6361, "s": 6305, "text": "Below the typical pinout of NodeMCU (ESP8266–12E V1.0):" }, { "code": null, "e": 6580, "s": 6361, "text": "The available pins are: 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, which correspond to the actual GPIO pin numbers of ESP8266 chip. Note that many end-user boards use their own adhoc pin numbering (marked e.g. D0, D1, ...)." }, { "code": null, "e": 6652, "s": 6580, "text": "Install a LED on NodeMCU pin 0 (D3) and test it, turning it ON and OFF:" }, { "code": null, "e": 6977, "s": 6652, "text": "# import library to deal with pins:from machine import Pin# define pin 0 as outputled = Pin(0, Pin.OUT)# define value of \"led\" as \"1\" or \"True\" to turn on the LEDled.value(1)# define value of \"led\" as \"0\" or \"False\" to turn off the LEDled.value(0)# also you can use .on() or .off methods to control the pin:led.on()led.off()" }, { "code": null, "e": 7029, "s": 6977, "text": "Now, Let’s import a time library and blink the LED:" }, { "code": null, "e": 7123, "s": 7029, "text": "from time import sleepfor i in range(5): led.on() sleep(0.5) led.off() sleep(0.5)" }, { "code": null, "e": 7208, "s": 7123, "text": "The simple sensor data that you can read on a NodeMCU can be got with a push-button." }, { "code": null, "e": 7289, "s": 7208, "text": "Let’s install a push-button between pin 13 (D7) and GND as shown in the diagram." }, { "code": null, "e": 7479, "s": 7289, "text": "Our push-button will be connected in a way that pin 13 normal state will be “High” (so we will use an internal Pull-up resistor to guarantee this state). When pressed, pin 13 will be “Low”." }, { "code": null, "e": 7628, "s": 7479, "text": "# define pin 13 as an input and activate an internal Pull-up resistor:button = Pin(13, Pin.IN, Pin.PULL_UP)# Read button state:print(button.value())" }, { "code": null, "e": 7703, "s": 7628, "text": "When you run the above cell (w/o pressing the button), the result will be:" }, { "code": null, "e": 7705, "s": 7703, "text": "1" }, { "code": null, "e": 7746, "s": 7705, "text": "Pressing the button, run the cell again:" }, { "code": null, "e": 7788, "s": 7746, "text": "# Read button state:print(button.value())" }, { "code": null, "e": 7807, "s": 7788, "text": "The result is now:" }, { "code": null, "e": 7809, "s": 7807, "text": "0" }, { "code": null, "e": 7926, "s": 7809, "text": "Note that stop pressing the button does not return the “cell value” to “1”. To see “1”, you must run the cell again." }, { "code": null, "e": 8005, "s": 7926, "text": "Let’s now do a small program to turn ON the LED only if the button is pressed:" }, { "code": null, "e": 8081, "s": 8005, "text": "print (button.value())if button.value() == 0: led.on()else: led.off()" }, { "code": null, "e": 8272, "s": 8081, "text": "PWM can be enabled on all pins except Pin(16). There is a single frequency for all channels, with a range between 1 and 1000 (measured in Hz). The duty cycle is between 0 and 1023 inclusive." }, { "code": null, "e": 8311, "s": 8272, "text": "Start calling the appropriate library:" }, { "code": null, "e": 8340, "s": 8311, "text": "from machine import Pin, PWM" }, { "code": null, "e": 8372, "s": 8340, "text": "several commands are available:" }, { "code": null, "e": 8650, "s": 8372, "text": "pwm0 = PWM(Pin(0)) # create PWM object from a pinpwm0.freq() # get current frequencypwm0.freq(1000) # set frequencypwm0.duty() # get current duty cyclepwm0.duty(200) # set duty cyclepwm0.deinit() # turn off PWM on the pin" }, { "code": null, "e": 8692, "s": 8650, "text": "Or you can set configure the pin at once:" }, { "code": null, "e": 8731, "s": 8692, "text": "pwm2 = PWM(Pin(2), freq=500, duty=512)" }, { "code": null, "e": 8788, "s": 8731, "text": "Let’s dimming the LED connected to Pin 0 from OFF to ON:" }, { "code": null, "e": 8944, "s": 8788, "text": "from machine import Pin, PWMpwm0 = PWM(Pin(0), freq=1000, duty=0)for i in range (0,1023,20): pwm0.duty(i) sleep(0.1) pwm0.duty(0) pwm0.deinit()" }, { "code": null, "e": 8984, "s": 8944, "text": "And how about to control a Servo Motor?" }, { "code": null, "e": 9283, "s": 8984, "text": "Let’s install a small hobby servo on our NodeMCU as shown in the diagram. Note that I am connecting the Servo VCC to NodeMCU +3.3V. This is OK for this tutorial, but on real projects, you must connect the Servo VCC to an external +5V Power supply (do not forget to connect the GNDs to NodeMCU GND)." }, { "code": null, "e": 9344, "s": 9283, "text": "The servo data pin will be connected to NodeMCU pin 14 (D5)." }, { "code": null, "e": 9566, "s": 9344, "text": "Servos usually work with frequency of 50Hz and then a duty cycle between about 40 and 115 will position them from 0 to 180 degrees respectively. A duty cycle of 77 will position the servo on its center value (90 degrees)." }, { "code": null, "e": 9596, "s": 9566, "text": "servo = PWM(Pin(14), freq=50)" }, { "code": null, "e": 9635, "s": 9596, "text": "Test the servo on different positions:" }, { "code": null, "e": 9764, "s": 9635, "text": "# Minimum position (angle 0)servo.duty(40)# Maximun position (angle 180)servo.duty(40)# center position (angle 90)servo.duty(40)" }, { "code": null, "e": 9830, "s": 9764, "text": "You can also create a simple swapping program to test your servo:" }, { "code": null, "e": 10017, "s": 9830, "text": "# swipping servostep = 2for i in range (40, 115, step): servo.duty(i) sleep (0.1) step = -1*stepfor i in range (115, 40, step): servo.duty(i) sleep (0.1) servo.duty(77)" }, { "code": null, "e": 10035, "s": 10017, "text": "Below the result:" }, { "code": null, "e": 10147, "s": 10035, "text": "I am not using the sonar here, so I will leave to you to develop a code to use it. It’s simple alheady! Try it!" }, { "code": null, "e": 10306, "s": 10147, "text": "The ESP8266 has a single pin A0 which can be used to read analog voltages and convert them to a digital value. You can construct such an ADC pin object using:" }, { "code": null, "e": 10342, "s": 10306, "text": "from machine import ADCadc = ADC(0)" }, { "code": null, "e": 10388, "s": 10342, "text": "Next, you can read the value of A0 pin using:" }, { "code": null, "e": 10399, "s": 10388, "text": "adc.read()" }, { "code": null, "e": 10665, "s": 10399, "text": "The Analog pin could be used to read, for example, a variable value got from a potentiometer as a voltage divider. This can be translated as an output for dimming the LED or move the servo to a specific position. You can try it based on what we have learned so far." }, { "code": null, "e": 10836, "s": 10665, "text": "Another useful example is to capture data from an analog sensor, as temperature (LM35), ultraviolet (UV) radiation or luminosity using an LDR (“Light Dependent Resistor)." }, { "code": null, "e": 10987, "s": 10836, "text": "An LDR decreases its resistance when the luminosity increase. So, you can create a voltage divider with an LDR and a resistor as shown in the diagram." }, { "code": null, "e": 11100, "s": 10987, "text": "Reading the analog voltage directly over the resistor, we will get a signal directly proportional to luminosity." }, { "code": null, "e": 11158, "s": 11100, "text": "Leave the sensor exposed to light and read the ADC value." }, { "code": null, "e": 11203, "s": 11158, "text": "Now, cover the sensor and get a lower value." }, { "code": null, "e": 11215, "s": 11203, "text": "In my case:" }, { "code": null, "e": 11249, "s": 11215, "text": "Maximum Light ==> adc value > 850" }, { "code": null, "e": 11282, "s": 11249, "text": "Minimun Light ==> adc value < 40" }, { "code": null, "e": 11546, "s": 11282, "text": "The 1-wire bus is a serial bus that uses just a single wire for communication (in addition to wires for ground and power). The DS18B20 temperature sensor is a very popular 1-wire device, and here we show how to use the \"onewire\" module to read from such a device." }, { "code": null, "e": 11679, "s": 11546, "text": "For the following code to work you need to have at least one DS18B20 temperature sensor with its data line connected to GPIO 2 (D4)." }, { "code": null, "e": 11807, "s": 11679, "text": "You must also power the sensors and connect a 4.7k Ohm resistor between the data pin and the power pin as shown in the diagram." }, { "code": null, "e": 11829, "s": 11807, "text": "Import the libraries:" }, { "code": null, "e": 11853, "s": 11829, "text": "import onewire, ds18x20" }, { "code": null, "e": 11934, "s": 11853, "text": "Define which pin the 1-wire device will be connected. In our case ==> pin 2 (D4)" }, { "code": null, "e": 11947, "s": 11934, "text": "dat = Pin(2)" }, { "code": null, "e": 11974, "s": 11947, "text": "Create the onewire object:" }, { "code": null, "e": 12017, "s": 11974, "text": "ds = ds18x20.DS18X20(onewire.OneWire(dat))" }, { "code": null, "e": 12113, "s": 12017, "text": "Scan for devices on the bus. Remember that you can have multiple devices connected at same bus." }, { "code": null, "e": 12165, "s": 12113, "text": "sensors = ds.scan()print('found devices:', sensors)" }, { "code": null, "e": 12286, "s": 12165, "text": "“sensors” is an array with the address of all 1-wire sensors connected. We will use \"sensors[0]” to point to our sensor." }, { "code": null, "e": 12515, "s": 12286, "text": "Note that you must execute the convert_temp() function to initiate a temperature reading, then wait at least 750ms before reading the value (do not forget to import time library). To read the value use: ds.read_temp(sensors[0]):" }, { "code": null, "e": 12582, "s": 12515, "text": "ds.convert_temp()time.sleep_ms(750)print(ds.read_temp(sensors[0]))" }, { "code": null, "e": 12916, "s": 12582, "text": "DHT (Digital Humidity & Temperature) sensors are low-cost digital sensors with capacitive humidity sensors and thermistors to measure the surrounding air. They feature a chip that handles analog to digital conversion and provides a digital interface using only a single data wire. Newer sensors additionally provide an I2C interface." }, { "code": null, "e": 13341, "s": 12916, "text": "The DHT11 (blue) and DHT22 (white) sensors provide the same digital interface, however, the DHT22 requires a separate object as it has a more complex calculation. DHT22 have 1 decimal place resolution for both humidity and temperature readings. DHT11 have whole number for both. A custom protocol is used to get the measurements from the sensor. The payload consists of a humidity value, a temperature value, and a checksum." }, { "code": null, "e": 13439, "s": 13341, "text": "Connect the DHT22 as shown in the diagram. The data pin will be connected to NodeMCU pin 12 (D6)." }, { "code": null, "e": 13543, "s": 13439, "text": "To use the DHT interface, construct the objects referring to their data pin. Start calling the library:" }, { "code": null, "e": 13565, "s": 13543, "text": "from dht import DHT22" }, { "code": null, "e": 13619, "s": 13565, "text": "Define the appropriated pin and construct the object:" }, { "code": null, "e": 13641, "s": 13619, "text": "data = DHT22(Pin(12))" }, { "code": null, "e": 13682, "s": 13641, "text": "Get the Temperature and Humidity values:" }, { "code": null, "e": 13805, "s": 13682, "text": "data.measure()temp = data.temperature()hum = data.humidity()print('Temp: {}oC'.format(temp))print('Hum: {}%'.format(hum))" }, { "code": null, "e": 14059, "s": 13805, "text": "The DHT11 can be called no more than once per second and the DHT22 once every two seconds for most accurate results. Sensor accuracy will degrade over time. Each sensor supports a different operating range. Refer to the product datasheets for specifics." }, { "code": null, "e": 14137, "s": 14059, "text": "DHT22 sensors are now sold under the name AM2302 and are otherwise identical." }, { "code": null, "e": 14245, "s": 14137, "text": "I2C is a two-wire protocol for communicating between devices. At the physical level it consists of 2 wires:" }, { "code": null, "e": 14297, "s": 14245, "text": "SCL and SDA, the clock and data lines respectively." }, { "code": null, "e": 14411, "s": 14297, "text": "I2C objects are created attached to a specific bus. They can be initialized when created or initialized later on." }, { "code": null, "e": 14444, "s": 14411, "text": "First, let’s import the library:" }, { "code": null, "e": 14468, "s": 14444, "text": "from machine import I2C" }, { "code": null, "e": 14549, "s": 14468, "text": "Considering a device on Pin 4 (SDA) and Pin 5 (SCL), let’s create an i2c object:" }, { "code": null, "e": 14583, "s": 14549, "text": "i2c = I2C(scl=Pin(5), sda=Pin(4))" }, { "code": null, "e": 14736, "s": 14583, "text": "Now, you should scan the I2C bus for eventual devices there. The function below will do this, returning the number of connected devices and its address:" }, { "code": null, "e": 15016, "s": 14736, "text": "def scanI2c(): print('Scan i2c bus...') devices = i2c.scan() if len(devices) == 0: print(\"No i2c device !\") else: print('i2c devices found:',len(devices)) for device in devices: print(\"Decimal address: \",device,\" | Hexa address: \",hex(device))" }, { "code": null, "e": 15130, "s": 15016, "text": "Let’s install an I2C OLED display on our NodeMCU as shown in the diagram. The display is the SSD 1306 (128 x 64)." }, { "code": null, "e": 15157, "s": 15130, "text": "Running the scan function:" }, { "code": null, "e": 15167, "s": 15157, "text": "scanI2c()" }, { "code": null, "e": 15231, "s": 15167, "text": "We will get as a result that 1device was found at address 0x3c." }, { "code": null, "e": 15295, "s": 15231, "text": "This address will be used for an oled object creation as below:" }, { "code": null, "e": 15389, "s": 15295, "text": "import ssd1306i2c = I2C(scl=Pin(5), sda=Pin(4))oled = ssd1306.SSD1306_I2C(128, 64, i2c, 0x3c)" }, { "code": null, "e": 15425, "s": 15389, "text": "Some methods to manage the display:" }, { "code": null, "e": 15903, "s": 15425, "text": "poweroff(), turns off the screen. Convenient for battery operation.contrast(), to adjust the contrastinvert(), invert the colors of the screen (finally white and black!)show(), to refresh the viewfill(), to fill the screen in black (1) or white (0)pixel(), to turn on a particular pixelscroll(), scroll the screen.text(), to display on text at the indicated x, y positionDraw lines hline(), vline() or any line line()Draw a rect rect rectangle() or rectangle filled fill_rect()" }, { "code": null, "e": 15927, "s": 15903, "text": "Let’s test our display:" }, { "code": null, "e": 15983, "s": 15927, "text": "oled.fill(0)oled.text(\"Hello esp8266\", 0, 0)oled.show()" }, { "code": null, "e": 16041, "s": 15983, "text": "And now, let’s display the DHT22 sensor data on put OLED:" }, { "code": null, "e": 16213, "s": 16041, "text": "data.measure()temp = data.temperature()hum = data.humidity()oled.fill(0)oled.text(\"Temp: \" + str(temp) + \"oC\", 0, 0)oled.text(\"Hum: \" + str(hum) + \"%\",0, 16)oled.show()" }, { "code": null, "e": 16407, "s": 16213, "text": "This article deliveres the bits and pieces for you to build a more robust project, using MicroPython as a programming language and Jupyter Notebook as a tool for quick development and analysis." }, { "code": null, "e": 16746, "s": 16407, "text": "Of course, if you want to run a program written in MicroPython on a NodeMCU independent of your PC and Jupyter, you must save your code as a “main.py” file for example, in any text editor and download it on your device using: “ Ampy”, that is a utility developed by Adafruit, to interact with a MicroPython board over a serial connection." }, { "code": null, "e": 17066, "s": 16746, "text": "Ampy is meant to be a simple command line tool to manipulate files and run code on a MicroPython board over its serial connection. With ampy you can send files from your computer to a MicroPython board’s file system, download files from a board to your computer, and even send a Python script to a board to be executed." }, { "code": null, "e": 17080, "s": 17066, "text": "Installation:" }, { "code": null, "e": 17112, "s": 17080, "text": "sudo pip3 install adafruit-ampy" }, { "code": null, "e": 17341, "s": 17112, "text": "Ampy is made to talk to a MicroPython board over its serial connection. You will need your board connected and any drivers to access it serial port installed. Then, for example, to list the files on the board run a command like:" }, { "code": null, "e": 17380, "s": 17341, "text": "ampy --port /dev/tty.SLAB_USBtoUART ls" }, { "code": null, "e": 17531, "s": 17380, "text": "For convenience, you can set an AMPY_PORT environment variable which will be used if the port parameter is not specified. For example on Linux or OSX:" }, { "code": null, "e": 17572, "s": 17531, "text": "export AMPY_PORT=/dev/tty.SLAB_USBtoUART" }, { "code": null, "e": 17617, "s": 17572, "text": "So, from now one, you can simplify commands:" }, { "code": null, "e": 17646, "s": 17617, "text": "List internal NodeMCU files:" }, { "code": null, "e": 17654, "s": 17646, "text": "ampy ls" }, { "code": null, "e": 17707, "s": 17654, "text": "You can read a file installed on your nodeMCU using:" }, { "code": null, "e": 17724, "s": 17707, "text": "ampy get boot.py" }, { "code": null, "e": 17832, "s": 17724, "text": "Once you create a file using your text editor (nano for example), you can install it on your NodeMCU using:" }, { "code": null, "e": 17849, "s": 17832, "text": "ampy put main.py" }, { "code": null, "e": 17947, "s": 17849, "text": "Now, when you press “Reset” button on your NodeMcu, the program that will run first is “main.py”." }, { "code": null, "e": 18003, "s": 17947, "text": "For Windows, please see the Adafruit instructions here." }, { "code": null, "e": 18105, "s": 18003, "text": "As always, I hope this project can help others find their way into the exciting world of electronics!" }, { "code": null, "e": 18189, "s": 18105, "text": "For details and final code, please visit my GitHub depository: Pyhon4DS/Micropython" }, { "code": null, "e": 18242, "s": 18189, "text": "For more projects, please visit my blog: MJRoBot.org" }, { "code": null, "e": 18279, "s": 18242, "text": "Saludos from the south of the world!" }, { "code": null, "e": 18307, "s": 18279, "text": "See you in my next article!" }, { "code": null, "e": 18318, "s": 18307, "text": "Thank you," }, { "code": null, "e": 18326, "s": 18318, "text": "Marcelo" }, { "code": null, "e": 18345, "s": 18326, "text": "No rights reserved" } ]
\mbox - Tex Command
\mbox - creates a box just wide enough to hold the text in its argument;no linebreaks are allowed in the text;text appears in \rm. { \mbox <text argument>} \mbox command creates a box just wide enough to hold the text in its argument;no linebreaks are allowed in the text;text appears in \rm. a + b \mbox{ (are you paying attention?) } = c a+b (are you paying attention?) =c a + b \text{ (are you paying attention?) } = c a+b (are you paying attention?) =c a + b \mbox{ (are you paying attention?) } = c a+b (are you paying attention?) =c a + b \mbox{ (are you paying attention?) } = c a + b \text{ (are you paying attention?) } = c a+b (are you paying attention?) =c a + b \text{ (are you paying attention?) } = c 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8118, "s": 7986, "text": "\\mbox - creates a box just wide enough to hold the text in its argument;no linebreaks are allowed in the text;text appears in \\rm. " }, { "code": null, "e": 8143, "s": 8118, "text": "{ \\mbox <text argument>}" }, { "code": null, "e": 8280, "s": 8143, "text": "\\mbox command creates a box just wide enough to hold the text in its argument;no linebreaks are allowed in the text;text appears in \\rm." }, { "code": null, "e": 8452, "s": 8280, "text": "\na + b \\mbox{ (are you paying attention?) } = c\n\na+b (are you paying attention?) =c\n\n\na + b \\text{ (are you paying attention?) } = c\n\na+b (are you paying attention?) =c\n\n\n" }, { "code": null, "e": 8537, "s": 8452, "text": "a + b \\mbox{ (are you paying attention?) } = c\n\na+b (are you paying attention?) =c\n\n" }, { "code": null, "e": 8584, "s": 8537, "text": "a + b \\mbox{ (are you paying attention?) } = c" }, { "code": null, "e": 8669, "s": 8584, "text": "a + b \\text{ (are you paying attention?) } = c\n\na+b (are you paying attention?) =c\n\n" }, { "code": null, "e": 8716, "s": 8669, "text": "a + b \\text{ (are you paying attention?) } = c" }, { "code": null, "e": 8748, "s": 8716, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8761, "s": 8748, "text": " Ashraf Said" }, { "code": null, "e": 8794, "s": 8761, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8807, "s": 8794, "text": " Ashraf Said" }, { "code": null, "e": 8839, "s": 8807, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8875, "s": 8839, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8910, "s": 8875, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8927, "s": 8910, "text": " Mohammad Nauman" }, { "code": null, "e": 8960, "s": 8927, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8974, "s": 8960, "text": " Daniel Stern" }, { "code": null, "e": 9006, "s": 8974, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 9021, "s": 9006, "text": " Nishant Kumar" }, { "code": null, "e": 9028, "s": 9021, "text": " Print" }, { "code": null, "e": 9039, "s": 9028, "text": " Add Notes" } ]
Getting an array of all items of a collection in Julia - collect() Method - GeeksforGeeks
26 Mar, 2020 The collect() is an inbuilt function in julia which is used to return an array of all items in the specified collection or iterator. Syntax:collect(collection)orcollect(element_type, collection) Parameters: collection: Specified collection or iterator. element_type: Specified type of elements. Returns: It returns an array of all items in the specified collection or iterator. Example 1: # Julia program to illustrate # the use of collection() method # Getting an array of all items in# the specified collection or iterator.println(collect(1:2:13))println(collect(1:4))println(collect(1:10))println(collect(1:5:10)) Output: [1, 3, 5, 7, 9, 11, 13] [1, 2, 3, 4] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] [1, 6] Example 2: # Julia program to illustrate # the use of collection() method # Getting an Array with the given # element type of all items in # a collection or iterable.println(collect(Int32, 1:2:5))println(collect(Int64, 1:5))println(collect(Float32, 1:2:5))println(collect(Float64, 1:5)) Output: Int32[1, 3, 5] [1, 2, 3, 4, 5] Float32[1.0, 3.0, 5.0] [1.0, 2.0, 3.0, 4.0, 5.0] Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Vectors in Julia Storing Output on a File in Julia Reshaping array dimensions in Julia | Array reshape() Method Getting rounded value of a number in Julia - round() Method Creating array with repeated elements in Julia - repeat() Method Get array dimensions and size of a dimension in Julia - size() Method Searching in Array for a given element in Julia Taking Input from Users in Julia while loop in Julia Tuples in Julia
[ { "code": null, "e": 24284, "s": 24256, "text": "\n26 Mar, 2020" }, { "code": null, "e": 24417, "s": 24284, "text": "The collect() is an inbuilt function in julia which is used to return an array of all items in the specified collection or iterator." }, { "code": null, "e": 24479, "s": 24417, "text": "Syntax:collect(collection)orcollect(element_type, collection)" }, { "code": null, "e": 24491, "s": 24479, "text": "Parameters:" }, { "code": null, "e": 24537, "s": 24491, "text": "collection: Specified collection or iterator." }, { "code": null, "e": 24579, "s": 24537, "text": "element_type: Specified type of elements." }, { "code": null, "e": 24662, "s": 24579, "text": "Returns: It returns an array of all items in the specified collection or iterator." }, { "code": null, "e": 24673, "s": 24662, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of collection() method # Getting an array of all items in# the specified collection or iterator.println(collect(1:2:13))println(collect(1:4))println(collect(1:10))println(collect(1:5:10))", "e": 24902, "s": 24673, "text": null }, { "code": null, "e": 24910, "s": 24902, "text": "Output:" }, { "code": null, "e": 24987, "s": 24910, "text": "[1, 3, 5, 7, 9, 11, 13]\n[1, 2, 3, 4]\n[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n[1, 6]\n" }, { "code": null, "e": 24998, "s": 24987, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of collection() method # Getting an Array with the given # element type of all items in # a collection or iterable.println(collect(Int32, 1:2:5))println(collect(Int64, 1:5))println(collect(Float32, 1:2:5))println(collect(Float64, 1:5))", "e": 25275, "s": 24998, "text": null }, { "code": null, "e": 25283, "s": 25275, "text": "Output:" }, { "code": null, "e": 25364, "s": 25283, "text": "Int32[1, 3, 5]\n[1, 2, 3, 4, 5]\nFloat32[1.0, 3.0, 5.0]\n[1.0, 2.0, 3.0, 4.0, 5.0]\n" }, { "code": null, "e": 25370, "s": 25364, "text": "Julia" }, { "code": null, "e": 25468, "s": 25370, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25477, "s": 25468, "text": "Comments" }, { "code": null, "e": 25490, "s": 25477, "text": "Old Comments" }, { "code": null, "e": 25507, "s": 25490, "text": "Vectors in Julia" }, { "code": null, "e": 25541, "s": 25507, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 25602, "s": 25541, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 25662, "s": 25602, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 25727, "s": 25662, "text": "Creating array with repeated elements in Julia - repeat() Method" }, { "code": null, "e": 25797, "s": 25727, "text": "Get array dimensions and size of a dimension in Julia - size() Method" }, { "code": null, "e": 25845, "s": 25797, "text": "Searching in Array for a given element in Julia" }, { "code": null, "e": 25878, "s": 25845, "text": "Taking Input from Users in Julia" }, { "code": null, "e": 25898, "s": 25878, "text": "while loop in Julia" } ]
Beyond One-Hot. 17 Ways of Transforming Categorical Features Into Numeric Features | by Samuele Mazzanti | Towards Data Science
“Which gradient boostings do you know?” “Xgboost, LightGBM, Catboost, HistGradient.” “And which categorical encodings do you know?” “One-hot.” I wouldn’t be surprised to hear such a conversation during a data science interview. Still, it would be quite striking, since just a small portion of data-science projects involve machine learning, whereas practically all of them involve some categorical data. Categorical encoding is the process of transforming a categorical column into one (or more) numeric column(s). This is necessary because computers are more at ease working with numbers than with strings. Why is that? Because with numbers it’s easy to find relations (such as “bigger”, “smaller”, “double”, “half”). Whereas — when given strings— a computer can say pretty much only whether they are “equal” or “different”. However, despite its impact, categorical encoding is easily overlooked by data science practitioners. Categorical encoding is a surprisingly underrated topic. This why I decided to deepen my knowledge of encoding algorithms. I started from a Python library called “category_encoders” (this is the Github link). Using it is as easy as: !pip install category_encodersimport category_encoders as cece.OrdinalEncoder().fit_transform(x) This post is a walkthrough of the 17 encoding algorithms contained in the library . For each algorithm, I provide a short explanation and a Python implementation in few lines of code. The purpose is not to reinvent the wheel, but to realize how the algorithms work under the hood. After all, “You don’t understand it, until you can code it”. I have classified the 17 encoding algorithms based on some of their characteristics. And since data scientists love decision trees, let’s make them happy: Here’s what the splits refer to: Supervised/Unsupervised: when the encoding is based solely on the categorical column, then it’s unsupervised. Otherwise, if the encoding is based on some function of the original column and a second (numeric) column, then it’s supervised. Output dimension: the encoding of a categorical column may produce one numeric column (output dimension = 1) or many numeric columns (output dimension > 1). Mapping: if each level has always the same output — whether a scalar (e.g. OrdinalEncoder) or an array (e.g. OneHotEncoder)— then the mapping is unique. On the contrary, if the same level is “allowed” to have different possible outputs, then the mapping is not unique. Each level is mapped to an integer, from 1 to L (where L is the number of levels). In this case we have used alphabetical order, but any other custom order is acceptable. You may think that ordinal encoding is non-sense, especially if the levels have no intrinsic order. You are right! In fact, it’s only a representation of convenience, used often to save memory, or as intermediate step for other types of encoding. Each level is mapped to the number of observations carrying that level. This encoding may be useful as an indicator of the “credibility” of each level. For instance, a machine learning algorithm may automatically decide to take into account the information brought by the level only its count is above some threshold. The encoding algorithm for excellence (and the most used). Each level is mapped to a dummy column (i.e. a column of 0/1), indicating whether that level is carried by that row. This implies that, whereas your input is a single column, your output consists of L columns (one for each level of the original column). This is why one-hot encoding should be handled with care: you may end up with a dataframe that is far bigger than the original one. Once the data is one-hot encoded, it’s ready for any predictive algorithm. To make things understandable at first sight, let’s take one observation for each level. Suppose we have observed a target variable, called y, containing the income of each individual (in thousands of dollars). Let’s fit a linear regression (OLS) on the data. To make the results easily readable, I have attached the OLS coefficients at the side of the table. In the case of one-hot encoding, the intercept has no particular meaning, and the coefficients are added to the intercept to obtain the estimate. In this case, since we have just one observation per level, by adding the intercept and the coefficient we obtain the exact value of y (there is no error). The code that follows may seem a little obscure at first. But don’t worry: in this case, it’s not so important to understand how the encoding is obtained, but how to use it. SumEncoder (as the next 3 encoders) belongs to a class called “contrast encodings”. These encodings are designed to have a specific behaviour when used in regression problems. In other words, you use one of these encodings if you want the regression coefficients to have some specific properties. In particular, SumEncoder is used when you want the regression coefficients to have zero-sum. If we take the same data that we have used in the paragraph above and fit a OLS, this is what we get: This time, the intercept corresponds to the mean of y. Moreover, by taking y of the last level and subtracting it from the intercept (68-50) we get 18, which is exactly the opposite of the sum of the remaining coefficients (-15-5+2=-18). This is precisely the property of sum encoding that I have mentioned above. Another contrast encoding (like SumEncoder). This encoder is useful for ordinal variables, i.e. variables whose levels can be ordered in a meaningful way. BackwardDifferenceEncoder is designed to compare adjacent levels. Suppose you have an ordinable variable (e.g. education level) and you want to know how it is related to a numeric variable (e.g. income). It may be interesting to compare each couple of consecutive levels (e.g. bachelors vs. high-school, masters vs. bachelors) with respect to the target variable. This is what BackwardDifferenceEncoder is designed for. Let’s see an example with the same data from the paragraphs above. The intercept coincides with the mean of y. The coefficient of Bachelors is 10, because y of Bachelors is 10 higher than High-School, Masters’ coefficient equals 7 because y of Masters is 7 higher than Bachelors and so on. HelmertEncoder is very similar to BackwardDifferenceEncoder, but instead of being compared just to the previous one, each level is compared with all the previous levels. Let’s see what we would get from a OLS model: PhD’s coefficient is 24, because PhD is 24 higher than the mean of the previous levels 68-((35+45+52)/3)=24. The same reasoning applies to all the levels. Another contrast encoding. As its name suggests, PolynomialEncoder is designed to quantify linear, quadratic and cubic behaviors of the target variable with respect to the categorical variable. I know what you are thinking. How can a numeric variable have a linear (or quadratic, or cubic) relation with a variable that is not numeric? This is based on the assumption that the underlying categorical variable has levels that are not only ordinable, but also equally spaced. For this reason, I would suggest to use it with care, only when you are sure that the assumption is reasonable. BinaryEncoder is basically the same of OrdinalEncoder, the only difference is that the integers are converted to binary numbers, then every positional digit is one-hot encoded. The output consists of dummy columns, as happens for the OneHotEncoder, but it leads to a dimensionality reduction with respect to one-hot. Honestly, I don’t know any practical application of this type of encoding (if you do, please comment below!). BaseNEncoder is simply a generalization of the BinaryEncoder. In fact, in BinaryEncoder, the numbers are in base 2, whereas in BaseNEncoder, numbers are in base n, with n greater than 1. Let’s see an example with base=3. Honestly, I don’t know any practical application of this type of encoding (if you do, please comment below!). In HashingEncoder, each original level is hashed, using some hashing algorithm, such as SHA-256. Then, the outcome is converted to integer and the module of that integer with respect to some (big) divisor is taken. By doing so, we have mapped each original string to an integer between 1 and divisor-1. Lastly, the integer that has been obtained by this procedure is one-hot encoded. Let’s see an example with output_dimension = 10. The fundamental property of hashing is that the resulting integer is uniformly distributed. So, if you take a divisor big enough, it’s unlikely that two different strings are mapped to the same integer. Why would that be useful? Actually, this has a very practical application called “hashing trick”. Imagine that you want to make an email spam classifier using a logistic regression. You could do that by one-hot-encoding all the words contained in your dataset. The main downsides are that you would need to store the mapping in a separate dictionary and your model dimensions would change any time that new strings appear. These issues may be easily overcome by using the hashing trick, because by hashing the input, you don’t need a dictionary anymore and your output dimension is fixed (it depends only on the divisor that you choose initially). Moreover, for the properties of hashing, you are granted that a new string will likely have a different encoding than the existing ones. Suppose that you have two variables: one categorical (x) and one numeric (y). Say that you want to transform x into a numeric variable. You may want to employ the information “carried” by y. An obvious idea is to take the mean of y for each level of x. In formula: This is reasonable, but there’s a big problem with this approach: some groups may be too small or too variable to be reliable. Many supervised encodings overcome this issue by choosing a middle way between the group mean and the global mean of y: where w_i is between 0 and 1, depending on how “credible” is the group mean. The next three algorithms (TargetEncoder, MEstimateEncoder and JamesSteinEncoder) differ based on how they define w_i. In TargetEncoder, the weight depends on the group numerosity and on a parameter called “smoothing”. When smoothing is 0, we rely solely on group means. Then, as smoothing increases, the global mean weights more and more, leading to a stronger regularization. Let’s see how the outcome changes with some different values of smoothing. MEstimateEncoder resembles TargetEncoder, but w_i depends on a parameter called “m”, which sets how much the global mean should weight in absolute terms. m is easy to understand because it can be considered as a number of observations: if the level has exactly m observations, then the level mean and the overall mean weight the same. Let’s see how the outcome changes for different values of m: TargetEncoder and MEstimateEncoder depend both on the group numerosity and on the value of a parameter (respectively smoothing and m) set by the user. This is not convenient, because setting these weights is a manual task. A natural question is the following: is there a way to set an optimal w_i, without the need of any human intervention? The JamesSteinEncoder tries to do so in a way that is statistically grounded. The intuition is that the mean of a group with high variance should be trusted less. Therefore, the higher the group variance, the lower the weight (if you want to know more about the formula, I suggest this post by Chris Said). Let’s see a numeric example: The JamesSteinEncoder has two significant advantages: it provides better estimates than the maximum-likelihood estimator, and it doesn’t need any parameter setting. GLMMEncoder follows a totally different approach. Basically, it fits a Linear Mixed Effect Model on y. This approach exploits the fact that Linear Mixed Effect Models are designed precisely for handling homogeneous groups of observations (as well explained here). Thus, the idea is to fit a model with no regressors (only the intercept) and to use the levels as groups. Then, the output is simply the sum of the intercept and the random effect of the group. WOEEncoder (which stands for “Weight of Evidence” Encoder) can be employed only for binary target variables, i.e. target variables whose levels are 0/1. The idea behind Weight of Evidence is that you have two distributions: the distribution of 1s (# of 1s in each group / # of 1s in all y) the distribution of 0s (# of 0s in each group / # of 0s in all y) The heart of the algorithm is dividing the distribution of 1s by the distribution of 0s (for each group). Of course, the higher this value, the more confident we are that the group is “skewed” towards 1s, and viceversa. Then, the logarithm of this value is taken. As you can see, due to the presence of a logarithm in the formula, the output is not not directly interpretable. However, it works pretty well as a preprocessing step for machine learning. All the 15 encoders seen up until now have a unique mapping. However, if you plan to use the encoding as input for a predictive model (for example a gradient boosting), this could be a problem. In fact, suppose that you use TargetEncoder. This would imply that you are introducing information about y_train inside X_train, which could lead to a serious risk of overfitting. The point is: how to maintain a supervised encoding, while limiting the risk of overfitting? LeaveOneOutEncoder offers a brilliant solution. It does a vanilla target encoding but, for each row, it does not consider the value of y observed for that row. In this way, it avoids row-wise leakage. CatBoost is a gradient boosting algorithm (like XGBoost or LightGBM) that has shown to work extremely well in a wide range of problems. The encoding algorithm is described in detail here (our implementation is a little simplified, but it’s good for grasping the concept). CatboostEncoder works basically like LeaveOneOutEncoder, but following an on-line approach. But how to simulate an on-line behaviour in an off-line setting? Imagine that you have a table. Then, take a row somewhere in the middle of the table. What CatBoost does is pretending that the rows above the current row have been observed previously in time, while the rows below have yet to be observed (i.e. will be observed in the future). Then, the algorithm does a leave-one-out encoding, but based only on the rows already observed. This may seem absurd. Why throwing away some information that could be useful? You can see it simply as more extreme attempt of randomizing the output (i.e. reducing overfitting). You can find all the code that is in the post (and something more) in this Github notebook. Thank you for reading! I hope you found this post useful. I appreciate feedback and constructive criticism. If you want to talk about this article or other related topics, you can text me at my Linkedin contact.
[ { "code": null, "e": 212, "s": 172, "text": "“Which gradient boostings do you know?”" }, { "code": null, "e": 257, "s": 212, "text": "“Xgboost, LightGBM, Catboost, HistGradient.”" }, { "code": null, "e": 304, "s": 257, "text": "“And which categorical encodings do you know?”" }, { "code": null, "e": 315, "s": 304, "text": "“One-hot.”" }, { "code": null, "e": 576, "s": 315, "text": "I wouldn’t be surprised to hear such a conversation during a data science interview. Still, it would be quite striking, since just a small portion of data-science projects involve machine learning, whereas practically all of them involve some categorical data." }, { "code": null, "e": 687, "s": 576, "text": "Categorical encoding is the process of transforming a categorical column into one (or more) numeric column(s)." }, { "code": null, "e": 998, "s": 687, "text": "This is necessary because computers are more at ease working with numbers than with strings. Why is that? Because with numbers it’s easy to find relations (such as “bigger”, “smaller”, “double”, “half”). Whereas — when given strings— a computer can say pretty much only whether they are “equal” or “different”." }, { "code": null, "e": 1100, "s": 998, "text": "However, despite its impact, categorical encoding is easily overlooked by data science practitioners." }, { "code": null, "e": 1157, "s": 1100, "text": "Categorical encoding is a surprisingly underrated topic." }, { "code": null, "e": 1333, "s": 1157, "text": "This why I decided to deepen my knowledge of encoding algorithms. I started from a Python library called “category_encoders” (this is the Github link). Using it is as easy as:" }, { "code": null, "e": 1430, "s": 1333, "text": "!pip install category_encodersimport category_encoders as cece.OrdinalEncoder().fit_transform(x)" }, { "code": null, "e": 1722, "s": 1430, "text": "This post is a walkthrough of the 17 encoding algorithms contained in the library . For each algorithm, I provide a short explanation and a Python implementation in few lines of code. The purpose is not to reinvent the wheel, but to realize how the algorithms work under the hood. After all," }, { "code": null, "e": 1772, "s": 1722, "text": "“You don’t understand it, until you can code it”." }, { "code": null, "e": 1927, "s": 1772, "text": "I have classified the 17 encoding algorithms based on some of their characteristics. And since data scientists love decision trees, let’s make them happy:" }, { "code": null, "e": 1960, "s": 1927, "text": "Here’s what the splits refer to:" }, { "code": null, "e": 2199, "s": 1960, "text": "Supervised/Unsupervised: when the encoding is based solely on the categorical column, then it’s unsupervised. Otherwise, if the encoding is based on some function of the original column and a second (numeric) column, then it’s supervised." }, { "code": null, "e": 2356, "s": 2199, "text": "Output dimension: the encoding of a categorical column may produce one numeric column (output dimension = 1) or many numeric columns (output dimension > 1)." }, { "code": null, "e": 2625, "s": 2356, "text": "Mapping: if each level has always the same output — whether a scalar (e.g. OrdinalEncoder) or an array (e.g. OneHotEncoder)— then the mapping is unique. On the contrary, if the same level is “allowed” to have different possible outputs, then the mapping is not unique." }, { "code": null, "e": 2796, "s": 2625, "text": "Each level is mapped to an integer, from 1 to L (where L is the number of levels). In this case we have used alphabetical order, but any other custom order is acceptable." }, { "code": null, "e": 3043, "s": 2796, "text": "You may think that ordinal encoding is non-sense, especially if the levels have no intrinsic order. You are right! In fact, it’s only a representation of convenience, used often to save memory, or as intermediate step for other types of encoding." }, { "code": null, "e": 3115, "s": 3043, "text": "Each level is mapped to the number of observations carrying that level." }, { "code": null, "e": 3361, "s": 3115, "text": "This encoding may be useful as an indicator of the “credibility” of each level. For instance, a machine learning algorithm may automatically decide to take into account the information brought by the level only its count is above some threshold." }, { "code": null, "e": 3537, "s": 3361, "text": "The encoding algorithm for excellence (and the most used). Each level is mapped to a dummy column (i.e. a column of 0/1), indicating whether that level is carried by that row." }, { "code": null, "e": 3806, "s": 3537, "text": "This implies that, whereas your input is a single column, your output consists of L columns (one for each level of the original column). This is why one-hot encoding should be handled with care: you may end up with a dataframe that is far bigger than the original one." }, { "code": null, "e": 4141, "s": 3806, "text": "Once the data is one-hot encoded, it’s ready for any predictive algorithm. To make things understandable at first sight, let’s take one observation for each level. Suppose we have observed a target variable, called y, containing the income of each individual (in thousands of dollars). Let’s fit a linear regression (OLS) on the data." }, { "code": null, "e": 4241, "s": 4141, "text": "To make the results easily readable, I have attached the OLS coefficients at the side of the table." }, { "code": null, "e": 4543, "s": 4241, "text": "In the case of one-hot encoding, the intercept has no particular meaning, and the coefficients are added to the intercept to obtain the estimate. In this case, since we have just one observation per level, by adding the intercept and the coefficient we obtain the exact value of y (there is no error)." }, { "code": null, "e": 4717, "s": 4543, "text": "The code that follows may seem a little obscure at first. But don’t worry: in this case, it’s not so important to understand how the encoding is obtained, but how to use it." }, { "code": null, "e": 5014, "s": 4717, "text": "SumEncoder (as the next 3 encoders) belongs to a class called “contrast encodings”. These encodings are designed to have a specific behaviour when used in regression problems. In other words, you use one of these encodings if you want the regression coefficients to have some specific properties." }, { "code": null, "e": 5210, "s": 5014, "text": "In particular, SumEncoder is used when you want the regression coefficients to have zero-sum. If we take the same data that we have used in the paragraph above and fit a OLS, this is what we get:" }, { "code": null, "e": 5524, "s": 5210, "text": "This time, the intercept corresponds to the mean of y. Moreover, by taking y of the last level and subtracting it from the intercept (68-50) we get 18, which is exactly the opposite of the sum of the remaining coefficients (-15-5+2=-18). This is precisely the property of sum encoding that I have mentioned above." }, { "code": null, "e": 5569, "s": 5524, "text": "Another contrast encoding (like SumEncoder)." }, { "code": null, "e": 5745, "s": 5569, "text": "This encoder is useful for ordinal variables, i.e. variables whose levels can be ordered in a meaningful way. BackwardDifferenceEncoder is designed to compare adjacent levels." }, { "code": null, "e": 6166, "s": 5745, "text": "Suppose you have an ordinable variable (e.g. education level) and you want to know how it is related to a numeric variable (e.g. income). It may be interesting to compare each couple of consecutive levels (e.g. bachelors vs. high-school, masters vs. bachelors) with respect to the target variable. This is what BackwardDifferenceEncoder is designed for. Let’s see an example with the same data from the paragraphs above." }, { "code": null, "e": 6389, "s": 6166, "text": "The intercept coincides with the mean of y. The coefficient of Bachelors is 10, because y of Bachelors is 10 higher than High-School, Masters’ coefficient equals 7 because y of Masters is 7 higher than Bachelors and so on." }, { "code": null, "e": 6559, "s": 6389, "text": "HelmertEncoder is very similar to BackwardDifferenceEncoder, but instead of being compared just to the previous one, each level is compared with all the previous levels." }, { "code": null, "e": 6605, "s": 6559, "text": "Let’s see what we would get from a OLS model:" }, { "code": null, "e": 6760, "s": 6605, "text": "PhD’s coefficient is 24, because PhD is 24 higher than the mean of the previous levels 68-((35+45+52)/3)=24. The same reasoning applies to all the levels." }, { "code": null, "e": 6787, "s": 6760, "text": "Another contrast encoding." }, { "code": null, "e": 6954, "s": 6787, "text": "As its name suggests, PolynomialEncoder is designed to quantify linear, quadratic and cubic behaviors of the target variable with respect to the categorical variable." }, { "code": null, "e": 7234, "s": 6954, "text": "I know what you are thinking. How can a numeric variable have a linear (or quadratic, or cubic) relation with a variable that is not numeric? This is based on the assumption that the underlying categorical variable has levels that are not only ordinable, but also equally spaced." }, { "code": null, "e": 7346, "s": 7234, "text": "For this reason, I would suggest to use it with care, only when you are sure that the assumption is reasonable." }, { "code": null, "e": 7523, "s": 7346, "text": "BinaryEncoder is basically the same of OrdinalEncoder, the only difference is that the integers are converted to binary numbers, then every positional digit is one-hot encoded." }, { "code": null, "e": 7663, "s": 7523, "text": "The output consists of dummy columns, as happens for the OneHotEncoder, but it leads to a dimensionality reduction with respect to one-hot." }, { "code": null, "e": 7773, "s": 7663, "text": "Honestly, I don’t know any practical application of this type of encoding (if you do, please comment below!)." }, { "code": null, "e": 7960, "s": 7773, "text": "BaseNEncoder is simply a generalization of the BinaryEncoder. In fact, in BinaryEncoder, the numbers are in base 2, whereas in BaseNEncoder, numbers are in base n, with n greater than 1." }, { "code": null, "e": 7994, "s": 7960, "text": "Let’s see an example with base=3." }, { "code": null, "e": 8104, "s": 7994, "text": "Honestly, I don’t know any practical application of this type of encoding (if you do, please comment below!)." }, { "code": null, "e": 8488, "s": 8104, "text": "In HashingEncoder, each original level is hashed, using some hashing algorithm, such as SHA-256. Then, the outcome is converted to integer and the module of that integer with respect to some (big) divisor is taken. By doing so, we have mapped each original string to an integer between 1 and divisor-1. Lastly, the integer that has been obtained by this procedure is one-hot encoded." }, { "code": null, "e": 8537, "s": 8488, "text": "Let’s see an example with output_dimension = 10." }, { "code": null, "e": 8838, "s": 8537, "text": "The fundamental property of hashing is that the resulting integer is uniformly distributed. So, if you take a divisor big enough, it’s unlikely that two different strings are mapped to the same integer. Why would that be useful? Actually, this has a very practical application called “hashing trick”." }, { "code": null, "e": 9163, "s": 8838, "text": "Imagine that you want to make an email spam classifier using a logistic regression. You could do that by one-hot-encoding all the words contained in your dataset. The main downsides are that you would need to store the mapping in a separate dictionary and your model dimensions would change any time that new strings appear." }, { "code": null, "e": 9525, "s": 9163, "text": "These issues may be easily overcome by using the hashing trick, because by hashing the input, you don’t need a dictionary anymore and your output dimension is fixed (it depends only on the divisor that you choose initially). Moreover, for the properties of hashing, you are granted that a new string will likely have a different encoding than the existing ones." }, { "code": null, "e": 9790, "s": 9525, "text": "Suppose that you have two variables: one categorical (x) and one numeric (y). Say that you want to transform x into a numeric variable. You may want to employ the information “carried” by y. An obvious idea is to take the mean of y for each level of x. In formula:" }, { "code": null, "e": 10037, "s": 9790, "text": "This is reasonable, but there’s a big problem with this approach: some groups may be too small or too variable to be reliable. Many supervised encodings overcome this issue by choosing a middle way between the group mean and the global mean of y:" }, { "code": null, "e": 10114, "s": 10037, "text": "where w_i is between 0 and 1, depending on how “credible” is the group mean." }, { "code": null, "e": 10233, "s": 10114, "text": "The next three algorithms (TargetEncoder, MEstimateEncoder and JamesSteinEncoder) differ based on how they define w_i." }, { "code": null, "e": 10492, "s": 10233, "text": "In TargetEncoder, the weight depends on the group numerosity and on a parameter called “smoothing”. When smoothing is 0, we rely solely on group means. Then, as smoothing increases, the global mean weights more and more, leading to a stronger regularization." }, { "code": null, "e": 10567, "s": 10492, "text": "Let’s see how the outcome changes with some different values of smoothing." }, { "code": null, "e": 10902, "s": 10567, "text": "MEstimateEncoder resembles TargetEncoder, but w_i depends on a parameter called “m”, which sets how much the global mean should weight in absolute terms. m is easy to understand because it can be considered as a number of observations: if the level has exactly m observations, then the level mean and the overall mean weight the same." }, { "code": null, "e": 10963, "s": 10902, "text": "Let’s see how the outcome changes for different values of m:" }, { "code": null, "e": 11186, "s": 10963, "text": "TargetEncoder and MEstimateEncoder depend both on the group numerosity and on the value of a parameter (respectively smoothing and m) set by the user. This is not convenient, because setting these weights is a manual task." }, { "code": null, "e": 11383, "s": 11186, "text": "A natural question is the following: is there a way to set an optimal w_i, without the need of any human intervention? The JamesSteinEncoder tries to do so in a way that is statistically grounded." }, { "code": null, "e": 11612, "s": 11383, "text": "The intuition is that the mean of a group with high variance should be trusted less. Therefore, the higher the group variance, the lower the weight (if you want to know more about the formula, I suggest this post by Chris Said)." }, { "code": null, "e": 11641, "s": 11612, "text": "Let’s see a numeric example:" }, { "code": null, "e": 11806, "s": 11641, "text": "The JamesSteinEncoder has two significant advantages: it provides better estimates than the maximum-likelihood estimator, and it doesn’t need any parameter setting." }, { "code": null, "e": 12176, "s": 11806, "text": "GLMMEncoder follows a totally different approach. Basically, it fits a Linear Mixed Effect Model on y. This approach exploits the fact that Linear Mixed Effect Models are designed precisely for handling homogeneous groups of observations (as well explained here). Thus, the idea is to fit a model with no regressors (only the intercept) and to use the levels as groups." }, { "code": null, "e": 12264, "s": 12176, "text": "Then, the output is simply the sum of the intercept and the random effect of the group." }, { "code": null, "e": 12417, "s": 12264, "text": "WOEEncoder (which stands for “Weight of Evidence” Encoder) can be employed only for binary target variables, i.e. target variables whose levels are 0/1." }, { "code": null, "e": 12488, "s": 12417, "text": "The idea behind Weight of Evidence is that you have two distributions:" }, { "code": null, "e": 12554, "s": 12488, "text": "the distribution of 1s (# of 1s in each group / # of 1s in all y)" }, { "code": null, "e": 12620, "s": 12554, "text": "the distribution of 0s (# of 0s in each group / # of 0s in all y)" }, { "code": null, "e": 12884, "s": 12620, "text": "The heart of the algorithm is dividing the distribution of 1s by the distribution of 0s (for each group). Of course, the higher this value, the more confident we are that the group is “skewed” towards 1s, and viceversa. Then, the logarithm of this value is taken." }, { "code": null, "e": 13073, "s": 12884, "text": "As you can see, due to the presence of a logarithm in the formula, the output is not not directly interpretable. However, it works pretty well as a preprocessing step for machine learning." }, { "code": null, "e": 13134, "s": 13073, "text": "All the 15 encoders seen up until now have a unique mapping." }, { "code": null, "e": 13447, "s": 13134, "text": "However, if you plan to use the encoding as input for a predictive model (for example a gradient boosting), this could be a problem. In fact, suppose that you use TargetEncoder. This would imply that you are introducing information about y_train inside X_train, which could lead to a serious risk of overfitting." }, { "code": null, "e": 13741, "s": 13447, "text": "The point is: how to maintain a supervised encoding, while limiting the risk of overfitting? LeaveOneOutEncoder offers a brilliant solution. It does a vanilla target encoding but, for each row, it does not consider the value of y observed for that row. In this way, it avoids row-wise leakage." }, { "code": null, "e": 14013, "s": 13741, "text": "CatBoost is a gradient boosting algorithm (like XGBoost or LightGBM) that has shown to work extremely well in a wide range of problems. The encoding algorithm is described in detail here (our implementation is a little simplified, but it’s good for grasping the concept)." }, { "code": null, "e": 14105, "s": 14013, "text": "CatboostEncoder works basically like LeaveOneOutEncoder, but following an on-line approach." }, { "code": null, "e": 14544, "s": 14105, "text": "But how to simulate an on-line behaviour in an off-line setting? Imagine that you have a table. Then, take a row somewhere in the middle of the table. What CatBoost does is pretending that the rows above the current row have been observed previously in time, while the rows below have yet to be observed (i.e. will be observed in the future). Then, the algorithm does a leave-one-out encoding, but based only on the rows already observed." }, { "code": null, "e": 14724, "s": 14544, "text": "This may seem absurd. Why throwing away some information that could be useful? You can see it simply as more extreme attempt of randomizing the output (i.e. reducing overfitting)." }, { "code": null, "e": 14816, "s": 14724, "text": "You can find all the code that is in the post (and something more) in this Github notebook." }, { "code": null, "e": 14874, "s": 14816, "text": "Thank you for reading! I hope you found this post useful." } ]
Functional Programming - Lambda Expressions
Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot. A lambda expression is characterized by the following syntax. parameter -> expression body Following are the important characteristics of a lambda expression. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter. Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter. Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required. Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required. Optional curly braces − No need to use curly braces in expression body if the body contains a single statement. Optional curly braces − No need to use curly braces in expression body if the body contains a single statement. Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value. Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value. Create the following Java program using any editor of your choice in, say, C:\> JAVA. public class Java8Tester { public static void main(String args[]) { Java8Tester tester = new Java8Tester(); //with type declaration MathOperation addition = (int a, int b) -> a + b; //with out type declaration MathOperation subtraction = (a, b) -> a - b; //with return statement along with curly braces MathOperation multiplication = (int a, int b) -> { return a * b; }; //without return statement and without curly braces MathOperation division = (int a, int b) -> a / b; System.out.println("10 + 5 = " + tester.operate(10, 5, addition)); System.out.println("10 - 5 = " + tester.operate(10, 5, subtraction)); System.out.println("10 x 5 = " + tester.operate(10, 5, multiplication)); System.out.println("10 / 5 = " + tester.operate(10, 5, division)); //without parenthesis GreetingService greetService1 = message -> System.out.println("Hello " + message); //with parenthesis GreetingService greetService2 = (message) -> System.out.println("Hello " + message); greetService1.sayMessage("Mahesh"); greetService2.sayMessage("Suresh"); } interface MathOperation { int operation(int a, int b); } interface GreetingService { void sayMessage(String message); } private int operate(int a, int b, MathOperation mathOperation) { return mathOperation.operation(a, b); } } Compile the class using javac compiler as follows − C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:\JAVA>java Java8Tester It should produce the following output − 10 + 5 = 15 10 - 5 = 5 10 x 5 = 50 10 / 5 = 2 Hello Mahesh Hello Suresh Following are the important points to be considered in the above example. Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService. Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService. Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java. Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java. Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time. Create the following Java program using any editor of your choice in, say, C:\> JAVA. Java8Tester.java public class Java8Tester { final static String salutation = "Hello! "; public static void main(String args[]) { GreetingService greetService1 = message -> System.out.println(salutation + message); greetService1.sayMessage("Mahesh"); } interface GreetingService { void sayMessage(String message); } } Compile the class using javac compiler as follows − C:\JAVA>javac Java8Tester.java Now run the Java8Tester as follows − C:\JAVA>java Java8Tester It should produce the following output − Hello! Mahesh 32 Lectures 3.5 hours Pavan Lalwani 11 Lectures 1 hours Prof. Paul Cline, Ed.D 72 Lectures 10.5 hours Arun Ammasai 51 Lectures 2 hours Skillbakerystudios 43 Lectures 4 hours Mohammad Nauman 8 Lectures 1 hours Santharam Sivalenka Print Add Notes Bookmark this page
[ { "code": null, "e": 2277, "s": 2089, "text": "Lambda expressions are introduced in Java 8 and are touted to be the biggest feature of Java 8. Lambda expression facilitates functional programming, and simplifies the development a lot." }, { "code": null, "e": 2339, "s": 2277, "text": "A lambda expression is characterized by the following syntax." }, { "code": null, "e": 2369, "s": 2339, "text": "parameter -> expression body\n" }, { "code": null, "e": 2437, "s": 2369, "text": "Following are the important characteristics of a lambda expression." }, { "code": null, "e": 2578, "s": 2437, "text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter." }, { "code": null, "e": 2719, "s": 2578, "text": "Optional type declaration − No need to declare the type of a parameter. The compiler can inference the same from the value of the parameter." }, { "code": null, "e": 2864, "s": 2719, "text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required." }, { "code": null, "e": 3009, "s": 2864, "text": "Optional parenthesis around parameter − No need to declare a single parameter in parenthesis. For multiple parameters, parentheses are required." }, { "code": null, "e": 3121, "s": 3009, "text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement." }, { "code": null, "e": 3233, "s": 3121, "text": "Optional curly braces − No need to use curly braces in expression body if the body contains a single statement." }, { "code": null, "e": 3432, "s": 3233, "text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value." }, { "code": null, "e": 3631, "s": 3432, "text": "Optional return keyword − The compiler automatically returns the value if the body has a single expression to return the value. Curly braces are required to indicate that expression returns a value." }, { "code": null, "e": 3717, "s": 3631, "text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA." }, { "code": null, "e": 5176, "s": 3717, "text": "public class Java8Tester {\n\n public static void main(String args[]) {\n Java8Tester tester = new Java8Tester();\n\t\t\n //with type declaration\n MathOperation addition = (int a, int b) -> a + b;\n\t\t\n //with out type declaration\n MathOperation subtraction = (a, b) -> a - b;\n\t\t\n //with return statement along with curly braces\n MathOperation multiplication = (int a, int b) -> { return a * b; };\n\t\t\n //without return statement and without curly braces\n MathOperation division = (int a, int b) -> a / b;\n\t\t\n System.out.println(\"10 + 5 = \" + tester.operate(10, 5, addition));\n System.out.println(\"10 - 5 = \" + tester.operate(10, 5, subtraction));\n System.out.println(\"10 x 5 = \" + tester.operate(10, 5, multiplication));\n System.out.println(\"10 / 5 = \" + tester.operate(10, 5, division));\n\t\t\n //without parenthesis\n GreetingService greetService1 = message ->\n System.out.println(\"Hello \" + message);\n\t\t\n //with parenthesis\n GreetingService greetService2 = (message) ->\n System.out.println(\"Hello \" + message);\n\t\t\n greetService1.sayMessage(\"Mahesh\");\n greetService2.sayMessage(\"Suresh\");\n }\n\t\n interface MathOperation {\n int operation(int a, int b);\n }\n\t\n interface GreetingService {\n void sayMessage(String message);\n }\n\t\n private int operate(int a, int b, MathOperation mathOperation) {\n return mathOperation.operation(a, b);\n }\n}" }, { "code": null, "e": 5228, "s": 5176, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 5260, "s": 5228, "text": "C:\\JAVA>javac Java8Tester.java\n" }, { "code": null, "e": 5297, "s": 5260, "text": "Now run the Java8Tester as follows −" }, { "code": null, "e": 5323, "s": 5297, "text": "C:\\JAVA>java Java8Tester\n" }, { "code": null, "e": 5364, "s": 5323, "text": "It should produce the following output −" }, { "code": null, "e": 5437, "s": 5364, "text": "10 + 5 = 15\n10 - 5 = 5\n10 x 5 = 50\n10 / 5 = 2\nHello Mahesh\nHello Suresh\n" }, { "code": null, "e": 5511, "s": 5437, "text": "Following are the important points to be considered in the above example." }, { "code": null, "e": 5856, "s": 5511, "text": "Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService." }, { "code": null, "e": 6201, "s": 5856, "text": "Lambda expressions are used primarily to define inline implementation of a functional interface, i.e., an interface with a single method only. In the above example, we've used various types of lambda expressions to define the operation method of MathOperation interface. Then we have defined the implementation of sayMessage of GreetingService." }, { "code": null, "e": 6338, "s": 6201, "text": "Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java." }, { "code": null, "e": 6475, "s": 6338, "text": "Lambda expression eliminates the need of anonymous class and gives a very simple yet powerful functional programming capability to Java." }, { "code": null, "e": 6694, "s": 6475, "text": "Using lambda expression, you can refer to any final variable or effectively final variable (which is assigned only once). Lambda expression throws a compilation error, if a variable is assigned a value the second time." }, { "code": null, "e": 6780, "s": 6694, "text": "Create the following Java program using any editor of your choice in, say, C:\\> JAVA." }, { "code": null, "e": 6797, "s": 6780, "text": "Java8Tester.java" }, { "code": null, "e": 7144, "s": 6797, "text": "public class Java8Tester {\n\n final static String salutation = \"Hello! \";\n \n public static void main(String args[]) {\n GreetingService greetService1 = message -> \n System.out.println(salutation + message);\n greetService1.sayMessage(\"Mahesh\");\n }\n\t\n interface GreetingService {\n void sayMessage(String message);\n }\n}" }, { "code": null, "e": 7196, "s": 7144, "text": "Compile the class using javac compiler as follows −" }, { "code": null, "e": 7228, "s": 7196, "text": "C:\\JAVA>javac Java8Tester.java\n" }, { "code": null, "e": 7265, "s": 7228, "text": "Now run the Java8Tester as follows −" }, { "code": null, "e": 7291, "s": 7265, "text": "C:\\JAVA>java Java8Tester\n" }, { "code": null, "e": 7332, "s": 7291, "text": "It should produce the following output −" }, { "code": null, "e": 7347, "s": 7332, "text": "Hello! Mahesh\n" }, { "code": null, "e": 7382, "s": 7347, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7397, "s": 7382, "text": " Pavan Lalwani" }, { "code": null, "e": 7430, "s": 7397, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 7454, "s": 7430, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 7490, "s": 7454, "text": "\n 72 Lectures \n 10.5 hours \n" }, { "code": null, "e": 7504, "s": 7490, "text": " Arun Ammasai" }, { "code": null, "e": 7537, "s": 7504, "text": "\n 51 Lectures \n 2 hours \n" }, { "code": null, "e": 7557, "s": 7537, "text": " Skillbakerystudios" }, { "code": null, "e": 7590, "s": 7557, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 7607, "s": 7590, "text": " Mohammad Nauman" }, { "code": null, "e": 7639, "s": 7607, "text": "\n 8 Lectures \n 1 hours \n" }, { "code": null, "e": 7660, "s": 7639, "text": " Santharam Sivalenka" }, { "code": null, "e": 7667, "s": 7660, "text": " Print" }, { "code": null, "e": 7678, "s": 7667, "text": " Add Notes" } ]
Tryit Editor v3.7
Tryit: HTML link to another folder
[]
Difference between OOP and POP - GeeksforGeeks
20 Aug, 2019 OOP:Related with the real life objects and their properties. OOP Concepts: 1. Class and Objects 2. Data abstraction 3. Encapsulation 4. Polymorphism 5. Inheritance POP:Related with the conventional style. This approach is also known as the top-down approach. In this approach, a program is divided into functions that perform specific tasks. This approach is mainly used for medium-sized applications. Data is global, and all the functions can access global data. The basic drawback of the procedural programming approach is that data is not secured because data is global and can be accessed by any function. Program control flow is achieved through function calls and go to statements. Difference between OOP and POP: Santosh Kumar 7 Object-Oriented-Design Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Differences and Applications of List, Tuple, Set and Dictionary in Python Difference between HashMap and HashSet Difference between Compile-time and Run-time Polymorphism in Java Similarities and Difference between Java and C++ Difference between List and ArrayList in Java Difference Between map() And flatMap() In Java Stream
[ { "code": null, "e": 24883, "s": 24855, "text": "\n20 Aug, 2019" }, { "code": null, "e": 24958, "s": 24883, "text": "OOP:Related with the real life objects and their properties. OOP Concepts:" }, { "code": null, "e": 25048, "s": 24958, "text": "1. Class and Objects\n2. Data abstraction\n3. Encapsulation\n4. Polymorphism\n5. Inheritance " }, { "code": null, "e": 25572, "s": 25048, "text": "POP:Related with the conventional style. This approach is also known as the top-down approach. In this approach, a program is divided into functions that perform specific tasks. This approach is mainly used for medium-sized applications. Data is global, and all the functions can access global data. The basic drawback of the procedural programming approach is that data is not secured because data is global and can be accessed by any function. Program control flow is achieved through function calls and go to statements." }, { "code": null, "e": 25604, "s": 25572, "text": "Difference between OOP and POP:" }, { "code": null, "e": 25620, "s": 25604, "text": "Santosh Kumar 7" }, { "code": null, "e": 25643, "s": 25620, "text": "Object-Oriented-Design" }, { "code": null, "e": 25662, "s": 25643, "text": "Difference Between" }, { "code": null, "e": 25760, "s": 25662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25821, "s": 25760, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 25889, "s": 25821, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 25947, "s": 25889, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 26002, "s": 25947, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 26076, "s": 26002, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 26115, "s": 26076, "text": "Difference between HashMap and HashSet" }, { "code": null, "e": 26181, "s": 26115, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 26230, "s": 26181, "text": "Similarities and Difference between Java and C++" }, { "code": null, "e": 26276, "s": 26230, "text": "Difference between List and ArrayList in Java" } ]
Tryit Editor v3.7
Tryit: SVG circle
[]
Faster Machine Learning Training with a GPU or TPU | by Bruce H. Cottman, Ph.D. | Towards Data Science
You can use the Jupyter Notebook on your local computer. Google Colab improves on the Jupyter Notebook in many ways. Here are the seven most powerful reasons to use Google Colab: You can get any public Jupyter Notebook from a GitHub repository.You load, edit, and save any .ipynbfile to the Google Drive associated with the Colab login. It is helpful to have a separate Google account for each project and thus a different Google Drive. You can get any public Jupyter Notebook from a GitHub repository. You load, edit, and save any .ipynbfile to the Google Drive associated with the Colab login. It is helpful to have a separate Google account for each project and thus a different Google Drive. Note: You can create a Git account for any project folder on Google Drive. Each team member hosts on a variety of different local computers. All they need is a browser and internet connection. Your team can be fully distributed geographically by the cloud. 3. You can provision one of many generations of the NVIDIA GPU. 4. You can provision one of many generations of the Google TPU. 5. You can provision a multi-core CPU. 6. Google Colab is free. Also, you can upgrade to a premium version that costs $9.99 per month per account. 7. A Colab notebook has many useful extensions of a Jupyter Notebook. In a browser, head to https://colab.research.google.com. A new tab pointing to Google Colab opens: If you are new to Colab, the only file in Recent is Welcome to Collaboratory. As I am not new, you can count five files in Recent. Click on GitHub and observe: Enter the GitHub account you want to browse. I entered bcottman, my GitHub top-level repository. From the repo bcottman/paso, I chose the file bcottman/paso/integration_test_pre_all.ipynb. This results in the file bcottman/paso/integration_test_pre_all.ipynb being loaded into the GCP (Google Cloud Platform) Colab browser. You can create a Google Drive and then create a Git account for any project folder. You are going to https://colab.research.google.com. Mount the Google Drive of the Google account. All files in the Google Drive will appear when you click on File|Open notebook: Select the colab_itils.ipynb file: Click on Runtime|Change runtime type: to provision an Nvidia GPU: The status of provisioning the Nvidia GPU is checked with: The from tensorflow.python.client import device_libdevice_lib.list_local_devices() Output: [name: "/device:CPU:0" device_type: "CPU" memory_limit: 268435456 locality { } incarnation: 17311008600223054265, name: "/device:GPU:0" device_type: "GPU" memory_limit: 14674281152 locality { bus_id: 1 links { } } incarnation: 7680686309919727928 physical_device_desc: "device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5"] An Nvidia Telsa T4 with 14.67 GB of fast memory is provided. To provision a Google TPU, select TPU in the “Notebook settings”: In this short article, I showed how: You can get any public file from a GitHub repository.You can load, edit, and save any .ipynb file to the Google Drive associated with the Colab login. You can get any public file from a GitHub repository. You can load, edit, and save any .ipynb file to the Google Drive associated with the Colab login. 3. You can provision one of many generations of the NVIDIA GPU. 4. You can provision one of many generations of the Google TPU. One critical capability with Google Colab is that team members can collaborate on a project using shared files on GitHub. Also, each team member can create their development sandbox on their own Google Drive. The cloud empowers remote work. Happy coding!
[ { "code": null, "e": 351, "s": 172, "text": "You can use the Jupyter Notebook on your local computer. Google Colab improves on the Jupyter Notebook in many ways. Here are the seven most powerful reasons to use Google Colab:" }, { "code": null, "e": 609, "s": 351, "text": "You can get any public Jupyter Notebook from a GitHub repository.You load, edit, and save any .ipynbfile to the Google Drive associated with the Colab login. It is helpful to have a separate Google account for each project and thus a different Google Drive." }, { "code": null, "e": 675, "s": 609, "text": "You can get any public Jupyter Notebook from a GitHub repository." }, { "code": null, "e": 868, "s": 675, "text": "You load, edit, and save any .ipynbfile to the Google Drive associated with the Colab login. It is helpful to have a separate Google account for each project and thus a different Google Drive." }, { "code": null, "e": 1125, "s": 868, "text": "Note: You can create a Git account for any project folder on Google Drive. Each team member hosts on a variety of different local computers. All they need is a browser and internet connection. Your team can be fully distributed geographically by the cloud." }, { "code": null, "e": 1189, "s": 1125, "text": "3. You can provision one of many generations of the NVIDIA GPU." }, { "code": null, "e": 1253, "s": 1189, "text": "4. You can provision one of many generations of the Google TPU." }, { "code": null, "e": 1292, "s": 1253, "text": "5. You can provision a multi-core CPU." }, { "code": null, "e": 1400, "s": 1292, "text": "6. Google Colab is free. Also, you can upgrade to a premium version that costs $9.99 per month per account." }, { "code": null, "e": 1470, "s": 1400, "text": "7. A Colab notebook has many useful extensions of a Jupyter Notebook." }, { "code": null, "e": 1569, "s": 1470, "text": "In a browser, head to https://colab.research.google.com. A new tab pointing to Google Colab opens:" }, { "code": null, "e": 1700, "s": 1569, "text": "If you are new to Colab, the only file in Recent is Welcome to Collaboratory. As I am not new, you can count five files in Recent." }, { "code": null, "e": 1729, "s": 1700, "text": "Click on GitHub and observe:" }, { "code": null, "e": 1826, "s": 1729, "text": "Enter the GitHub account you want to browse. I entered bcottman, my GitHub top-level repository." }, { "code": null, "e": 1918, "s": 1826, "text": "From the repo bcottman/paso, I chose the file bcottman/paso/integration_test_pre_all.ipynb." }, { "code": null, "e": 2053, "s": 1918, "text": "This results in the file bcottman/paso/integration_test_pre_all.ipynb being loaded into the GCP (Google Cloud Platform) Colab browser." }, { "code": null, "e": 2315, "s": 2053, "text": "You can create a Google Drive and then create a Git account for any project folder. You are going to https://colab.research.google.com. Mount the Google Drive of the Google account. All files in the Google Drive will appear when you click on File|Open notebook:" }, { "code": null, "e": 2350, "s": 2315, "text": "Select the colab_itils.ipynb file:" }, { "code": null, "e": 2416, "s": 2350, "text": "Click on Runtime|Change runtime type: to provision an Nvidia GPU:" }, { "code": null, "e": 2475, "s": 2416, "text": "The status of provisioning the Nvidia GPU is checked with:" }, { "code": null, "e": 2558, "s": 2475, "text": "The from tensorflow.python.client import device_libdevice_lib.list_local_devices()" }, { "code": null, "e": 2566, "s": 2558, "text": "Output:" }, { "code": null, "e": 2939, "s": 2566, "text": "[name: \"/device:CPU:0\" device_type: \"CPU\" memory_limit: 268435456 locality { } incarnation: 17311008600223054265, name: \"/device:GPU:0\" device_type: \"GPU\" memory_limit: 14674281152 locality { bus_id: 1 links { } } incarnation: 7680686309919727928 physical_device_desc: \"device: 0, name: Tesla T4, pci bus id: 0000:00:04.0, compute capability: 7.5\"]" }, { "code": null, "e": 3000, "s": 2939, "text": "An Nvidia Telsa T4 with 14.67 GB of fast memory is provided." }, { "code": null, "e": 3066, "s": 3000, "text": "To provision a Google TPU, select TPU in the “Notebook settings”:" }, { "code": null, "e": 3103, "s": 3066, "text": "In this short article, I showed how:" }, { "code": null, "e": 3254, "s": 3103, "text": "You can get any public file from a GitHub repository.You can load, edit, and save any .ipynb file to the Google Drive associated with the Colab login." }, { "code": null, "e": 3308, "s": 3254, "text": "You can get any public file from a GitHub repository." }, { "code": null, "e": 3406, "s": 3308, "text": "You can load, edit, and save any .ipynb file to the Google Drive associated with the Colab login." }, { "code": null, "e": 3470, "s": 3406, "text": "3. You can provision one of many generations of the NVIDIA GPU." }, { "code": null, "e": 3534, "s": 3470, "text": "4. You can provision one of many generations of the Google TPU." }, { "code": null, "e": 3743, "s": 3534, "text": "One critical capability with Google Colab is that team members can collaborate on a project using shared files on GitHub. Also, each team member can create their development sandbox on their own Google Drive." } ]
XAML Vs C# Code
You can use XAML to create, initialize, and set the properties of objects. The same activities can also be performed using programming code. XAML is just another simple and easy way to design UI elements. With XAML, it is up to you to decide whether you want to declare objects in XAML or declare them using code. Let’s take a simple example to demonstrate how to write in XAML − <Window x:Class = "XAMLVsCode.MainWindow" xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" Title = "MainWindow" Height = "350" Width = "525"> <StackPanel> <TextBlock Text = "Welcome to XAML Tutorial" Height = "20" Width = "200" Margin = "5"/> <Button Content = "Ok" Height = "20" Width = "60" Margin = "5"/> </StackPanel> </Window> In this example, we have created a stack panel with a Button and a Text block and defined some of the properties of button and text block such as Height, Width, and Margin. When the above code is compiled and executed, it will produce the following output − Now look at the same code which is written in C#. using System; using System.Text; using System.Windows; using System.Windows.Controls; namespace XAMLVsCode { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // Create the StackPanel StackPanel stackPanel = new StackPanel(); this.Content = stackPanel; // Create the TextBlock TextBlock textBlock = new TextBlock(); textBlock.Text = "Welcome to XAML Tutorial"; textBlock.Height = 20; textBlock.Width = 200; textBlock.Margin = new Thickness(5); stackPanel.Children.Add(textBlock); // Create the Button Button button = new Button(); button.Content = "OK"; button.Height = 20; button.Width = 50; button.Margin = new Thickness(20); stackPanel.Children.Add(button); } } } When the above code is compiled and executed, it will produce the following output. Note that it is exactly the same as the output of XAML code. Now you can see that how simple it is to use and understand XAML. Print Add Notes Bookmark this page
[ { "code": null, "e": 2064, "s": 1923, "text": "You can use XAML to create, initialize, and set the properties of objects. The same activities can also be performed using programming code." }, { "code": null, "e": 2237, "s": 2064, "text": "XAML is just another simple and easy way to design UI elements. With XAML, it is up to you to decide whether you want to declare objects in XAML or declare them using code." }, { "code": null, "e": 2303, "s": 2237, "text": "Let’s take a simple example to demonstrate how to write in XAML −" }, { "code": null, "e": 2744, "s": 2303, "text": "<Window x:Class = \"XAMLVsCode.MainWindow\"\n xmlns = \"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x = \"http://schemas.microsoft.com/winfx/2006/xaml\" Title = \"MainWindow\" Height = \"350\" Width = \"525\"> \n\t\n <StackPanel> \n <TextBlock Text = \"Welcome to XAML Tutorial\" Height = \"20\" Width = \"200\" Margin = \"5\"/>\n <Button Content = \"Ok\" Height = \"20\" Width = \"60\" Margin = \"5\"/> \n </StackPanel> \n\t\n</Window> " }, { "code": null, "e": 3002, "s": 2744, "text": "In this example, we have created a stack panel with a Button and a Text block and defined some of the properties of button and text block such as Height, Width, and Margin. When the above code is compiled and executed, it will produce the following output −" }, { "code": null, "e": 3052, "s": 3002, "text": "Now look at the same code which is written in C#." }, { "code": null, "e": 4070, "s": 3052, "text": "using System; \nusing System.Text; \nusing System.Windows; \nusing System.Windows.Controls; \n\nnamespace XAMLVsCode { \n /// <summary> \n /// Interaction logic for MainWindow.xaml \n /// </summary> \n\t\n public partial class MainWindow : Window {\n public MainWindow() { \n InitializeComponent(); \n \n // Create the StackPanel \n StackPanel stackPanel = new StackPanel();\n this.Content = stackPanel; \n\t\t\t\n // Create the TextBlock \n TextBlock textBlock = new TextBlock(); \n textBlock.Text = \"Welcome to XAML Tutorial\"; \n textBlock.Height = 20;\n textBlock.Width = 200; \n textBlock.Margin = new Thickness(5); \n stackPanel.Children.Add(textBlock); \n\t\t\t\n // Create the Button \n Button button = new Button(); \n button.Content = \"OK\"; \n button.Height = 20; \n button.Width = 50; \n button.Margin = new Thickness(20); \n stackPanel.Children.Add(button); \n } \n }\n}" }, { "code": null, "e": 4215, "s": 4070, "text": "When the above code is compiled and executed, it will produce the following output. Note that it is exactly the same as the output of XAML code." }, { "code": null, "e": 4281, "s": 4215, "text": "Now you can see that how simple it is to use and understand XAML." }, { "code": null, "e": 4288, "s": 4281, "text": " Print" }, { "code": null, "e": 4299, "s": 4288, "text": " Add Notes" } ]
Bandit - A Wargame For Linux Beginners - GeeksforGeeks
22 Jan, 2021 The Bandit is a wargame for those who are beginners at Linux/UNIX environment and are facing problems while learning the real-time use of Linux commands. The game will teach the basics of Linux and will make you compatible to play even other wargames. This game basically provides you the environment which is similar to real-time with files having data the same as used in real time. Basically, the game starts with level 0. Then to proceed further you have to visit the Official Game Website and there is a hint for every level would be given. What you have to do is just go through the hint, find the password for the next level using that hint and proceed further. And to get the password you will have to use Linux Commands which will help you in understanding the Linux commands easily. 1. Open Terminal and Enter the following command. $ssh bandit0@bandit.labs.overthewire.org -p 2220 It will ask for a password Enter password -> bandit0 2. After entering the password you will be connected to the server of the game. Now enter the following command $ls $cat readme 3. It will give you the password for the next level. The highlighted text in the image is the password for the next level. Now, after getting your first level done, use the exit command to exit the current level. Similarly, continue with the game, now to connect to level 1 use the following command. $ssh bandit1@bandit.labs.overthewire.org -p 2220 It will ask for the password. Enter the password we get from level 0. Bravo! You are in the game. Meanwhile, you will face some problems but keep going you will rock the game and will master Linux commands. shreya18bit1140 Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. nohup Command in Linux with Examples scp command in Linux with Examples Thread functions in C/C++ SED command in Linux | Set 2 mv command in Linux with examples Docker - COPY Instruction chown command in Linux with Examples Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting nslookup command in Linux with Examples
[ { "code": null, "e": 24430, "s": 24402, "text": "\n22 Jan, 2021" }, { "code": null, "e": 25225, "s": 24430, "text": "The Bandit is a wargame for those who are beginners at Linux/UNIX environment and are facing problems while learning the real-time use of Linux commands. The game will teach the basics of Linux and will make you compatible to play even other wargames. This game basically provides you the environment which is similar to real-time with files having data the same as used in real time. Basically, the game starts with level 0. Then to proceed further you have to visit the Official Game Website and there is a hint for every level would be given. What you have to do is just go through the hint, find the password for the next level using that hint and proceed further. And to get the password you will have to use Linux Commands which will help you in understanding the Linux commands easily. " }, { "code": null, "e": 25277, "s": 25225, "text": "1. Open Terminal and Enter the following command. " }, { "code": null, "e": 25326, "s": 25277, "text": "$ssh bandit0@bandit.labs.overthewire.org -p 2220" }, { "code": null, "e": 25354, "s": 25326, "text": "It will ask for a password " }, { "code": null, "e": 25380, "s": 25354, "text": "Enter password -> bandit0" }, { "code": null, "e": 25461, "s": 25380, "text": "2. After entering the password you will be connected to the server of the game. " }, { "code": null, "e": 25494, "s": 25461, "text": "Now enter the following command " }, { "code": null, "e": 25510, "s": 25494, "text": "$ls\n$cat readme" }, { "code": null, "e": 25634, "s": 25510, "text": "3. It will give you the password for the next level. The highlighted text in the image is the password for the next level. " }, { "code": null, "e": 25813, "s": 25634, "text": "Now, after getting your first level done, use the exit command to exit the current level. Similarly, continue with the game, now to connect to level 1 use the following command. " }, { "code": null, "e": 25862, "s": 25813, "text": "$ssh bandit1@bandit.labs.overthewire.org -p 2220" }, { "code": null, "e": 26070, "s": 25862, "text": "It will ask for the password. Enter the password we get from level 0. Bravo! You are in the game. Meanwhile, you will face some problems but keep going you will rock the game and will master Linux commands. " }, { "code": null, "e": 26086, "s": 26070, "text": "shreya18bit1140" }, { "code": null, "e": 26097, "s": 26086, "text": "Linux-Unix" }, { "code": null, "e": 26195, "s": 26097, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26232, "s": 26195, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 26267, "s": 26232, "text": "scp command in Linux with Examples" }, { "code": null, "e": 26293, "s": 26267, "text": "Thread functions in C/C++" }, { "code": null, "e": 26322, "s": 26293, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 26356, "s": 26322, "text": "mv command in Linux with examples" }, { "code": null, "e": 26382, "s": 26356, "text": "Docker - COPY Instruction" }, { "code": null, "e": 26419, "s": 26382, "text": "chown command in Linux with Examples" }, { "code": null, "e": 26459, "s": 26419, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 26494, "s": 26459, "text": "Basic Operators in Shell Scripting" } ]
Finding minimum absolute difference within a Binary Search Tree in JavaScript
We are required to write a JavaScript function that takes in the root of a BST that holds some numerical data like this − 1 \ 3 / 2 The function should return the minimum absolute difference between any two nodes of the tree. For example − For the above tree, the output should be − const output = 1; because |1 - 2| = |3 - 2| = 1 The code for this will be − Live Demo class Node{ constructor(data) { this.data = data; this.left = null; this.right = null; }; }; class BinarySearchTree{ constructor(){ // root of a binary seach tree this.root = null; } insert(data){ var newNode = new Node(data); if(this.root === null){ this.root = newNode; }else{ this.insertNode(this.root, newNode); }; }; insertNode(node, newNode){ if(newNode.data < node.data){ if(node.left === null){ node.left = newNode; }else{ this.insertNode(node.left, newNode); }; } else { if(node.right === null){ node.right = newNode; }else{ this.insertNode(node.right,newNode); }; }; }; }; const BST = new BinarySearchTree(); BST.insert(1); BST.insert(3); BST.insert(2); const getMinimumDifference = function(root) { const nodes = []; const dfs = (root) => { if(root) { dfs(root.left); nodes.push(root.data); dfs(root.right); }; }; dfs(root); let result = nodes[1] - nodes[0]; for(let i = 1; i < nodes.length - 1; i++) { result = Math.min(result, nodes[i + 1] - nodes[i]); }; return result; }; console.log(getMinimumDifference(BST.root)); And the output in the console will be − 1
[ { "code": null, "e": 1184, "s": 1062, "text": "We are required to write a JavaScript function that takes in the root of a BST that holds some numerical data like this −" }, { "code": null, "e": 1194, "s": 1184, "text": "1\n\\\n3\n/\n2" }, { "code": null, "e": 1288, "s": 1194, "text": "The function should return the minimum absolute difference between any two nodes of the tree." }, { "code": null, "e": 1302, "s": 1288, "text": "For example −" }, { "code": null, "e": 1345, "s": 1302, "text": "For the above tree, the output should be −" }, { "code": null, "e": 1363, "s": 1345, "text": "const output = 1;" }, { "code": null, "e": 1393, "s": 1363, "text": "because |1 - 2| = |3 - 2| = 1" }, { "code": null, "e": 1421, "s": 1393, "text": "The code for this will be −" }, { "code": null, "e": 1432, "s": 1421, "text": " Live Demo" }, { "code": null, "e": 2749, "s": 1432, "text": "class Node{\n constructor(data) {\n this.data = data;\n this.left = null;\n this.right = null;\n };\n};\nclass BinarySearchTree{\n constructor(){\n // root of a binary seach tree\n this.root = null;\n }\n insert(data){\n var newNode = new Node(data);\n if(this.root === null){\n this.root = newNode;\n }else{\n this.insertNode(this.root, newNode);\n };\n };\n insertNode(node, newNode){\n if(newNode.data < node.data){\n if(node.left === null){\n node.left = newNode;\n }else{\n this.insertNode(node.left, newNode);\n };\n } else {\n if(node.right === null){\n node.right = newNode;\n }else{\n this.insertNode(node.right,newNode);\n };\n };\n };\n};\nconst BST = new BinarySearchTree();\nBST.insert(1);\nBST.insert(3);\nBST.insert(2);\nconst getMinimumDifference = function(root) {\n const nodes = [];\n const dfs = (root) => {\n if(root) {\n dfs(root.left);\n nodes.push(root.data);\n dfs(root.right);\n };\n };\n dfs(root);\n let result = nodes[1] - nodes[0];\n for(let i = 1; i < nodes.length - 1; i++) {\n result = Math.min(result, nodes[i + 1] - nodes[i]);\n };\n return result;\n};\nconsole.log(getMinimumDifference(BST.root));" }, { "code": null, "e": 2789, "s": 2749, "text": "And the output in the console will be −" }, { "code": null, "e": 2791, "s": 2789, "text": "1" } ]
List add() Method in Java with Examples - GeeksforGeeks
02 Jan, 2019 This method of List interface is used to append the specified element in argument to the end of the list. Syntax: boolean add(E e) Parameters: This function has a single parameter, i.e, e – element to be appended to this list. Returns: It returns true if the specified element is appended and list changes. Below programs show the implementation of this method. Program 1: // Java code to show the implementation of// add method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { List<Integer> l = new ArrayList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); }} [10, 15, 20] Program 2: Below is the code to show implementation of list.add() using Linkedlist. // Java code to show the implementation of// add method in list interface using LinkedListimport java.util.*;public class CollectionsDemo { // Driver code public static void main(String[] args) { List<Integer> ll = new LinkedList<>(); ll.add(100); ll.add(200); ll.add(300); ll.add(400); ll.add(500); System.out.println(ll); }} [100, 200, 300, 400, 500] Reference:Oracle Docs Java - util package Java-Collections Java-Functions java-list Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java Multidimensional Arrays in Java Stream In Java Stack Class in Java Singleton Class in Java Set in Java Overriding in Java Collections in Java
[ { "code": null, "e": 24418, "s": 24390, "text": "\n02 Jan, 2019" }, { "code": null, "e": 24524, "s": 24418, "text": "This method of List interface is used to append the specified element in argument to the end of the list." }, { "code": null, "e": 24532, "s": 24524, "text": "Syntax:" }, { "code": null, "e": 24549, "s": 24532, "text": "boolean add(E e)" }, { "code": null, "e": 24645, "s": 24549, "text": "Parameters: This function has a single parameter, i.e, e – element to be appended to this list." }, { "code": null, "e": 24725, "s": 24645, "text": "Returns: It returns true if the specified element is appended and list changes." }, { "code": null, "e": 24780, "s": 24725, "text": "Below programs show the implementation of this method." }, { "code": null, "e": 24791, "s": 24780, "text": "Program 1:" }, { "code": "// Java code to show the implementation of// add method in list interfaceimport java.util.*;public class GfG { // Driver code public static void main(String[] args) { List<Integer> l = new ArrayList<>(); l.add(10); l.add(15); l.add(20); System.out.println(l); }}", "e": 25103, "s": 24791, "text": null }, { "code": null, "e": 25117, "s": 25103, "text": "[10, 15, 20]\n" }, { "code": null, "e": 25201, "s": 25117, "text": "Program 2: Below is the code to show implementation of list.add() using Linkedlist." }, { "code": "// Java code to show the implementation of// add method in list interface using LinkedListimport java.util.*;public class CollectionsDemo { // Driver code public static void main(String[] args) { List<Integer> ll = new LinkedList<>(); ll.add(100); ll.add(200); ll.add(300); ll.add(400); ll.add(500); System.out.println(ll); }}", "e": 25595, "s": 25201, "text": null }, { "code": null, "e": 25622, "s": 25595, "text": "[100, 200, 300, 400, 500]\n" }, { "code": null, "e": 25644, "s": 25622, "text": "Reference:Oracle Docs" }, { "code": null, "e": 25664, "s": 25644, "text": "Java - util package" }, { "code": null, "e": 25681, "s": 25664, "text": "Java-Collections" }, { "code": null, "e": 25696, "s": 25681, "text": "Java-Functions" }, { "code": null, "e": 25706, "s": 25696, "text": "java-list" }, { "code": null, "e": 25711, "s": 25706, "text": "Java" }, { "code": null, "e": 25716, "s": 25711, "text": "Java" }, { "code": null, "e": 25733, "s": 25716, "text": "Java-Collections" }, { "code": null, "e": 25831, "s": 25733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25863, "s": 25831, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 25893, "s": 25863, "text": "HashMap in Java with Examples" }, { "code": null, "e": 25912, "s": 25893, "text": "Interfaces in Java" }, { "code": null, "e": 25944, "s": 25912, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 25959, "s": 25944, "text": "Stream In Java" }, { "code": null, "e": 25979, "s": 25959, "text": "Stack Class in Java" }, { "code": null, "e": 26003, "s": 25979, "text": "Singleton Class in Java" }, { "code": null, "e": 26015, "s": 26003, "text": "Set in Java" }, { "code": null, "e": 26034, "s": 26015, "text": "Overriding in Java" } ]
Print all possible strings of length k that can be formed from a set of n characters
28 May, 2022 Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set. Examples: Input: set[] = {'a', 'b'}, k = 3 Output: aaa aab aba abb baa bab bba bbb Input: set[] = {'a', 'b', 'c', 'd'}, k = 1 Output: a b c d For a given set of size n, there will be n^k possible strings of length k. The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for k equals to k-1. Below is the implementation of above idea : C++ Java Python3 C# Javascript // C++ program to print all// possible strings of length k#include <bits/stdc++.h>using namespace std; // The main recursive method// to print all possible// strings of length kvoid printAllKLengthRec(char set[], string prefix, int n, int k){ // Base case: k is 0, // print prefix if (k == 0) { cout << (prefix) << endl; return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (int i = 0; i < n; i++) { string newPrefix; // Next character of input added newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); } } void printAllKLength(char set[], int k,int n){ printAllKLengthRec(set, "", n, k);} // Driver Codeint main(){ cout << "First Test" << endl; char set1[] = {'a', 'b'}; int k = 3; printAllKLength(set1, k, 2); cout << "Second Test\n"; char set2[] = {'a', 'b', 'c', 'd'}; k = 1; printAllKLength(set2, k, 4);} // This code is contributed// by Mohit kumar // Java program to print all// possible strings of length k class GFG { // The method that prints all// possible strings of length k.// It is mainly a wrapper over// recursive function printAllKLengthRec()static void printAllKLength(char[] set, int k){ int n = set.length; printAllKLengthRec(set, "", n, k);} // The main recursive method// to print all possible// strings of length kstatic void printAllKLengthRec(char[] set, String prefix, int n, int k){ // Base case: k is 0, // print prefix if (k == 0) { System.out.println(prefix); return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (int i = 0; i < n; ++i) { // Next character of input added String newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); }} // Driver Codepublic static void main(String[] args){ System.out.println("First Test"); char[] set1 = {'a', 'b'}; int k = 3; printAllKLength(set1, k); System.out.println("\nSecond Test"); char[] set2 = {'a', 'b', 'c', 'd'}; k = 1; printAllKLength(set2, k);}} # Python 3 program to print all# possible strings of length k # The method that prints all# possible strings of length k.# It is mainly a wrapper over# recursive function printAllKLengthRec()def printAllKLength(set, k): n = len(set) printAllKLengthRec(set, "", n, k) # The main recursive method# to print all possible# strings of length kdef printAllKLengthRec(set, prefix, n, k): # Base case: k is 0, # print prefix if (k == 0) : print(prefix) return # One by one add all characters # from set and recursively # call for k equals to k-1 for i in range(n): # Next character of input added newPrefix = prefix + set[i] # k is decreased, because # we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1) # Driver Codeif __name__ == "__main__": print("First Test") set1 = ['a', 'b'] k = 3 printAllKLength(set1, k) print("\nSecond Test") set2 = ['a', 'b', 'c', 'd'] k = 1 printAllKLength(set2, k) # This code is contributed# by ChitraNayal // C# program to print all// possible strings of length kusing System; class GFG { // The method that prints all// possible strings of length k.// It is mainly a wrapper over// recursive function printAllKLengthRec()static void printAllKLength(char[] set, int k){ int n = set.Length; printAllKLengthRec(set, "", n, k);} // The main recursive method// to print all possible// strings of length kstatic void printAllKLengthRec(char[] set, String prefix, int n, int k){ // Base case: k is 0, // print prefix if (k == 0) { Console.WriteLine(prefix); return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (int i = 0; i < n; ++i) { // Next character of input added String newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); }} // Driver Codestatic public void Main (){ Console.WriteLine("First Test"); char[] set1 = {'a', 'b'}; int k = 3; printAllKLength(set1, k); Console.WriteLine("\nSecond Test"); char[] set2 = {'a', 'b', 'c', 'd'}; k = 1; printAllKLength(set2, k);}} // This code is contributed by Ajit. <script>// Javascript program to print all// possible strings of length k // The method that prints all // possible strings of length k. // It is mainly a wrapper over // recursive function printAllKLengthRec() function printAllKLength(set,k) { let n = set.length; printAllKLengthRec(set, "", n, k); } // The main recursive method // to print all possible // strings of length k function printAllKLengthRec(set,prefix,n,k) { // Base case: k is 0, // print prefix if (k == 0) { document.write(prefix+"<br>"); return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (let i = 0; i < n; ++i) { // Next character of input added let newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); } } // Driver Code document.write("First Test<br>"); let set1=['a', 'b']; let k = 3; printAllKLength(set1, k); document.write("<br>Second Test<br>"); let set2 = ['a', 'b', 'c', 'd']; k = 1; printAllKLength(set2, k); // This code is contributed by avanitrachhadiya2155 </script> Output: First Test aaa aab aba abb baa bab bba bbb Second Test a b c d Time complexity: O(nk) Auxiliary Space: O(k) The above solution is mainly a generalization of this post. This article is contributed by Abhinav Ramana. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t ukasp mohit kumar 29 avanitrachhadiya2155 surinderdawra388 surbhikumaridav combionatrics Java-String-Programs Combinatorial Java Recursion Recursion Java Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 May, 2022" }, { "code": null, "e": 184, "s": 54, "text": "Given a set of characters and a positive integer k, print all possible strings of length k that can be formed from the given set." }, { "code": null, "e": 194, "s": 184, "text": "Examples:" }, { "code": null, "e": 331, "s": 194, "text": "Input: \nset[] = {'a', 'b'}, k = 3\n\nOutput:\naaa\naab\naba\nabb\nbaa\nbab\nbba\nbbb\n\n\nInput: \nset[] = {'a', 'b', 'c', 'd'}, k = 1\nOutput:\na\nb\nc\nd" }, { "code": null, "e": 654, "s": 331, "text": "For a given set of size n, there will be n^k possible strings of length k. The idea is to start from an empty output string (we call it prefix in following code). One by one add all characters to prefix. For every character added, print all possible strings with current prefix by recursively calling for k equals to k-1. " }, { "code": null, "e": 699, "s": 654, "text": "Below is the implementation of above idea : " }, { "code": null, "e": 703, "s": 699, "text": "C++" }, { "code": null, "e": 708, "s": 703, "text": "Java" }, { "code": null, "e": 716, "s": 708, "text": "Python3" }, { "code": null, "e": 719, "s": 716, "text": "C#" }, { "code": null, "e": 730, "s": 719, "text": "Javascript" }, { "code": "// C++ program to print all// possible strings of length k#include <bits/stdc++.h>using namespace std; // The main recursive method// to print all possible// strings of length kvoid printAllKLengthRec(char set[], string prefix, int n, int k){ // Base case: k is 0, // print prefix if (k == 0) { cout << (prefix) << endl; return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (int i = 0; i < n; i++) { string newPrefix; // Next character of input added newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); } } void printAllKLength(char set[], int k,int n){ printAllKLengthRec(set, \"\", n, k);} // Driver Codeint main(){ cout << \"First Test\" << endl; char set1[] = {'a', 'b'}; int k = 3; printAllKLength(set1, k, 2); cout << \"Second Test\\n\"; char set2[] = {'a', 'b', 'c', 'd'}; k = 1; printAllKLength(set2, k, 4);} // This code is contributed// by Mohit kumar", "e": 1908, "s": 730, "text": null }, { "code": "// Java program to print all// possible strings of length k class GFG { // The method that prints all// possible strings of length k.// It is mainly a wrapper over// recursive function printAllKLengthRec()static void printAllKLength(char[] set, int k){ int n = set.length; printAllKLengthRec(set, \"\", n, k);} // The main recursive method// to print all possible// strings of length kstatic void printAllKLengthRec(char[] set, String prefix, int n, int k){ // Base case: k is 0, // print prefix if (k == 0) { System.out.println(prefix); return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (int i = 0; i < n; ++i) { // Next character of input added String newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); }} // Driver Codepublic static void main(String[] args){ System.out.println(\"First Test\"); char[] set1 = {'a', 'b'}; int k = 3; printAllKLength(set1, k); System.out.println(\"\\nSecond Test\"); char[] set2 = {'a', 'b', 'c', 'd'}; k = 1; printAllKLength(set2, k);}}", "e": 3238, "s": 1908, "text": null }, { "code": "# Python 3 program to print all# possible strings of length k # The method that prints all# possible strings of length k.# It is mainly a wrapper over# recursive function printAllKLengthRec()def printAllKLength(set, k): n = len(set) printAllKLengthRec(set, \"\", n, k) # The main recursive method# to print all possible# strings of length kdef printAllKLengthRec(set, prefix, n, k): # Base case: k is 0, # print prefix if (k == 0) : print(prefix) return # One by one add all characters # from set and recursively # call for k equals to k-1 for i in range(n): # Next character of input added newPrefix = prefix + set[i] # k is decreased, because # we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1) # Driver Codeif __name__ == \"__main__\": print(\"First Test\") set1 = ['a', 'b'] k = 3 printAllKLength(set1, k) print(\"\\nSecond Test\") set2 = ['a', 'b', 'c', 'd'] k = 1 printAllKLength(set2, k) # This code is contributed# by ChitraNayal", "e": 4323, "s": 3238, "text": null }, { "code": "// C# program to print all// possible strings of length kusing System; class GFG { // The method that prints all// possible strings of length k.// It is mainly a wrapper over// recursive function printAllKLengthRec()static void printAllKLength(char[] set, int k){ int n = set.Length; printAllKLengthRec(set, \"\", n, k);} // The main recursive method// to print all possible// strings of length kstatic void printAllKLengthRec(char[] set, String prefix, int n, int k){ // Base case: k is 0, // print prefix if (k == 0) { Console.WriteLine(prefix); return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (int i = 0; i < n; ++i) { // Next character of input added String newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); }} // Driver Codestatic public void Main (){ Console.WriteLine(\"First Test\"); char[] set1 = {'a', 'b'}; int k = 3; printAllKLength(set1, k); Console.WriteLine(\"\\nSecond Test\"); char[] set2 = {'a', 'b', 'c', 'd'}; k = 1; printAllKLength(set2, k);}} // This code is contributed by Ajit.", "e": 5686, "s": 4323, "text": null }, { "code": "<script>// Javascript program to print all// possible strings of length k // The method that prints all // possible strings of length k. // It is mainly a wrapper over // recursive function printAllKLengthRec() function printAllKLength(set,k) { let n = set.length; printAllKLengthRec(set, \"\", n, k); } // The main recursive method // to print all possible // strings of length k function printAllKLengthRec(set,prefix,n,k) { // Base case: k is 0, // print prefix if (k == 0) { document.write(prefix+\"<br>\"); return; } // One by one add all characters // from set and recursively // call for k equals to k-1 for (let i = 0; i < n; ++i) { // Next character of input added let newPrefix = prefix + set[i]; // k is decreased, because // we have added a new character printAllKLengthRec(set, newPrefix, n, k - 1); } } // Driver Code document.write(\"First Test<br>\"); let set1=['a', 'b']; let k = 3; printAllKLength(set1, k); document.write(\"<br>Second Test<br>\"); let set2 = ['a', 'b', 'c', 'd']; k = 1; printAllKLength(set2, k); // This code is contributed by avanitrachhadiya2155 </script>", "e": 7101, "s": 5686, "text": null }, { "code": null, "e": 7110, "s": 7101, "text": "Output: " }, { "code": null, "e": 7174, "s": 7110, "text": "First Test\naaa\naab\naba\nabb\nbaa\nbab\nbba\nbbb\n\nSecond Test\na\nb\nc\nd" }, { "code": null, "e": 7197, "s": 7174, "text": "Time complexity: O(nk)" }, { "code": null, "e": 7219, "s": 7197, "text": "Auxiliary Space: O(k)" }, { "code": null, "e": 7279, "s": 7219, "text": "The above solution is mainly a generalization of this post." }, { "code": null, "e": 7451, "s": 7279, "text": "This article is contributed by Abhinav Ramana. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 7457, "s": 7451, "text": "jit_t" }, { "code": null, "e": 7463, "s": 7457, "text": "ukasp" }, { "code": null, "e": 7478, "s": 7463, "text": "mohit kumar 29" }, { "code": null, "e": 7499, "s": 7478, "text": "avanitrachhadiya2155" }, { "code": null, "e": 7516, "s": 7499, "text": "surinderdawra388" }, { "code": null, "e": 7532, "s": 7516, "text": "surbhikumaridav" }, { "code": null, "e": 7546, "s": 7532, "text": "combionatrics" }, { "code": null, "e": 7567, "s": 7546, "text": "Java-String-Programs" }, { "code": null, "e": 7581, "s": 7567, "text": "Combinatorial" }, { "code": null, "e": 7586, "s": 7581, "text": "Java" }, { "code": null, "e": 7596, "s": 7586, "text": "Recursion" }, { "code": null, "e": 7606, "s": 7596, "text": "Recursion" }, { "code": null, "e": 7611, "s": 7606, "text": "Java" }, { "code": null, "e": 7625, "s": 7611, "text": "Combinatorial" } ]
Check Armstrong Number in PL/SQL
04 Jul, 2018 Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if. abcd... = pow(a, n) + pow(b, n) + pow(c, n) + pow(d, n) + .... Example: Input : 153 Output : Yes 153 is an Armstrong number. 1*1*1 + 5*5*5 + 3*3*3 = 153 Input : 120 Output : No 120 is not a Armstrong number. 1*1*1 + 2*2*2 + 0*0*0 = 9 Input : 1253 Output : No 1253 is not a Armstrong Number 1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723 Input : 1634 Output : Yes 1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634 declare-- declare variable n, s,r, len-- and m of datatype number n number:=1634; s number:=0; r number; len number; m number; begin m := n; len := length(to_char(n)); -- while loop till n>0 while n>0 loop r := mod(n , 10); s := s + power(r , len); n := trunc(n / 10); end loop; if m = s then dbms_output.put_line('yes'); else dbms_output.put_line('no'); end if; end; -- End program output: Yes SQL-PL/SQL SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Sub queries in From Clause Window functions in SQL What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT RANK() Function in SQL Server How to Import JSON Data into SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jul, 2018" }, { "code": null, "e": 213, "s": 28, "text": "Given a number x, determine whether the given number is Armstrong number or not. A positive integer of n digits is called an Armstrong number of order n (order is number of digits) if." }, { "code": null, "e": 277, "s": 213, "text": "abcd... = pow(a, n) + pow(b, n) + pow(c, n) + pow(d, n) + .... " }, { "code": null, "e": 286, "s": 277, "text": "Example:" }, { "code": null, "e": 622, "s": 286, "text": "Input : 153\nOutput : Yes\n153 is an Armstrong number.\n1*1*1 + 5*5*5 + 3*3*3 = 153\n\nInput : 120\nOutput : No\n120 is not a Armstrong number.\n1*1*1 + 2*2*2 + 0*0*0 = 9\n\nInput : 1253\nOutput : No\n1253 is not a Armstrong Number\n1*1*1*1 + 2*2*2*2 + 5*5*5*5 + 3*3*3*3 = 723\n\nInput : 1634\nOutput : Yes\n1*1*1*1 + 6*6*6*6 + 3*3*3*3 + 4*4*4*4 = 1634" }, { "code": "declare-- declare variable n, s,r, len-- and m of datatype number n number:=1634; s number:=0; r number; len number; m number; begin m := n; len := length(to_char(n)); -- while loop till n>0 while n>0 loop r := mod(n , 10); s := s + power(r , len); n := trunc(n / 10); end loop; if m = s then dbms_output.put_line('yes'); else dbms_output.put_line('no'); end if; end; -- End program", "e": 1106, "s": 622, "text": null }, { "code": null, "e": 1114, "s": 1106, "text": "output:" }, { "code": null, "e": 1118, "s": 1114, "text": "Yes" }, { "code": null, "e": 1129, "s": 1118, "text": "SQL-PL/SQL" }, { "code": null, "e": 1133, "s": 1129, "text": "SQL" }, { "code": null, "e": 1137, "s": 1133, "text": "SQL" }, { "code": null, "e": 1235, "s": 1137, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1301, "s": 1235, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1334, "s": 1301, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1358, "s": 1334, "text": "Window functions in SQL" }, { "code": null, "e": 1390, "s": 1358, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1468, "s": 1390, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1485, "s": 1468, "text": "SQL using Python" }, { "code": null, "e": 1521, "s": 1485, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1551, "s": 1521, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1592, "s": 1551, "text": "How to Import JSON Data into SQL Server?" } ]
Retrieve elements from Python Set
18 Jan, 2022 Prerequisites: Python Set In this article, we will discuss how to retrieve elements from the sets in Python. By iterating the elements in a set using for loop we can get them all set elements. Example: Python3 # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # display set elements using for loopfor i in data: print(i) print("----") # create a set with string elementsdata1 = {"sravan", "harsha", "jyothika"} # display set elements using for loopfor i in data1: print(i) Output: 7072 7074 7076 7058 7059 ---- sravan harsha jyothika In set we can not perform indexing, first, we have to convert that set into a list and then perform the indexing. So we are using list() function to convert the set into the list. Example: Python3 # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve 1 st elementprint(list(data)[0]) # retrieve 4 th elementprint(list(data)[3]) # retrieve last elementprint(list(data)[-1]) Output: 7072 7058 7059 We can convert it into a list and then access the last element by using pop() function. This will get the last element or we can also use index = -1 to get the last element. Example: Python3 # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve last elementprint(list(data)[-1]) # retrieve last elementprint(list(data).pop()) Output: 7076 7076 We can access the first item in the set by using iter() function, we have to apply next() to it to get the first element. Syntax: next(iter(set)) Example: Python3 # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve first elementprint(next(iter(data))) Output: 7058 We can also use first() method from the iteration_utilities module, Which will return the first element. Syntax: first(set) Example: Python3 # import iteration_utilitiesfrom iteration_utilities import first # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve first elementprint(first(data)) Output: 7058 We can get n number of random elements from a set using sample() function. This is available in a random module and this will return a list of sample elements. Example: Python3 # import random moduleimport random # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve 2 random elementsprint(random.sample(data, 2)) # retrieve 1 random elementprint(random.sample(data, 1)) # retrieve 4 random elementsprint(random.sample(data, 4)) Output: [7058, 7074] [7072] [7059, 7074, 7058, 7076] gulshankumarar231 Picked python-set Python python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jan, 2022" }, { "code": null, "e": 54, "s": 28, "text": "Prerequisites: Python Set" }, { "code": null, "e": 137, "s": 54, "text": "In this article, we will discuss how to retrieve elements from the sets in Python." }, { "code": null, "e": 221, "s": 137, "text": "By iterating the elements in a set using for loop we can get them all set elements." }, { "code": null, "e": 230, "s": 221, "text": "Example:" }, { "code": null, "e": 238, "s": 230, "text": "Python3" }, { "code": "# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # display set elements using for loopfor i in data: print(i) print(\"----\") # create a set with string elementsdata1 = {\"sravan\", \"harsha\", \"jyothika\"} # display set elements using for loopfor i in data1: print(i)", "e": 531, "s": 238, "text": null }, { "code": null, "e": 539, "s": 531, "text": "Output:" }, { "code": null, "e": 592, "s": 539, "text": "7072\n7074\n7076\n7058\n7059\n----\nsravan\nharsha\njyothika" }, { "code": null, "e": 772, "s": 592, "text": "In set we can not perform indexing, first, we have to convert that set into a list and then perform the indexing. So we are using list() function to convert the set into the list." }, { "code": null, "e": 781, "s": 772, "text": "Example:" }, { "code": null, "e": 789, "s": 781, "text": "Python3" }, { "code": "# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve 1 st elementprint(list(data)[0]) # retrieve 4 th elementprint(list(data)[3]) # retrieve last elementprint(list(data)[-1])", "e": 998, "s": 789, "text": null }, { "code": null, "e": 1006, "s": 998, "text": "Output:" }, { "code": null, "e": 1021, "s": 1006, "text": "7072\n7058\n7059" }, { "code": null, "e": 1195, "s": 1021, "text": "We can convert it into a list and then access the last element by using pop() function. This will get the last element or we can also use index = -1 to get the last element." }, { "code": null, "e": 1204, "s": 1195, "text": "Example:" }, { "code": null, "e": 1212, "s": 1204, "text": "Python3" }, { "code": "# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve last elementprint(list(data)[-1]) # retrieve last elementprint(list(data).pop())", "e": 1378, "s": 1212, "text": null }, { "code": null, "e": 1386, "s": 1378, "text": "Output:" }, { "code": null, "e": 1396, "s": 1386, "text": "7076\n7076" }, { "code": null, "e": 1518, "s": 1396, "text": "We can access the first item in the set by using iter() function, we have to apply next() to it to get the first element." }, { "code": null, "e": 1542, "s": 1518, "text": "Syntax: next(iter(set))" }, { "code": null, "e": 1551, "s": 1542, "text": "Example:" }, { "code": null, "e": 1559, "s": 1551, "text": "Python3" }, { "code": "# create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve first elementprint(next(iter(data)))", "e": 1682, "s": 1559, "text": null }, { "code": null, "e": 1690, "s": 1682, "text": "Output:" }, { "code": null, "e": 1695, "s": 1690, "text": "7058" }, { "code": null, "e": 1800, "s": 1695, "text": "We can also use first() method from the iteration_utilities module, Which will return the first element." }, { "code": null, "e": 1819, "s": 1800, "text": "Syntax: first(set)" }, { "code": null, "e": 1828, "s": 1819, "text": "Example:" }, { "code": null, "e": 1836, "s": 1828, "text": "Python3" }, { "code": "# import iteration_utilitiesfrom iteration_utilities import first # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve first elementprint(first(data))", "e": 2020, "s": 1836, "text": null }, { "code": null, "e": 2028, "s": 2020, "text": "Output:" }, { "code": null, "e": 2033, "s": 2028, "text": "7058" }, { "code": null, "e": 2193, "s": 2033, "text": "We can get n number of random elements from a set using sample() function. This is available in a random module and this will return a list of sample elements." }, { "code": null, "e": 2202, "s": 2193, "text": "Example:" }, { "code": null, "e": 2210, "s": 2202, "text": "Python3" }, { "code": "# import random moduleimport random # create a set with integer elementsdata = {7058, 7059, 7072, 7074, 7076} # retrieve 2 random elementsprint(random.sample(data, 2)) # retrieve 1 random elementprint(random.sample(data, 1)) # retrieve 4 random elementsprint(random.sample(data, 4))", "e": 2494, "s": 2210, "text": null }, { "code": null, "e": 2502, "s": 2494, "text": "Output:" }, { "code": null, "e": 2547, "s": 2502, "text": "[7058, 7074]\n[7072]\n[7059, 7074, 7058, 7076]" }, { "code": null, "e": 2565, "s": 2547, "text": "gulshankumarar231" }, { "code": null, "e": 2572, "s": 2565, "text": "Picked" }, { "code": null, "e": 2583, "s": 2572, "text": "python-set" }, { "code": null, "e": 2590, "s": 2583, "text": "Python" }, { "code": null, "e": 2601, "s": 2590, "text": "python-set" } ]
Python | Consecutive elements pairing in list
18 May, 2020 Sometimes, while working with lists, we need to pair up the like elements in the list and then store them as lists of lists. This particular task has its utility in many domains, be it web development or day-day programming. Let’s discuss certain ways in which this can be achieved. Method #1 : Using list comprehensionThe list comprehension can be easily used to perform this particular task, but consecutively making the pairs of i’th and (i+1)th element. # Python3 code to demonstrate# consecutive element pairing # using list comprehension # initializing listtest_list = [5, 4, 1, 3, 2] # printing original listprint("The original list : " + str(test_list)) # using list comprehension# consecutive element pairing res = [[test_list[i], test_list[i + 1]] for i in range(len(test_list) - 1)] # print resultprint("The consecutive element paired list is : " + str(res)) The original list : [5, 4, 1, 3, 2] The consecutive element paired list is : [[5, 4], [4, 1], [1, 3], [3, 2]] Method # 2: Using zip()This task can also be achieved using only the zip function which performs the task for all the elements. # Python3 code to demonstrate# consecutive element pairing # using zip() # initializing listtest_list = [5, 4, 1, 3, 2] # printing original listprint("The original list : " + str(test_list)) # using zip()# consecutive element pairing res = list(zip(test_list, test_list[1:])) # print resultprint("The consecutive element paired list is : " + str(res)) The original list : [5, 4, 1, 3, 2] The consecutive element paired list is : [[5, 4], [4, 1], [1, 3], [3, 2]] mvdream02 Python list-programs python-list Python Python Programs python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Enumerate() in Python Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 54, "s": 26, "text": "\n18 May, 2020" }, { "code": null, "e": 337, "s": 54, "text": "Sometimes, while working with lists, we need to pair up the like elements in the list and then store them as lists of lists. This particular task has its utility in many domains, be it web development or day-day programming. Let’s discuss certain ways in which this can be achieved." }, { "code": null, "e": 512, "s": 337, "text": "Method #1 : Using list comprehensionThe list comprehension can be easily used to perform this particular task, but consecutively making the pairs of i’th and (i+1)th element." }, { "code": "# Python3 code to demonstrate# consecutive element pairing # using list comprehension # initializing listtest_list = [5, 4, 1, 3, 2] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension# consecutive element pairing res = [[test_list[i], test_list[i + 1]] for i in range(len(test_list) - 1)] # print resultprint(\"The consecutive element paired list is : \" + str(res))", "e": 935, "s": 512, "text": null }, { "code": null, "e": 1051, "s": 935, "text": " \nThe original list : [5, 4, 1, 3, 2]\nThe consecutive element paired list is : [[5, 4], [4, 1], [1, 3], [3, 2]]\n" }, { "code": null, "e": 1181, "s": 1053, "text": "Method # 2: Using zip()This task can also be achieved using only the zip function which performs the task for all the elements." }, { "code": "# Python3 code to demonstrate# consecutive element pairing # using zip() # initializing listtest_list = [5, 4, 1, 3, 2] # printing original listprint(\"The original list : \" + str(test_list)) # using zip()# consecutive element pairing res = list(zip(test_list, test_list[1:])) # print resultprint(\"The consecutive element paired list is : \" + str(res))", "e": 1537, "s": 1181, "text": null }, { "code": null, "e": 1653, "s": 1537, "text": " \nThe original list : [5, 4, 1, 3, 2]\nThe consecutive element paired list is : [[5, 4], [4, 1], [1, 3], [3, 2]]\n" }, { "code": null, "e": 1663, "s": 1653, "text": "mvdream02" }, { "code": null, "e": 1684, "s": 1663, "text": "Python list-programs" }, { "code": null, "e": 1696, "s": 1684, "text": "python-list" }, { "code": null, "e": 1703, "s": 1696, "text": "Python" }, { "code": null, "e": 1719, "s": 1703, "text": "Python Programs" }, { "code": null, "e": 1731, "s": 1719, "text": "python-list" }, { "code": null, "e": 1829, "s": 1731, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1847, "s": 1829, "text": "Python Dictionary" }, { "code": null, "e": 1869, "s": 1847, "text": "Enumerate() in Python" }, { "code": null, "e": 1911, "s": 1869, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1946, "s": 1911, "text": "Read a file line by line in Python" }, { "code": null, "e": 1978, "s": 1946, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2021, "s": 1978, "text": "Python program to convert a list to string" }, { "code": null, "e": 2043, "s": 2021, "text": "Defaultdict in Python" }, { "code": null, "e": 2082, "s": 2043, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2120, "s": 2082, "text": "Python | Convert a list to dictionary" } ]
Object.seal( ) In JavaScript
09 Nov, 2021 Object and Object Constructors in JavaScript? In the living world of object-oriented programming, we already know the importance of classes and objects but unlike other programming languages, JavaScript does not have the traditional classes as seen in other languages. But JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations. Constructors are general JavaScript functions that are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects). Constructors can be useful when we need a way to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions. For instance, consider the following code: Javascript function Automobile(color) { this.color=color;} var vehicle1 = new Automobile ("red"); The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things: It creates a fresh new object(instance) Automobile() and assigns it to a variable.It sets the constructor property i.e “color” of the object to Automobile. It creates a fresh new object(instance) Automobile() and assigns it to a variable. It sets the constructor property i.e “color” of the object to Automobile. Object.seal() Method Among the Object constructor methods, there is a method Object.seal() which is used to seal an object. Sealing an object does not allow new properties to be added and marks all existing properties as non-configurable. Although values of present properties can be changed as long as they are writable. The object to be sealed is passed as an argument and the method returns the object which has been sealed. Difference between Object.freeze() Method and Object.seal() Method If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the Object.seal() method then the changes can be made `in the existing properties of the object. Applications: Object.seal() is used for sealing objects and arrays. Object.seal() is used to make an object immutable. Syntax: Object.seal(obj) Parameters Used: obj : It is the object which has to be sealed. obj : It is the object which has to be sealed. Return Value: Object.sealed() returns the object that was passed to the function. Examples of the above function are provided below. Examples: Input : const obj1 = { property1: 'initial_data'}; const obj2 = Object.seal(obj1); obj2.property1 = 'new_data'; console.log(obj2.property1); Output : "new_data" Explanation: In this example, the object “ob2” has been assigned properties of object “obj1” and it is been sealed so that new values cannot be added. The value of property 1 for obj2 has been updated since sealing an object allows existent properties to be changed. Input : var obj = { prop: function() {}, name: 'adam' }; console.log(obj); obj.name = 'billy'; delete obj.prop; console.log(obj); var o = Object.seal(obj); delete obj.prop; console.log(obj); obj.name = 'chris'; console.log(obj); Output : Object { prop: function () {}, name: "adam" } Object { name: "billy" } Object { name: "billy" } Object { name: "chris" } Explanation: In this example, the object “obj” has been assigned “prop: function” which has been later deleted since the object “obj wasn’t sealed. After that, a new object “o” has been assigned the sealed values of “obj” which prevented it from deletion but allowed updations in the existing properties. Codes for the above function are provided below. Code 1: Javascript <script>// creating an object constructor and assigning values to itconst obj1 = { property1: 'initial_data'}; // creating a second object which will seal the properties of the first objectconst obj2 = Object.seal(obj1); // Updating the properties of the frozen objectobj2.property1 = 'new_data'; // Displaying the properties of the frozen objectconsole.log(obj2.property1);</script> OUTPUT: "new_data" Code 2: Javascript <script>// creating an object constructor and assigning values to itvar obj = { prop: function() {}, name: 'adam' }; // Displaying the properties of the object createdconsole.log(obj); // Updating the properties of the objectobj.name = 'billy';delete obj.prop; // Displaying the updated properties of the objectconsole.log(obj); // Sealing the object using object.seal() methodvar o = Object.seal(obj); // Updating the properties of the objectdelete obj.prop; // Displaying the updated properties of the objectconsole.log(obj); // Updating the properties of the sealed objectobj.name = 'chris'; // Displaying the properties of the frozen objectconsole.log(obj); </script> OUTPUT: Object { prop: function () {}, name: "adam" } Object { name: "billy" } Object { name: "billy" } Object { name: "chris" } Exceptions: It causes a TypeError if the argument passed is not an object. Deleting or adding properties to a sealed object will fail or throw a TypeError. Converting a data property to accessor or its vice versa will throw a TypeError. Supported Browsers: Google Chrome 6.0 and above Internet Explorer 9.0 and above Mozilla 4.0 and above Opera 12 and above Safari 5.0 and above Edge 12 and above Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal ysachin2314 clintra javascript-functions javascript-object JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? How to get character array from string in JavaScript? JavaScript | console.log() with Examples JavaScript | Promises
[ { "code": null, "e": 54, "s": 26, "text": "\n09 Nov, 2021" }, { "code": null, "e": 442, "s": 54, "text": "Object and Object Constructors in JavaScript? In the living world of object-oriented programming, we already know the importance of classes and objects but unlike other programming languages, JavaScript does not have the traditional classes as seen in other languages. But JavaScript has objects and constructors which work mostly in the same way to perform the same kind of operations. " }, { "code": null, "e": 692, "s": 442, "text": "Constructors are general JavaScript functions that are used with the “new” keyword. Constructors are of two types in JavaScript i.e. built-in constructors(array and object) and custom constructors(define properties and methods for specific objects)." }, { "code": null, "e": 1013, "s": 692, "text": "Constructors can be useful when we need a way to create an object “type” that can be used multiple times without having to redefine the object every time and this could be achieved using the Object Constructor function. It’s a convention to capitalize the name of constructors to distinguish them from regular functions." }, { "code": null, "e": 1057, "s": 1013, "text": "For instance, consider the following code: " }, { "code": null, "e": 1068, "s": 1057, "text": "Javascript" }, { "code": "function Automobile(color) { this.color=color;} var vehicle1 = new Automobile (\"red\");", "e": 1156, "s": 1068, "text": null }, { "code": null, "e": 1470, "s": 1156, "text": "The function “Automobile()” is an object constructor, and its properties and methods i.e “color” is declared inside it by prefixing it with the keyword “this”. Objects defined using an object constructor are then made instants using the keyword “new”. When new Automobile() is called, JavaScript does two things: " }, { "code": null, "e": 1626, "s": 1470, "text": "It creates a fresh new object(instance) Automobile() and assigns it to a variable.It sets the constructor property i.e “color” of the object to Automobile." }, { "code": null, "e": 1709, "s": 1626, "text": "It creates a fresh new object(instance) Automobile() and assigns it to a variable." }, { "code": null, "e": 1783, "s": 1709, "text": "It sets the constructor property i.e “color” of the object to Automobile." }, { "code": null, "e": 2211, "s": 1783, "text": "Object.seal() Method Among the Object constructor methods, there is a method Object.seal() which is used to seal an object. Sealing an object does not allow new properties to be added and marks all existing properties as non-configurable. Although values of present properties can be changed as long as they are writable. The object to be sealed is passed as an argument and the method returns the object which has been sealed." }, { "code": null, "e": 2278, "s": 2211, "text": "Difference between Object.freeze() Method and Object.seal() Method" }, { "code": null, "e": 2540, "s": 2278, "text": "If an object is frozen using the Object.freeze() method then its properties become immutable and no changes can be made in them whereas if an object is sealed using the Object.seal() method then the changes can be made `in the existing properties of the object." }, { "code": null, "e": 2555, "s": 2540, "text": "Applications: " }, { "code": null, "e": 2609, "s": 2555, "text": "Object.seal() is used for sealing objects and arrays." }, { "code": null, "e": 2660, "s": 2609, "text": "Object.seal() is used to make an object immutable." }, { "code": null, "e": 2669, "s": 2660, "text": "Syntax: " }, { "code": null, "e": 2686, "s": 2669, "text": "Object.seal(obj)" }, { "code": null, "e": 2704, "s": 2686, "text": "Parameters Used: " }, { "code": null, "e": 2751, "s": 2704, "text": "obj : It is the object which has to be sealed." }, { "code": null, "e": 2798, "s": 2751, "text": "obj : It is the object which has to be sealed." }, { "code": null, "e": 2881, "s": 2798, "text": "Return Value: Object.sealed() returns the object that was passed to the function. " }, { "code": null, "e": 2932, "s": 2881, "text": "Examples of the above function are provided below." }, { "code": null, "e": 2943, "s": 2932, "text": "Examples: " }, { "code": null, "e": 3129, "s": 2943, "text": "Input : const obj1 = { property1: 'initial_data'};\n const obj2 = Object.seal(obj1);\n obj2.property1 = 'new_data';\n console.log(obj2.property1);\n\nOutput : \"new_data\"" }, { "code": null, "e": 3397, "s": 3129, "text": "Explanation: In this example, the object “ob2” has been assigned properties of object “obj1” and it is been sealed so that new values cannot be added. The value of property 1 for obj2 has been updated since sealing an object allows existent properties to be changed. " }, { "code": null, "e": 3856, "s": 3397, "text": "Input : var obj = { prop: function() {}, name: 'adam' };\n console.log(obj);\n obj.name = 'billy';\n delete obj.prop;\n console.log(obj);\n var o = Object.seal(obj);\n delete obj.prop;\n console.log(obj);\n obj.name = 'chris';\n console.log(obj);\n\nOutput : Object { prop: function () {}, name: \"adam\" }\n Object { name: \"billy\" }\n Object { name: \"billy\" }\n Object { name: \"chris\" }" }, { "code": null, "e": 4161, "s": 3856, "text": "Explanation: In this example, the object “obj” has been assigned “prop: function” which has been later deleted since the object “obj wasn’t sealed. After that, a new object “o” has been assigned the sealed values of “obj” which prevented it from deletion but allowed updations in the existing properties." }, { "code": null, "e": 4210, "s": 4161, "text": "Codes for the above function are provided below." }, { "code": null, "e": 4219, "s": 4210, "text": "Code 1: " }, { "code": null, "e": 4230, "s": 4219, "text": "Javascript" }, { "code": "<script>// creating an object constructor and assigning values to itconst obj1 = { property1: 'initial_data'}; // creating a second object which will seal the properties of the first objectconst obj2 = Object.seal(obj1); // Updating the properties of the frozen objectobj2.property1 = 'new_data'; // Displaying the properties of the frozen objectconsole.log(obj2.property1);</script>", "e": 4615, "s": 4230, "text": null }, { "code": null, "e": 4624, "s": 4615, "text": "OUTPUT: " }, { "code": null, "e": 4635, "s": 4624, "text": "\"new_data\"" }, { "code": null, "e": 4644, "s": 4635, "text": "Code 2: " }, { "code": null, "e": 4655, "s": 4644, "text": "Javascript" }, { "code": "<script>// creating an object constructor and assigning values to itvar obj = { prop: function() {}, name: 'adam' }; // Displaying the properties of the object createdconsole.log(obj); // Updating the properties of the objectobj.name = 'billy';delete obj.prop; // Displaying the updated properties of the objectconsole.log(obj); // Sealing the object using object.seal() methodvar o = Object.seal(obj); // Updating the properties of the objectdelete obj.prop; // Displaying the updated properties of the objectconsole.log(obj); // Updating the properties of the sealed objectobj.name = 'chris'; // Displaying the properties of the frozen objectconsole.log(obj); </script>", "e": 5328, "s": 4655, "text": null }, { "code": null, "e": 5337, "s": 5328, "text": "OUTPUT: " }, { "code": null, "e": 5458, "s": 5337, "text": "Object { prop: function () {}, name: \"adam\" }\nObject { name: \"billy\" }\nObject { name: \"billy\" }\nObject { name: \"chris\" }" }, { "code": null, "e": 5471, "s": 5458, "text": "Exceptions: " }, { "code": null, "e": 5534, "s": 5471, "text": "It causes a TypeError if the argument passed is not an object." }, { "code": null, "e": 5615, "s": 5534, "text": "Deleting or adding properties to a sealed object will fail or throw a TypeError." }, { "code": null, "e": 5696, "s": 5615, "text": "Converting a data property to accessor or its vice versa will throw a TypeError." }, { "code": null, "e": 5716, "s": 5696, "text": "Supported Browsers:" }, { "code": null, "e": 5744, "s": 5716, "text": "Google Chrome 6.0 and above" }, { "code": null, "e": 5776, "s": 5744, "text": "Internet Explorer 9.0 and above" }, { "code": null, "e": 5798, "s": 5776, "text": "Mozilla 4.0 and above" }, { "code": null, "e": 5817, "s": 5798, "text": "Opera 12 and above" }, { "code": null, "e": 5838, "s": 5817, "text": "Safari 5.0 and above" }, { "code": null, "e": 5856, "s": 5838, "text": "Edge 12 and above" }, { "code": null, "e": 5961, "s": 5856, "text": "Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/seal " }, { "code": null, "e": 5973, "s": 5961, "text": "ysachin2314" }, { "code": null, "e": 5981, "s": 5973, "text": "clintra" }, { "code": null, "e": 6002, "s": 5981, "text": "javascript-functions" }, { "code": null, "e": 6020, "s": 6002, "text": "javascript-object" }, { "code": null, "e": 6031, "s": 6020, "text": "JavaScript" }, { "code": null, "e": 6129, "s": 6031, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6190, "s": 6129, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 6262, "s": 6190, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 6302, "s": 6262, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 6344, "s": 6302, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 6385, "s": 6344, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 6437, "s": 6385, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 6483, "s": 6437, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 6537, "s": 6483, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 6578, "s": 6537, "text": "JavaScript | console.log() with Examples" } ]
Bootstrap-5 Forms
06 Jul, 2021 Form controls: <input>, <select>, <textarea> are the tags used for general appearance like input field, select item and textareas. Note: To make the user interface more presentable, use properties like padding, margins as per the need. Example: HTML <!DOCTYPE html><html> <head> <!-- CSS only --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"></head> <body class="container-sm mt-5"> <form> <h2 class="text-center"> Display Form Controls </h2> <div class="form-group"> <label>Email address</label> <input type="email" class="form-control" placeholder="geeks@example.com"> </div> <div class="form-group mt-2"> <label>Example select</label> <select class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class="form-group mt-2"> <label>Example textarea</label> <textarea class="form-control"></textarea> </div> </form></body> </html> Output: Notes: The class used for form control is .form-control. The size of form-control can be adjusted by using .form-control-lg and .form-control-sm Example: HTML <!DOCTYPE html><html> <head> <!-- CSS only --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"></head> <body class="container-sm mt-5"> <input class="form-control mt-3 form-control-lg" type="text" placeholder=".form-control-lg"> <input class="form-control mt-3" type="text" placeholder="Default input"> <input class="form-control mt-3 form-control-sm" type="text" placeholder=".form-control-sm"></body> </html> Output: The file input type can be defined with class .form-control-file Example: HTML <!DOCTYPE html><html> <head> <!-- CSS only --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"></head> <body class="container-sm mt-5"> <form> <div class="form-group"> <label>Example file input</label><br> <input type="file" class="form-control-file"> </div> </form></body> </html> Output: The range input type can be defined with class .form-control-range Example: HTML <!DOCTYPE html><html> <head> <title>Input Range</title> <!-- CSS only --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"></head> <body class="container-sm mt-5"> <form> <div class="form-group"> <label>Example Range input</label><br> <input type="range" class="form-control-range"> </div> </form></body> </html> Output: 2. Radios and checkboxes: The classes used for radios and checkboxes are .form-check. Example: HTML <!DOCTYPE html><html> <head> <title>Radios and CheckBoxes</title> <!-- CSS only --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"></head> <body class="container-sm mt-5"> <form> <div class="form-check"> <input class="form-check-input" type="checkbox"> <label class="form-check-label"> Default checkbox </label> </div> <div class="form-check"> <input class="form-check-input" type="radio"> <label class="form-check-label"> Default Unchecked Radio </label> </div> </form></body> </html> Output: 3. Horizontal Form: The class used for horizontal form is .form-row Example: HTML <!DOCTYPE html><html> <head> <title>Horizontal Form</title> <!-- CSS only --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css"></head> <body class="container-sm mt-5"> <form> <div class="form-row p-4"> <div class="col mt-2"> <input type="text" class="form-control" placeholder=" User Name"> </div> <div class="col mt-2"> <input type="password" class="form-control" placeholder=" Password"> </div> <div class="col-2 mt-2 "> <button class="btn btn-primary btn-block">Login</button> </div> </div> </form></body> </html> Output: Supported Browser: Google Chrome Internet Explorer Firefox Opera Safari ysachin2314 Bootstrap-Misc HTML-Misc Technical Scripter 2020 Bootstrap HTML Technical Scripter 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": "\n06 Jul, 2021" }, { "code": null, "e": 189, "s": 53, "text": "Form controls: <input>, <select>, <textarea> are the tags used for general appearance like input field, select item and textareas. " }, { "code": null, "e": 294, "s": 189, "text": "Note: To make the user interface more presentable, use properties like padding, margins as per the need." }, { "code": null, "e": 304, "s": 294, "text": "Example: " }, { "code": null, "e": 309, "s": 304, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css\"></head> <body class=\"container-sm mt-5\"> <form> <h2 class=\"text-center\"> Display Form Controls </h2> <div class=\"form-group\"> <label>Email address</label> <input type=\"email\" class=\"form-control\" placeholder=\"geeks@example.com\"> </div> <div class=\"form-group mt-2\"> <label>Example select</label> <select class=\"form-control\"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> <div class=\"form-group mt-2\"> <label>Example textarea</label> <textarea class=\"form-control\"></textarea> </div> </form></body> </html>", "e": 1292, "s": 309, "text": null }, { "code": null, "e": 1300, "s": 1292, "text": "Output:" }, { "code": null, "e": 1307, "s": 1300, "text": "Notes:" }, { "code": null, "e": 1357, "s": 1307, "text": "The class used for form control is .form-control." }, { "code": null, "e": 1446, "s": 1357, "text": "The size of form-control can be adjusted by using .form-control-lg and .form-control-sm " }, { "code": null, "e": 1455, "s": 1446, "text": "Example:" }, { "code": null, "e": 1460, "s": 1455, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css\"></head> <body class=\"container-sm mt-5\"> <input class=\"form-control mt-3 form-control-lg\" type=\"text\" placeholder=\".form-control-lg\"> <input class=\"form-control mt-3\" type=\"text\" placeholder=\"Default input\"> <input class=\"form-control mt-3 form-control-sm\" type=\"text\" placeholder=\".form-control-sm\"></body> </html>", "e": 1969, "s": 1460, "text": null }, { "code": null, "e": 1977, "s": 1969, "text": "Output:" }, { "code": null, "e": 2043, "s": 1977, "text": "The file input type can be defined with class .form-control-file" }, { "code": null, "e": 2052, "s": 2043, "text": "Example:" }, { "code": null, "e": 2057, "s": 2052, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css\"></head> <body class=\"container-sm mt-5\"> <form> <div class=\"form-group\"> <label>Example file input</label><br> <input type=\"file\" class=\"form-control-file\"> </div> </form></body> </html>", "e": 2448, "s": 2057, "text": null }, { "code": null, "e": 2456, "s": 2448, "text": "Output:" }, { "code": null, "e": 2523, "s": 2456, "text": "The range input type can be defined with class .form-control-range" }, { "code": null, "e": 2532, "s": 2523, "text": "Example:" }, { "code": null, "e": 2537, "s": 2532, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Input Range</title> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css\"></head> <body class=\"container-sm mt-5\"> <form> <div class=\"form-group\"> <label>Example Range input</label><br> <input type=\"range\" class=\"form-control-range\"> </div> </form></body> </html>", "e": 2989, "s": 2537, "text": null }, { "code": null, "e": 2997, "s": 2989, "text": "Output:" }, { "code": null, "e": 3083, "s": 2997, "text": "2. Radios and checkboxes: The classes used for radios and checkboxes are .form-check." }, { "code": null, "e": 3092, "s": 3083, "text": "Example:" }, { "code": null, "e": 3097, "s": 3092, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Radios and CheckBoxes</title> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css\"></head> <body class=\"container-sm mt-5\"> <form> <div class=\"form-check\"> <input class=\"form-check-input\" type=\"checkbox\"> <label class=\"form-check-label\"> Default checkbox </label> </div> <div class=\"form-check\"> <input class=\"form-check-input\" type=\"radio\"> <label class=\"form-check-label\"> Default Unchecked Radio </label> </div> </form></body> </html>", "e": 3825, "s": 3097, "text": null }, { "code": null, "e": 3833, "s": 3825, "text": "Output:" }, { "code": null, "e": 3901, "s": 3833, "text": "3. Horizontal Form: The class used for horizontal form is .form-row" }, { "code": null, "e": 3910, "s": 3901, "text": "Example:" }, { "code": null, "e": 3915, "s": 3910, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Horizontal Form</title> <!-- CSS only --> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css\"></head> <body class=\"container-sm mt-5\"> <form> <div class=\"form-row p-4\"> <div class=\"col mt-2\"> <input type=\"text\" class=\"form-control\" placeholder=\" User Name\"> </div> <div class=\"col mt-2\"> <input type=\"password\" class=\"form-control\" placeholder=\" Password\"> </div> <div class=\"col-2 mt-2 \"> <button class=\"btn btn-primary btn-block\">Login</button> </div> </div> </form></body> </html>", "e": 4730, "s": 3915, "text": null }, { "code": null, "e": 4738, "s": 4730, "text": "Output:" }, { "code": null, "e": 4757, "s": 4738, "text": "Supported Browser:" }, { "code": null, "e": 4771, "s": 4757, "text": "Google Chrome" }, { "code": null, "e": 4789, "s": 4771, "text": "Internet Explorer" }, { "code": null, "e": 4797, "s": 4789, "text": "Firefox" }, { "code": null, "e": 4803, "s": 4797, "text": "Opera" }, { "code": null, "e": 4810, "s": 4803, "text": "Safari" }, { "code": null, "e": 4822, "s": 4810, "text": "ysachin2314" }, { "code": null, "e": 4837, "s": 4822, "text": "Bootstrap-Misc" }, { "code": null, "e": 4847, "s": 4837, "text": "HTML-Misc" }, { "code": null, "e": 4871, "s": 4847, "text": "Technical Scripter 2020" }, { "code": null, "e": 4881, "s": 4871, "text": "Bootstrap" }, { "code": null, "e": 4886, "s": 4881, "text": "HTML" }, { "code": null, "e": 4905, "s": 4886, "text": "Technical Scripter" }, { "code": null, "e": 4922, "s": 4905, "text": "Web Technologies" }, { "code": null, "e": 4927, "s": 4922, "text": "HTML" } ]
GATE | Gate IT 2005 | Question 8
29 Mar, 2018 Using Booth’s Algorithm for multiplication, the multiplier -57 will be recoded as(A) 0 -1 0 0 1 0 0 -1(B) 1 1 0 0 0 1 1 1(C) 0 -1 0 0 1 0 0 0(D) 0 1 0 0 -1 0 0 1Answer: (A)Explanation: Booth’s algorithm: first take 2’s complement of given number if number is negative, then append 0 into LSB. Then, for each pair from LSB to MSB (add 1 bit at a time): 00 = 0, 01 = +1, 10 = -1, 11 = 0 Therefore, given number in signed representation (2’s complementation) of -57 = 2's complement of (00111001) = 11000110+1 = 11000111 = append 0 into LSB of (11000111) = 110001110 Now Booth's code (add 1 bit at a time, from LSB to MSB): = 11, 10, 00, 00, 01, 11, 11, 10 = 0 -1 0 0 1 0 0 -1 Alternative way –You can calculated decimal values in given options:(A) 0 -1 0 0 1 0 0 -1 = 0*(2^6) -1*(2^6) + 0*(2^5) + 0*(2^4) + 1*(2^3) + 0*(2^2) + 0*(2^1) -1*(2^0) = -2^6 + 2^3 – 2^0 = -64 +8 -1 = -57(B) 1 1 0 0 0 1 1 1 = 2^7 + 2^6 + 2^2 2^1 + 2^0 = 199(C) 0 -1 0 0 1 0 0 0 = -2^6 + 2^3 = -56(D) 0 1 0 0 -1 0 0 1 = 2^6 – 2^3 + 2^0 = 57 So, option (A) is correct.Quiz of this Question Gate IT 2005 GATE-Gate IT 2005 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | GATE-CS-2014-(Set-2) | Question 65 GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33 GATE | GATE-CS-2014-(Set-3) | Question 20 GATE | GATE-CS-2015 (Set 3) | Question 65 GATE | GATE-CS-2014-(Set-3) | Question 65 GATE | GATE CS 2008 | Question 46 GATE | GATE CS 1996 | Question 63 GATE | Gate IT 2005 | Question 52 GATE | GATE CS 2012 | Question 18 GATE | GATE-CS-2001 | Question 50
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Mar, 2018" }, { "code": null, "e": 321, "s": 28, "text": "Using Booth’s Algorithm for multiplication, the multiplier -57 will be recoded as(A) 0 -1 0 0 1 0 0 -1(B) 1 1 0 0 0 1 1 1(C) 0 -1 0 0 1 0 0 0(D) 0 1 0 0 -1 0 0 1Answer: (A)Explanation: Booth’s algorithm: first take 2’s complement of given number if number is negative, then append 0 into LSB." }, { "code": null, "e": 413, "s": 321, "text": "Then, for each pair from LSB to MSB (add 1 bit at a time):\n00 = 0, 01 = +1, 10 = -1, 11 = 0" }, { "code": null, "e": 491, "s": 413, "text": "Therefore, given number in signed representation (2’s complementation) of -57" }, { "code": null, "e": 702, "s": 491, "text": "= 2's complement of (00111001) = 11000110+1 = 11000111\n= append 0 into LSB of (11000111) = 110001110\nNow Booth's code (add 1 bit at a time, from LSB to MSB):\n= 11, 10, 00, 00, 01, 11, 11, 10 = 0 -1 0 0 1 0 0 -1" }, { "code": null, "e": 1042, "s": 702, "text": "Alternative way –You can calculated decimal values in given options:(A) 0 -1 0 0 1 0 0 -1 = 0*(2^6) -1*(2^6) + 0*(2^5) + 0*(2^4) + 1*(2^3) + 0*(2^2) + 0*(2^1) -1*(2^0) = -2^6 + 2^3 – 2^0 = -64 +8 -1 = -57(B) 1 1 0 0 0 1 1 1 = 2^7 + 2^6 + 2^2 2^1 + 2^0 = 199(C) 0 -1 0 0 1 0 0 0 = -2^6 + 2^3 = -56(D) 0 1 0 0 -1 0 0 1 = 2^6 – 2^3 + 2^0 = 57" }, { "code": null, "e": 1090, "s": 1042, "text": "So, option (A) is correct.Quiz of this Question" }, { "code": null, "e": 1103, "s": 1090, "text": "Gate IT 2005" }, { "code": null, "e": 1121, "s": 1103, "text": "GATE-Gate IT 2005" }, { "code": null, "e": 1126, "s": 1121, "text": "GATE" }, { "code": null, "e": 1224, "s": 1126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1266, "s": 1224, "text": "GATE | GATE-CS-2014-(Set-2) | Question 65" }, { "code": null, "e": 1328, "s": 1266, "text": "GATE | Sudo GATE 2020 Mock I (27 December 2019) | Question 33" }, { "code": null, "e": 1370, "s": 1328, "text": "GATE | GATE-CS-2014-(Set-3) | Question 20" }, { "code": null, "e": 1412, "s": 1370, "text": "GATE | GATE-CS-2015 (Set 3) | Question 65" }, { "code": null, "e": 1454, "s": 1412, "text": "GATE | GATE-CS-2014-(Set-3) | Question 65" }, { "code": null, "e": 1488, "s": 1454, "text": "GATE | GATE CS 2008 | Question 46" }, { "code": null, "e": 1522, "s": 1488, "text": "GATE | GATE CS 1996 | Question 63" }, { "code": null, "e": 1556, "s": 1522, "text": "GATE | Gate IT 2005 | Question 52" }, { "code": null, "e": 1590, "s": 1556, "text": "GATE | GATE CS 2012 | Question 18" } ]
Implementing Csurf Middleware in Node.js
16 Jun, 2021 Csurf module in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSRF token as a cookie. The token sent will be different for each request since they are generated randomly.Prerequisites An IDE of your choice NodeJs and NPM installed and setup in your system. Basic knowledge of Node.js modules and Embedded JavaScript(ejs). Installation: First, we need to initialize our application with package.json file. Therefore, write the following command in the terminal: First, we need to initialize our application with package.json file. Therefore, write the following command in the terminal: npm init After, the package.json is created, its time to install our dependencies. Therefore, Install the required dependencies by the following command: After, the package.json is created, its time to install our dependencies. Therefore, Install the required dependencies by the following command: npm install body-parser cookie-parser express csurf --save Cookie-parser is used to parse the incoming cookies. Body-parser is used to parse the incoming form data that we will be creating in a HTML file. Create a file and named as app.js and write the following code for requiring module: Filename: app.js Cookie-parser is used to parse the incoming cookies. Body-parser is used to parse the incoming form data that we will be creating in a HTML file. Create a file and named as app.js and write the following code for requiring module: Filename: app.js javascript const express = require('express');const csrf = require('csurf');const cookieParser = require('cookie-parser');const bodyParser = require('body-parser'); Here, csrf will act as a middleware for generating and validating CSRF cookies. This middleware will add a function for generating cookies. This function will be passed to requests through a hidden form field. This created cookie will be then validated when the users send requests. The middleware populates req.csrfToken(). Now after we have required all the modules, now let’s write down the full code as shown below: Filename: app.js Here, csrf will act as a middleware for generating and validating CSRF cookies. This middleware will add a function for generating cookies. This function will be passed to requests through a hidden form field. This created cookie will be then validated when the users send requests. The middleware populates req.csrfToken(). Now after we have required all the modules, now let’s write down the full code as shown below: Filename: app.js javascript const express = require('express');const csrf = require('csurf');const cookieParser = require('cookie-parser');const bodyParser = require('body-parser'); var csrfProtection = csrf({ cookie: true });var parseForm = bodyParser.urlencoded({ extended: false }); var app = express();app.set('view engine','ejs') app.use(cookieParser()); app.get('/form', csrfProtection, function (req, res) { // pass the csrfToken to the view res.render('login', { csrfToken: req.csrfToken() });}); app.post('/process', parseForm, csrfProtection, function (req, res) { res.send('Successfully Validated!!');}); app.listen(3000, (err) => { if (err) console.log(err); console.log('Server Running');}); In the above code, after importing the modules, we set up the route middlewares and pass the validation method as cookie instead of token. Body-parser is used to parse the data coming from the form. Since, cookie is used as the validation method, therefore, cookie-parser is used. Now, in the GET request, we are rendering the passed cookie value to the view. In the POST request, we are first validating the cookie and if validated, then we are sending a message. Now, create a folder and named as view and create a file and name it as login.ejs and write the following code in it: In the above code, after importing the modules, we set up the route middlewares and pass the validation method as cookie instead of token. Body-parser is used to parse the data coming from the form. Since, cookie is used as the validation method, therefore, cookie-parser is used. Now, in the GET request, we are rendering the passed cookie value to the view. In the POST request, we are first validating the cookie and if validated, then we are sending a message. Now, create a folder and named as view and create a file and name it as login.ejs and write the following code in it: html <html><head> <title>Csurf Middleware</title></head><body> <form action="process" method="POST"> <input type="hidden" name="_csrf" value="<%= csrfToken %>"> <input type="text" name="myname"> <input type="submit" value="Submit"> </form></body></html> The above code example will run just as a simple application but there will be an added extra security measure for preventing CSRF. Steps to run this program: Make sure you have installed express, csurf, cookie-parser, body-parser module with following command: Make sure you have installed express, csurf, cookie-parser, body-parser module with following command: npm install express npm install express npm install csurf npm install cookie-parser npm install body-parser Run index.js file with following command: Run index.js file with following command: node index.js Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below: Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below: After submitting the form, you will see the following output: After submitting the form, you will see the following output: Successfully Validated!! Conclusion: Csurf is a very useful node module for preventing Cross-Site Request Forgery attack. varshagumber28 Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jun, 2021" }, { "code": null, "e": 445, "s": 28, "text": "Csurf module in Node.js prevents the Cross-Site Request Forgery(CSRF) attack on an application. By using this module, when a browser renders up a page from the server, it sends a randomly generated string as a CSRF token. Therefore, when the POST request is performed, it will send the random CSRF token as a cookie. The token sent will be different for each request since they are generated randomly.Prerequisites " }, { "code": null, "e": 467, "s": 445, "text": "An IDE of your choice" }, { "code": null, "e": 518, "s": 467, "text": "NodeJs and NPM installed and setup in your system." }, { "code": null, "e": 583, "s": 518, "text": "Basic knowledge of Node.js modules and Embedded JavaScript(ejs)." }, { "code": null, "e": 599, "s": 583, "text": "Installation: " }, { "code": null, "e": 726, "s": 599, "text": "First, we need to initialize our application with package.json file. Therefore, write the following command in the terminal: " }, { "code": null, "e": 853, "s": 726, "text": "First, we need to initialize our application with package.json file. Therefore, write the following command in the terminal: " }, { "code": null, "e": 862, "s": 853, "text": "npm init" }, { "code": null, "e": 1010, "s": 862, "text": " After, the package.json is created, its time to install our dependencies. Therefore, Install the required dependencies by the following command: " }, { "code": null, "e": 1159, "s": 1012, "text": "After, the package.json is created, its time to install our dependencies. Therefore, Install the required dependencies by the following command: " }, { "code": null, "e": 1218, "s": 1159, "text": "npm install body-parser cookie-parser express csurf --save" }, { "code": null, "e": 1468, "s": 1218, "text": "Cookie-parser is used to parse the incoming cookies. Body-parser is used to parse the incoming form data that we will be creating in a HTML file. Create a file and named as app.js and write the following code for requiring module: Filename: app.js " }, { "code": null, "e": 1616, "s": 1468, "text": "Cookie-parser is used to parse the incoming cookies. Body-parser is used to parse the incoming form data that we will be creating in a HTML file. " }, { "code": null, "e": 1719, "s": 1616, "text": "Create a file and named as app.js and write the following code for requiring module: Filename: app.js " }, { "code": null, "e": 1730, "s": 1719, "text": "javascript" }, { "code": "const express = require('express');const csrf = require('csurf');const cookieParser = require('cookie-parser');const bodyParser = require('body-parser');", "e": 1884, "s": 1730, "text": null }, { "code": null, "e": 2324, "s": 1884, "text": "Here, csrf will act as a middleware for generating and validating CSRF cookies. This middleware will add a function for generating cookies. This function will be passed to requests through a hidden form field. This created cookie will be then validated when the users send requests. The middleware populates req.csrfToken(). Now after we have required all the modules, now let’s write down the full code as shown below: Filename: app.js " }, { "code": null, "e": 2651, "s": 2324, "text": "Here, csrf will act as a middleware for generating and validating CSRF cookies. This middleware will add a function for generating cookies. This function will be passed to requests through a hidden form field. This created cookie will be then validated when the users send requests. The middleware populates req.csrfToken(). " }, { "code": null, "e": 2765, "s": 2651, "text": "Now after we have required all the modules, now let’s write down the full code as shown below: Filename: app.js " }, { "code": null, "e": 2776, "s": 2765, "text": "javascript" }, { "code": "const express = require('express');const csrf = require('csurf');const cookieParser = require('cookie-parser');const bodyParser = require('body-parser'); var csrfProtection = csrf({ cookie: true });var parseForm = bodyParser.urlencoded({ extended: false }); var app = express();app.set('view engine','ejs') app.use(cookieParser()); app.get('/form', csrfProtection, function (req, res) { // pass the csrfToken to the view res.render('login', { csrfToken: req.csrfToken() });}); app.post('/process', parseForm, csrfProtection, function (req, res) { res.send('Successfully Validated!!');}); app.listen(3000, (err) => { if (err) console.log(err); console.log('Server Running');});", "e": 3471, "s": 2776, "text": null }, { "code": null, "e": 4056, "s": 3471, "text": "In the above code, after importing the modules, we set up the route middlewares and pass the validation method as cookie instead of token. Body-parser is used to parse the data coming from the form. Since, cookie is used as the validation method, therefore, cookie-parser is used. Now, in the GET request, we are rendering the passed cookie value to the view. In the POST request, we are first validating the cookie and if validated, then we are sending a message. Now, create a folder and named as view and create a file and name it as login.ejs and write the following code in it: " }, { "code": null, "e": 4523, "s": 4056, "text": "In the above code, after importing the modules, we set up the route middlewares and pass the validation method as cookie instead of token. Body-parser is used to parse the data coming from the form. Since, cookie is used as the validation method, therefore, cookie-parser is used. Now, in the GET request, we are rendering the passed cookie value to the view. In the POST request, we are first validating the cookie and if validated, then we are sending a message. " }, { "code": null, "e": 4642, "s": 4523, "text": "Now, create a folder and named as view and create a file and name it as login.ejs and write the following code in it: " }, { "code": null, "e": 4647, "s": 4642, "text": "html" }, { "code": "<html><head> <title>Csurf Middleware</title></head><body> <form action=\"process\" method=\"POST\"> <input type=\"hidden\" name=\"_csrf\" value=\"<%= csrfToken %>\"> <input type=\"text\" name=\"myname\"> <input type=\"submit\" value=\"Submit\"> </form></body></html>", "e": 4940, "s": 4647, "text": null }, { "code": null, "e": 5105, "s": 4944, "text": "The above code example will run just as a simple application but there will be an added extra security measure for preventing CSRF. Steps to run this program: " }, { "code": null, "e": 5210, "s": 5105, "text": "Make sure you have installed express, csurf, cookie-parser, body-parser module with following command: " }, { "code": null, "e": 5315, "s": 5210, "text": "Make sure you have installed express, csurf, cookie-parser, body-parser module with following command: " }, { "code": null, "e": 5423, "s": 5315, "text": "npm install express\nnpm install express\nnpm install csurf\nnpm install cookie-parser\nnpm install body-parser" }, { "code": null, "e": 5467, "s": 5423, "text": "Run index.js file with following command: " }, { "code": null, "e": 5511, "s": 5467, "text": "Run index.js file with following command: " }, { "code": null, "e": 5525, "s": 5511, "text": "node index.js" }, { "code": null, "e": 5645, "s": 5525, "text": "Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below: " }, { "code": null, "e": 5765, "s": 5645, "text": "Open the browser and go to http://localhost:3000/form, then you will see the form with an input field as shown below: " }, { "code": null, "e": 5830, "s": 5765, "text": " After submitting the form, you will see the following output: " }, { "code": null, "e": 5896, "s": 5832, "text": "After submitting the form, you will see the following output: " }, { "code": null, "e": 5921, "s": 5896, "text": "Successfully Validated!!" }, { "code": null, "e": 6023, "s": 5925, "text": "Conclusion: Csurf is a very useful node module for preventing Cross-Site Request Forgery attack. " }, { "code": null, "e": 6038, "s": 6023, "text": "varshagumber28" }, { "code": null, "e": 6051, "s": 6038, "text": "Node.js-Misc" }, { "code": null, "e": 6059, "s": 6051, "text": "Node.js" }, { "code": null, "e": 6076, "s": 6059, "text": "Web Technologies" } ]
Power Set in Lexicographic order
22 Jun, 2022 This article is about generating Power set in lexicographical order. Examples : Input : abc Output : a ab abc ac b bc c The idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last character so that next permutation can be generated. C++ Java Python3 C# PHP Javascript // CPP program to generate power set in// lexicographic order.#include <bits/stdc++.h>using namespace std; // str : Stores input string// n : Length of str.void func(string s, vector<string>& str, int n, int pow_set){ int i, j; for (i = 0; i < pow_set; i++) { string x; for (j = 0; j < n; j++) { if (i & 1 << j) { x = x + s[j]; } } if (i != 0) str.push_back(x); }}int main(){ int n; string s; vector<string> str; s = "cab"; n = s.length(); int pow_set = pow(2, n); func(s, str, n, pow_set); sort(str.begin(), str.end()); for (int i = 0; i < str.size(); i++) cout << str[i] << " "; cout << endl; return 0;} // Java program to generate power set in// lexicographic order.import java.util.*; class GFG { // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr static void permuteRec(String str, int n, int index, String curr) { // base case if (index == n) { return; } System.out.println(curr); for (int i = index + 1; i < n; i++) { curr += str.charAt(i); permuteRec(str, n, i, curr); // backtracking curr = curr.substring(0, curr.length() - 1); } return; } // Generates power set in lexicographic // order. static void powerSet(String str) { char[] arr = str.toCharArray(); Arrays.sort(arr); permuteRec(new String(arr), str.length(), -1, ""); } // Driver code public static void main(String[] args) { String str = "cab"; powerSet(str); }} /* This code contributed by PrinciRaj1992 */ # Python3 program to generate power# set in lexicographic order. # str : Stores input string# n : Length of str.# curr : Stores current permutation# index : Index in current permutation, currdef permuteRec(string, n, index = -1, curr = ""): # base case if index == n: return if len(curr) > 0: print(curr) for i in range(index + 1, n): curr += string[i] permuteRec(string, n, i, curr) # backtracking curr = curr[:len(curr) - 1] # Generates power set in lexicographic orderdef powerSet(string): string = ''.join(sorted(string)) permuteRec(string, len(string)) # Driver Codeif __name__ == "__main__": string = "cab" powerSet(string) # This code is contributed by vibhu4agarwal // C# program to generate power set in// lexicographic order.using System; class GFG { // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr static void permuteRec(String str, int n, int index, String curr) { // base case if (index == n) { return; } Console.WriteLine(curr); for (int i = index + 1; i < n; i++) { curr += str[i]; permuteRec(str, n, i, curr); // backtracking curr = curr.Substring(0, curr.Length - 1); } return; } // Generates power set in lexicographic // order. static void powerSet(String str) { char[] arr = str.ToCharArray(); Array.Sort(arr); permuteRec(new String(arr), str.Length, -1, ""); } // Driver code public static void Main(String[] args) { String str = "cab"; powerSet(str); }} // This code contributed by Rajput-Ji <?php// PHP program to generate power// set in lexicographic order. // str : Stores input string// n : Length of str.// curr : Stores current permutation// index : Index in current permutation, currfunction permuteRec($str, $n, $index = -1, $curr = ""){ // base case if ($index == $n) return; echo $curr."\n"; for ($i = $index + 1; $i < $n; $i++) { $curr=$curr.$str[$i]; permuteRec($str, $n, $i, $curr); // backtracking $curr =""; } return;} // Generates power set in lexicographic// order.function powerSet($str){ $str = str_split($str); sort($str); permuteRec($str, sizeof($str));} // Driver code$str = "cab";powerSet($str); // This code is contributed by Mithun Kumar?> <script>// javascript program to generate power set in// lexicographic order. // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr function permuteRec( str , n , index, curr) { // base case if (index == n) { return; } document.write(curr+" "); for (var i = index + 1; i < n; i++) { curr += str[i]; permuteRec(str, n, i, curr); // backtracking curr = curr.substring(0, curr.length - 1); } return; } // Generates power set in lexicographic // order. function powerSet(str) { var arr = str.split(""); arr.sort(); permuteRec(arr, str.length, -1, ""); } // Driver code var str = "cab"; powerSet(str); // This code contributed by umadevi9616</script> a ab b c ca cab cb Time Complexity: O(n*2n) Auxiliary Space: O(1) Mithun Kumar vibhu4agarwal princiraj1992 Rajput-Ji srivatsa vatsa maddler umadevi9616 youmailmahibagi Backtracking Recursion Strings Strings Recursion Backtracking Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 136, "s": 54, "text": "This article is about generating Power set in lexicographical order. Examples : " }, { "code": null, "e": 176, "s": 136, "text": "Input : abc\nOutput : a ab abc ac b bc c" }, { "code": null, "e": 408, "s": 178, "text": "The idea is to sort array first. After sorting, one by one fix characters and recursively generates all subsets starting from them. After every recursive call, we remove last character so that next permutation can be generated. " }, { "code": null, "e": 412, "s": 408, "text": "C++" }, { "code": null, "e": 417, "s": 412, "text": "Java" }, { "code": null, "e": 425, "s": 417, "text": "Python3" }, { "code": null, "e": 428, "s": 425, "text": "C#" }, { "code": null, "e": 432, "s": 428, "text": "PHP" }, { "code": null, "e": 443, "s": 432, "text": "Javascript" }, { "code": "// CPP program to generate power set in// lexicographic order.#include <bits/stdc++.h>using namespace std; // str : Stores input string// n : Length of str.void func(string s, vector<string>& str, int n, int pow_set){ int i, j; for (i = 0; i < pow_set; i++) { string x; for (j = 0; j < n; j++) { if (i & 1 << j) { x = x + s[j]; } } if (i != 0) str.push_back(x); }}int main(){ int n; string s; vector<string> str; s = \"cab\"; n = s.length(); int pow_set = pow(2, n); func(s, str, n, pow_set); sort(str.begin(), str.end()); for (int i = 0; i < str.size(); i++) cout << str[i] << \" \"; cout << endl; return 0;}", "e": 1175, "s": 443, "text": null }, { "code": "// Java program to generate power set in// lexicographic order.import java.util.*; class GFG { // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr static void permuteRec(String str, int n, int index, String curr) { // base case if (index == n) { return; } System.out.println(curr); for (int i = index + 1; i < n; i++) { curr += str.charAt(i); permuteRec(str, n, i, curr); // backtracking curr = curr.substring(0, curr.length() - 1); } return; } // Generates power set in lexicographic // order. static void powerSet(String str) { char[] arr = str.toCharArray(); Arrays.sort(arr); permuteRec(new String(arr), str.length(), -1, \"\"); } // Driver code public static void main(String[] args) { String str = \"cab\"; powerSet(str); }} /* This code contributed by PrinciRaj1992 */", "e": 2247, "s": 1175, "text": null }, { "code": "# Python3 program to generate power# set in lexicographic order. # str : Stores input string# n : Length of str.# curr : Stores current permutation# index : Index in current permutation, currdef permuteRec(string, n, index = -1, curr = \"\"): # base case if index == n: return if len(curr) > 0: print(curr) for i in range(index + 1, n): curr += string[i] permuteRec(string, n, i, curr) # backtracking curr = curr[:len(curr) - 1] # Generates power set in lexicographic orderdef powerSet(string): string = ''.join(sorted(string)) permuteRec(string, len(string)) # Driver Codeif __name__ == \"__main__\": string = \"cab\" powerSet(string) # This code is contributed by vibhu4agarwal", "e": 2991, "s": 2247, "text": null }, { "code": "// C# program to generate power set in// lexicographic order.using System; class GFG { // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr static void permuteRec(String str, int n, int index, String curr) { // base case if (index == n) { return; } Console.WriteLine(curr); for (int i = index + 1; i < n; i++) { curr += str[i]; permuteRec(str, n, i, curr); // backtracking curr = curr.Substring(0, curr.Length - 1); } return; } // Generates power set in lexicographic // order. static void powerSet(String str) { char[] arr = str.ToCharArray(); Array.Sort(arr); permuteRec(new String(arr), str.Length, -1, \"\"); } // Driver code public static void Main(String[] args) { String str = \"cab\"; powerSet(str); }} // This code contributed by Rajput-Ji", "e": 4035, "s": 2991, "text": null }, { "code": "<?php// PHP program to generate power// set in lexicographic order. // str : Stores input string// n : Length of str.// curr : Stores current permutation// index : Index in current permutation, currfunction permuteRec($str, $n, $index = -1, $curr = \"\"){ // base case if ($index == $n) return; echo $curr.\"\\n\"; for ($i = $index + 1; $i < $n; $i++) { $curr=$curr.$str[$i]; permuteRec($str, $n, $i, $curr); // backtracking $curr =\"\"; } return;} // Generates power set in lexicographic// order.function powerSet($str){ $str = str_split($str); sort($str); permuteRec($str, sizeof($str));} // Driver code$str = \"cab\";powerSet($str); // This code is contributed by Mithun Kumar?>", "e": 4806, "s": 4035, "text": null }, { "code": "<script>// javascript program to generate power set in// lexicographic order. // str : Stores input string // n : Length of str. // curr : Stores current permutation // index : Index in current permutation, curr function permuteRec( str , n , index, curr) { // base case if (index == n) { return; } document.write(curr+\" \"); for (var i = index + 1; i < n; i++) { curr += str[i]; permuteRec(str, n, i, curr); // backtracking curr = curr.substring(0, curr.length - 1); } return; } // Generates power set in lexicographic // order. function powerSet(str) { var arr = str.split(\"\"); arr.sort(); permuteRec(arr, str.length, -1, \"\"); } // Driver code var str = \"cab\"; powerSet(str); // This code contributed by umadevi9616</script>", "e": 5715, "s": 4806, "text": null }, { "code": null, "e": 5735, "s": 5715, "text": "a ab b c ca cab cb " }, { "code": null, "e": 5782, "s": 5735, "text": "Time Complexity: O(n*2n) Auxiliary Space: O(1)" }, { "code": null, "e": 5795, "s": 5782, "text": "Mithun Kumar" }, { "code": null, "e": 5809, "s": 5795, "text": "vibhu4agarwal" }, { "code": null, "e": 5823, "s": 5809, "text": "princiraj1992" }, { "code": null, "e": 5833, "s": 5823, "text": "Rajput-Ji" }, { "code": null, "e": 5848, "s": 5833, "text": "srivatsa vatsa" }, { "code": null, "e": 5856, "s": 5848, "text": "maddler" }, { "code": null, "e": 5868, "s": 5856, "text": "umadevi9616" }, { "code": null, "e": 5884, "s": 5868, "text": "youmailmahibagi" }, { "code": null, "e": 5897, "s": 5884, "text": "Backtracking" }, { "code": null, "e": 5907, "s": 5897, "text": "Recursion" }, { "code": null, "e": 5915, "s": 5907, "text": "Strings" }, { "code": null, "e": 5923, "s": 5915, "text": "Strings" }, { "code": null, "e": 5933, "s": 5923, "text": "Recursion" }, { "code": null, "e": 5946, "s": 5933, "text": "Backtracking" } ]
How to draw a polyline in HTML5 SVG?
SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. To draw a polygon in HTML SVG, use the SVG <polyline> element. The <polyline> element is to create a shape that consists of straight lines. The points attribute is the x and y coordinates for each corner. You can try to run the following code to learn how to draw a polyline in HTML5 SVG: <!DOCTYPE html> <html> <head> <style> #svgelem { position: relative; left: 20%; -webkit-transform: translateX(-20%); -ms-transform: translateX(-20%); transform: translateX(-20%); } </style> <title>HTML5 SVG Polyline</title> </head> <body> <h2>HTML5 SVG Polyline</h2> <svg id="svgelem" width="300" height="300" xmlns="http://www.w3.org/2000/svg"> <polyline points="0,0 0,20 20,20 20,40 40,40 40,60" fill="red" /> </svg> </body> </html>
[ { "code": null, "e": 1315, "s": 1062, "text": "SVG stands for Scalable Vector Graphics and is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer. Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG." }, { "code": null, "e": 1520, "s": 1315, "text": "To draw a polygon in HTML SVG, use the SVG <polyline> element. The <polyline> element is to create a shape that consists of straight lines. The points attribute is the x and y coordinates for each corner." }, { "code": null, "e": 1604, "s": 1520, "text": "You can try to run the following code to learn how to draw a polyline in HTML5 SVG:" }, { "code": null, "e": 2175, "s": 1604, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #svgelem {\n position: relative;\n left: 20%;\n -webkit-transform: translateX(-20%);\n -ms-transform: translateX(-20%);\n transform: translateX(-20%);\n }\n </style>\n <title>HTML5 SVG Polyline</title>\n </head>\n\n <body>\n <h2>HTML5 SVG Polyline</h2>\n <svg id=\"svgelem\" width=\"300\" height=\"300\" xmlns=\"http://www.w3.org/2000/svg\">\n <polyline points=\"0,0 0,20 20,20 20,40 40,40 40,60\" fill=\"red\" />\n </svg>\n </body>\n</html>" } ]
jQuery | :has() Selector with example - GeeksforGeeks
27 Feb, 2019 The :has() selector in jQuery is used to select all elements that have one or more elements inside of them, that matches the specified selector. Syntax: $(":has(selector)") Parameter: This selector contains single parameter selector which is mandatory and used to specify the element to select. It is also required to accept any kind of selector. Example 1: This example uses :has selector to select <h2> span element to create solid green border. <!DOCTYPE html><html> <head> <title>jQuery :has() Selector</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to use :has selector --> <script> $(document).ready(function(){ $("h2:has(span)").css("border", "solid green"); }); </script> </head> <body> <center> <h1 id="geeks1" style = "color:green;">GeeksForGeeks</h1> <h2 id="geeks2"><span>jQuery :has() Selector</span></h2> </center> </body></html> Output: Example 2: This example uses :has selector to select element and create border. <!DOCTYPE html><html> <head> <title>jQuery :has() Selector</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to use :has selector --> <script> $(document).ready(function(){ $("body:has(h1, span)").css("border", "solid green"); }); </script> </head> <body> <center> <h1 id="geeks1" style = "color:green;">GeeksForGeeks</h1> <h2 id="geeks2"><span>jQuery :has() Selector</span></h2> </center> </body></html> Output: jQuery-Selectors JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Form validation using jQuery How to Dynamically Add/Remove Table Rows using jQuery ? How to Show and Hide div elements using radio buttons? Scroll to the top of the page using JavaScript/jQuery jQuery | children() with Examples Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26316, "s": 26288, "text": "\n27 Feb, 2019" }, { "code": null, "e": 26461, "s": 26316, "text": "The :has() selector in jQuery is used to select all elements that have one or more elements inside of them, that matches the specified selector." }, { "code": null, "e": 26469, "s": 26461, "text": "Syntax:" }, { "code": null, "e": 26489, "s": 26469, "text": "$(\":has(selector)\")" }, { "code": null, "e": 26663, "s": 26489, "text": "Parameter: This selector contains single parameter selector which is mandatory and used to specify the element to select. It is also required to accept any kind of selector." }, { "code": null, "e": 26764, "s": 26663, "text": "Example 1: This example uses :has selector to select <h2> span element to create solid green border." }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery :has() Selector</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to use :has selector --> <script> $(document).ready(function(){ $(\"h2:has(span)\").css(\"border\", \"solid green\"); }); </script> </head> <body> <center> <h1 id=\"geeks1\" style = \"color:green;\">GeeksForGeeks</h1> <h2 id=\"geeks2\"><span>jQuery :has() Selector</span></h2> </center> </body></html>", "e": 27334, "s": 26764, "text": null }, { "code": null, "e": 27342, "s": 27334, "text": "Output:" }, { "code": null, "e": 27422, "s": 27342, "text": "Example 2: This example uses :has selector to select element and create border." }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery :has() Selector</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to use :has selector --> <script> $(document).ready(function(){ $(\"body:has(h1, span)\").css(\"border\", \"solid green\"); }); </script> </head> <body> <center> <h1 id=\"geeks1\" style = \"color:green;\">GeeksForGeeks</h1> <h2 id=\"geeks2\"><span>jQuery :has() Selector</span></h2> </center> </body></html>", "e": 27998, "s": 27422, "text": null }, { "code": null, "e": 28006, "s": 27998, "text": "Output:" }, { "code": null, "e": 28023, "s": 28006, "text": "jQuery-Selectors" }, { "code": null, "e": 28030, "s": 28023, "text": "JQuery" }, { "code": null, "e": 28047, "s": 28030, "text": "Web Technologies" }, { "code": null, "e": 28145, "s": 28047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28174, "s": 28145, "text": "Form validation using jQuery" }, { "code": null, "e": 28230, "s": 28174, "text": "How to Dynamically Add/Remove Table Rows using jQuery ?" }, { "code": null, "e": 28285, "s": 28230, "text": "How to Show and Hide div elements using radio buttons?" }, { "code": null, "e": 28339, "s": 28285, "text": "Scroll to the top of the page using JavaScript/jQuery" }, { "code": null, "e": 28373, "s": 28339, "text": "jQuery | children() with Examples" }, { "code": null, "e": 28413, "s": 28373, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28446, "s": 28413, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28491, "s": 28446, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28534, "s": 28491, "text": "How to fetch data from an API in ReactJS ?" } ]
Commonly Asked C Programming Interview Questions | Set 3 - GeeksforGeeks
26 Apr, 2021 Q.1 Write down the smallest executable code? Ans. main is necessary for executing the code. Code is C void main(){} Q.2 What are entry control and exit control loops? Ans. C support only 2 loops: Entry Control: This loop is categorized in 2 part a. while loop b. for loopExit control: In this category, there is one type of loop known as a. do while loop. Entry Control: This loop is categorized in 2 part a. while loop b. for loop Exit control: In this category, there is one type of loop known as a. do while loop. Q.3 Why pre-processor directive does not have a semi-colon at last? Ans. Semi-colon is needed by the compiler and as the name suggests Preprocessors are programs that process our source code before compilation. Therefore the semi-colon is not required.Q.4 What is the difference between including the header file with-in angular braces < > and double quotes ” “? Ans. If a header file is included within < > then the compiler searches for the particular header file only within the built-in include path. If a header file is included within ” “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built-in include path.Q.5 What is the difference between near, far and huge pointers? Ans. These are some old concepts used in 16 bit Intel architectures in the days of MS DOS, not much useful anymore. Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine. The limitation is that we can only access 64kb of data at a time. A far pointer is typically 32 bit that can access memory outside current segment. To use this, compiler allocates a segment register to store segment address, then another register to store offset within current segment. Like far pointer, huge pointer is also typically 32 bit and can access outside segment. In case of far pointers, a segment is fixed. In far pointer, the segment part cannot be modified, but in Huge it can be Q.6 Why does “type demotion” does not exist instead of “type promotion”? Also, it would consume less space resource than by doing it from type promotion.? Ans. Let’s take an example to understand it. Suppose double a=1.5; int b=10 and we want to calculate a+b By type demotion, float type a will convert to int. Therefore a=1 and a+b=1+10=11 but we know that correct answer is 11.5 which will only get by type promotion. So the conclusion is that by type demotion we will not get the correct answer.Q.7 What are stack and heap areas? Heap Area:It is used for the objects allocated dynamically (Using malloc() and calloc()).Stack Area:It is used to store local variables and arguments of a method. This stays in memory only till the termination of that particular method. Heap Area:It is used for the objects allocated dynamically (Using malloc() and calloc()). Stack Area:It is used to store local variables and arguments of a method. This stays in memory only till the termination of that particular method. Please refer stack vs heap memory for details. Q.8 Difference between #include in C and import in Java? Ans. Q.9 Difference between ++*p, *p++ and *++p? 1) Precedence of prefix ++ and * is same. Associativity of both is right to left. 2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.(Refer: Precedence Table)The expression ++*p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr[0] = 10, arr[1] = 20, *p = 11“.The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20“.The expression *++p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of third program is “arr[0] = 10, arr[1] = 20, *p = 20“Please refer Difference between ++*p, *p++ and *++p for details.Q.10 Explain Deep Copy and Shallow Copy with examples? In the following C program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy. C // C program to demonstrate shallow copy# include <stdio.h># include <string.h># include <stdlib.h> struct test{ char *str;}; int main(){ struct test st1, st2; st1.str = (char *)malloc(sizeof(char) * 20); strcpy(st1.str, "GeeksforGeeks"); st2 = st1; st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was shallow, both strings are same */ printf("st1's str = %s\n", st1.str); printf("st2's str = %s\n", st2.str); return 0;} st1's str = XYeksforGeeks st2's str = XYeksforGeeks To do Deep Copy, we allocate new memory for dynamically allocated members and explicitly copy them. C // C program to demonstrate deep copy# include <stdio.h># include <string.h># include <stdlib.h> struct test{ char *str;}; int main(){ struct test st1, st2; st1.str = (char *)malloc(sizeof(char) * 20); strcpy(st1.str, "GeeksforGeeks"); st2 = st1; // We add extra statements to do deep copy st2.str = (char *)malloc(sizeof(char) * 20); strcpy(st2.str, st1.str); st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was deep, both strings are different */ printf("st1's str = %s\n", st1.str); printf("st2's str = %s\n", st2.str); return 0;} st1's str = XYeksforGeeks st2's str = GeeksforGeeks 1. https://www.geeksforgeeks.org/commonly-asked-c-programming-interview-questions-set-1/ 2. https://www.geeksforgeeks.org/commonly-asked-c-programming-interview-questions-set-2/ talmoramit srinam ShreyMehrotra1 sweetyty interview-preparation placement preparation C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments TCP Server-Client implementation in C Exception Handling in C++ Multithreading in C 'this' pointer in C++ UDP Server-Client implementation in C Operators in C / C++ Ways to copy a vector in C++ Smart Pointers in C++ and How to Use Them Understanding "extern" keyword in C Input-output system calls in C | Create, Open, Close, Read, Write
[ { "code": null, "e": 24152, "s": 24124, "text": "\n26 Apr, 2021" }, { "code": null, "e": 24252, "s": 24152, "text": "Q.1 Write down the smallest executable code? Ans. main is necessary for executing the code. Code is" }, { "code": null, "e": 24254, "s": 24252, "text": "C" }, { "code": "void main(){}", "e": 24268, "s": 24254, "text": null }, { "code": null, "e": 24354, "s": 24272, "text": "Q.2 What are entry control and exit control loops? Ans. C support only 2 loops: " }, { "code": null, "e": 24514, "s": 24354, "text": "Entry Control: This loop is categorized in 2 part a. while loop b. for loopExit control: In this category, there is one type of loop known as a. do while loop." }, { "code": null, "e": 24590, "s": 24514, "text": "Entry Control: This loop is categorized in 2 part a. while loop b. for loop" }, { "code": null, "e": 24675, "s": 24590, "text": "Exit control: In this category, there is one type of loop known as a. do while loop." }, { "code": null, "e": 26139, "s": 24675, "text": "Q.3 Why pre-processor directive does not have a semi-colon at last? Ans. Semi-colon is needed by the compiler and as the name suggests Preprocessors are programs that process our source code before compilation. Therefore the semi-colon is not required.Q.4 What is the difference between including the header file with-in angular braces < > and double quotes ” “? Ans. If a header file is included within < > then the compiler searches for the particular header file only within the built-in include path. If a header file is included within ” “, then the compiler searches for the particular header file first in the current working directory, if not found then in the built-in include path.Q.5 What is the difference between near, far and huge pointers? Ans. These are some old concepts used in 16 bit Intel architectures in the days of MS DOS, not much useful anymore. Near pointer is used to store 16 bit addresses means within current segment on a 16 bit machine. The limitation is that we can only access 64kb of data at a time. A far pointer is typically 32 bit that can access memory outside current segment. To use this, compiler allocates a segment register to store segment address, then another register to store offset within current segment. Like far pointer, huge pointer is also typically 32 bit and can access outside segment. In case of far pointers, a segment is fixed. In far pointer, the segment part cannot be modified, but in Huge it can be " }, { "code": null, "e": 26674, "s": 26139, "text": "Q.6 Why does “type demotion” does not exist instead of “type promotion”? Also, it would consume less space resource than by doing it from type promotion.? Ans. Let’s take an example to understand it. Suppose double a=1.5; int b=10 and we want to calculate a+b By type demotion, float type a will convert to int. Therefore a=1 and a+b=1+10=11 but we know that correct answer is 11.5 which will only get by type promotion. So the conclusion is that by type demotion we will not get the correct answer.Q.7 What are stack and heap areas? " }, { "code": null, "e": 26911, "s": 26674, "text": "Heap Area:It is used for the objects allocated dynamically (Using malloc() and calloc()).Stack Area:It is used to store local variables and arguments of a method. This stays in memory only till the termination of that particular method." }, { "code": null, "e": 27001, "s": 26911, "text": "Heap Area:It is used for the objects allocated dynamically (Using malloc() and calloc())." }, { "code": null, "e": 27149, "s": 27001, "text": "Stack Area:It is used to store local variables and arguments of a method. This stays in memory only till the termination of that particular method." }, { "code": null, "e": 27260, "s": 27149, "text": "Please refer stack vs heap memory for details. Q.8 Difference between #include in C and import in Java? Ans. " }, { "code": null, "e": 28571, "s": 27260, "text": "Q.9 Difference between ++*p, *p++ and *++p? 1) Precedence of prefix ++ and * is same. Associativity of both is right to left. 2) Precedence of postfix ++ is higher than both * and prefix ++. Associativity of postfix ++ is left to right.(Refer: Precedence Table)The expression ++*p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as ++(*p). Therefore the output of first program is “arr[0] = 10, arr[1] = 20, *p = 11“.The expression *p++ is treated as *(p++) as the precedence of postfix ++ is higher than *. Therefore the output of second program is “arr[0] = 10, arr[1] = 20, *p = 20“.The expression *++p has two operators of same precedence, so compiler looks for associativity. Associativity of operators is right to left. Therefore the expression is treated as *(++p). Therefore the output of third program is “arr[0] = 10, arr[1] = 20, *p = 20“Please refer Difference between ++*p, *p++ and *++p for details.Q.10 Explain Deep Copy and Shallow Copy with examples? In the following C program, struct variable st1 contains pointer to dynamically allocated memory. When we assign st1 to st2, str pointer of st2 also start pointing to same memory location. This kind of copying is called Shallow Copy. " }, { "code": null, "e": 28573, "s": 28571, "text": "C" }, { "code": "// C program to demonstrate shallow copy# include <stdio.h># include <string.h># include <stdlib.h> struct test{ char *str;}; int main(){ struct test st1, st2; st1.str = (char *)malloc(sizeof(char) * 20); strcpy(st1.str, \"GeeksforGeeks\"); st2 = st1; st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was shallow, both strings are same */ printf(\"st1's str = %s\\n\", st1.str); printf(\"st2's str = %s\\n\", st2.str); return 0;}", "e": 29011, "s": 28573, "text": null }, { "code": null, "e": 29063, "s": 29011, "text": "st1's str = XYeksforGeeks\nst2's str = XYeksforGeeks" }, { "code": null, "e": 29165, "s": 29065, "text": "To do Deep Copy, we allocate new memory for dynamically allocated members and explicitly copy them." }, { "code": null, "e": 29167, "s": 29165, "text": "C" }, { "code": "// C program to demonstrate deep copy# include <stdio.h># include <string.h># include <stdlib.h> struct test{ char *str;}; int main(){ struct test st1, st2; st1.str = (char *)malloc(sizeof(char) * 20); strcpy(st1.str, \"GeeksforGeeks\"); st2 = st1; // We add extra statements to do deep copy st2.str = (char *)malloc(sizeof(char) * 20); strcpy(st2.str, st1.str); st1.str[0] = 'X'; st1.str[1] = 'Y'; /* Since copy was deep, both strings are different */ printf(\"st1's str = %s\\n\", st1.str); printf(\"st2's str = %s\\n\", st2.str); return 0;}", "e": 29723, "s": 29167, "text": null }, { "code": null, "e": 29775, "s": 29723, "text": "st1's str = XYeksforGeeks\nst2's str = GeeksforGeeks" }, { "code": null, "e": 29955, "s": 29777, "text": "1. https://www.geeksforgeeks.org/commonly-asked-c-programming-interview-questions-set-1/ 2. https://www.geeksforgeeks.org/commonly-asked-c-programming-interview-questions-set-2/" }, { "code": null, "e": 29966, "s": 29955, "text": "talmoramit" }, { "code": null, "e": 29973, "s": 29966, "text": "srinam" }, { "code": null, "e": 29988, "s": 29973, "text": "ShreyMehrotra1" }, { "code": null, "e": 29997, "s": 29988, "text": "sweetyty" }, { "code": null, "e": 30019, "s": 29997, "text": "interview-preparation" }, { "code": null, "e": 30041, "s": 30019, "text": "placement preparation" }, { "code": null, "e": 30052, "s": 30041, "text": "C Language" }, { "code": null, "e": 30150, "s": 30052, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30159, "s": 30150, "text": "Comments" }, { "code": null, "e": 30172, "s": 30159, "text": "Old Comments" }, { "code": null, "e": 30210, "s": 30172, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 30236, "s": 30210, "text": "Exception Handling in C++" }, { "code": null, "e": 30256, "s": 30236, "text": "Multithreading in C" }, { "code": null, "e": 30278, "s": 30256, "text": "'this' pointer in C++" }, { "code": null, "e": 30316, "s": 30278, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 30337, "s": 30316, "text": "Operators in C / C++" }, { "code": null, "e": 30366, "s": 30337, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 30408, "s": 30366, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 30444, "s": 30408, "text": "Understanding \"extern\" keyword in C" } ]
Tryit Editor v3.7
Background Image Repeat Tryit: Strange background image
[ { "code": null, "e": 49, "s": 25, "text": "Background Image Repeat" } ]
How to change text font for JLabel with HTML in Java?
To change text font, you can use the setFont() method of JLabel − label.setFont(new Font("Verdana", Font.PLAIN, 12)); The following is an example to change text font for JLabel with HTML − import java.awt.Font; import javax.swing.*; public class SwingDemo { public static void main(String args[]) { JFrame frame = new JFrame("Label Example"); JLabel label; label = new JLabel("<html><font size=+1>" + "<center>ABC</html>"); label.setBounds(50, 50, 100, 30); label.setFont(new Font("Verdana", Font.PLAIN, 12)); frame.add(label); frame.setSize(500,300); frame.setLayout(null); frame.setVisible(true); } }
[ { "code": null, "e": 1128, "s": 1062, "text": "To change text font, you can use the setFont() method of JLabel −" }, { "code": null, "e": 1180, "s": 1128, "text": "label.setFont(new Font(\"Verdana\", Font.PLAIN, 12));" }, { "code": null, "e": 1251, "s": 1180, "text": "The following is an example to change text font for JLabel with HTML −" }, { "code": null, "e": 1725, "s": 1251, "text": "import java.awt.Font;\nimport javax.swing.*;\npublic class SwingDemo {\n public static void main(String args[]) {\n JFrame frame = new JFrame(\"Label Example\");\n JLabel label;\n label = new JLabel(\"<html><font size=+1>\" + \"<center>ABC</html>\");\n label.setBounds(50, 50, 100, 30);\n label.setFont(new Font(\"Verdana\", Font.PLAIN, 12));\n frame.add(label);\n frame.setSize(500,300);\n frame.setLayout(null);\n frame.setVisible(true);\n }\n}" } ]
Downloading OpenImages Dataset in Google Drive using Colab | by MRINALI GUPTA | Towards Data Science
Want to train your Computer Vision model on a custom dataset but don't want to scrape the web for the images. Try out OpenImages, an open-source dataset having ~9 million varied images with 600 object categories and rich annotations provided by google. The dataset contains image-level labels annotations, object bounding boxes, object segmentation, visual relationships, localized narratives, and more. You can download the specific categories as per your interest instead of downloading the whole dataset. In this article, we will download some selected classes/categories using google colab and will save the data in Google Drive. You can use jupyter notebook as well in your local runtime. For this article, you need a google account and some space in google drive to download the data. Mount your Google Drive in Colab. Mount your Google Drive in Colab. 2. Create a folder where your data should be stored. Here, I have created a directory named OpenImages. !mkdir OpenImages 3. Change the working directory to the folder you have just created. Confirm your working directory using “!pwd” command. cd OpenImages 4. Run the below commands to download the annotations files for train, test, and validation along with the class file. # Download required meta-files!wget https://storage.googleapis.com/openimages/2018_04/class-descriptions-boxable.csv !wget https://storage.googleapis.com/openimages/2018_04/train/train-annotations-bbox.csv !wget https://storage.googleapis.com/openimages/2018_04/validation/validation-annotations-bbox.csv !wget https://storage.googleapis.com/openimages/2018_04/test/test-annotations-bbox.csv 5. Use the GitHub link to save the downloadOI.py in your working directory(https://github.com/spmallick/learnopencv/blob/master/downloadOpenImages/downloadOI.py) or copy the code present in the link and create the file directly as shown below. (Thanks to Sataya Mallick/learnopencv for this amazing code repository. Do check out this amazing Github repository if you are interested in Computer Vision and OpenCV). #This magic function is used to create the files.downloadOI.py is the file name%%writefile downloadOI.py#Author : Sunita Nayak, Big Vision LLC#### Usage example: python3 downloadOI.py --classes 'Ice_cream,Cookie' --mode trainimport argparseimport csvimport subprocessimport osfrom tqdm import tqdmimport multiprocessingfrom multiprocessing import Pool as thread_poolcpu_count = multiprocessing.cpu_count()parser = argparse.ArgumentParser(description='Download Class specific images from OpenImagesV4')parser.add_argument("--mode", help="Dataset category - train, validation or test", required=True)parser.add_argument("--classes", help="Names of object classes to be downloaded", required=True)parser.add_argument("--nthreads", help="Number of threads to use", required=False, type=int, default=cpu_count*2)parser.add_argument("--occluded", help="Include occluded images", required=False, type=int, default=1)parser.add_argument("--truncated", help="Include truncated images", required=False, type=int, default=1)parser.add_argument("--groupOf", help="Include groupOf images", required=False, type=int, default=1)parser.add_argument("--depiction", help="Include depiction images", required=False, type=int, default=1)parser.add_argument("--inside", help="Include inside images", required=False, type=int, default=1)args = parser.parse_args()run_mode = args.modethreads = args.nthreadsclasses = []for class_name in args.classes.split(','): classes.append(class_name)with open('./class-descriptions-boxable.csv', mode='r') as infile: reader = csv.reader(infile) dict_list = {rows[1]:rows[0] for rows in reader}subprocess.run(['rm', '-rf', run_mode])subprocess.run([ 'mkdir', run_mode])pool = thread_pool(threads)commands = []cnt = 0for ind in range(0, len(classes)): class_name = classes[ind] print("Class "+str(ind) + " : " + class_name) subprocess.run([ 'mkdir', run_mode+'/'+class_name]) command = "grep "+dict_list[class_name.replace('_', ' ')] + " ./" + run_mode + "-annotations-bbox.csv" class_annotations = subprocess.run(command.split(), stdout=subprocess.PIPE).stdout.decode('utf-8') class_annotations = class_annotations.splitlines() for line in class_annotations: line_parts = line.split(',') #IsOccluded,IsTruncated,IsGroupOf,IsDepiction,IsInside if (args.occluded==0 and int(line_parts[8])>0): print("Skipped %s",line_parts[0]) continue if (args.truncated==0 and int(line_parts[9])>0): print("Skipped %s",line_parts[0]) continue if (args.groupOf==0 and int(line_parts[10])>0): print("Skipped %s",line_parts[0]) continue if (args.depiction==0 and int(line_parts[11])>0): print("Skipped %s",line_parts[0]) continue if (args.inside==0 and int(line_parts[12])>0): print("Skipped %s",line_parts[0]) continue cnt = cnt + 1 command = 'aws s3 --no-sign-request --only-show-errors cp s3://open-images-dataset/'+run_mode+'/'+line_parts[0]+'.jpg '+ run_mode+'/'+class_name+'/'+line_parts[0]+'.jpg' commands.append(command) with open('%s/%s/%s.txt'%(run_mode,class_name,line_parts[0]),'a') as f: f.write(','.join([class_name, line_parts[4], line_parts[5], line_parts[6], line_parts[7]])+'\n')print("Annotation Count : "+str(cnt))commands = list(set(commands))print("Number of images to be downloaded : "+str(len(commands)))list(tqdm(pool.imap(os.system, commands), total = len(commands) ))pool.close()pool.join() 6. The content in the directory OpenImages should look like this 7. Run the below command to avoid “aws: not found sh: 1: aws: not found” error. !pip install awscli 8. Downloading the specific data. Here I am downloading 2 classes Sink and Toilet. You can try multiple classes and download the data. You can find all the class names in the “class-descriptions-boxable.csv”. # Download Sink and Toilet images for test !python3 downloadOI.py --classes "Sink,Toilet" --mode test# Download Sink and Toilet images for train!python3 downloadOI.py --classes "Sink,Toilet" --mode train# Download Sink and Toilet images for validation!python3 downloadOI.py --classes "Sink,Toilet" --mode validation There are 3 mode options you can choose a) — mode train: To download the training data b) — mode test: To download the test data c) — mode validation: To download the validation data Each Category has an image file along with its annotations in a text file. Filepath: OpenImages/train/Sink/01681d52ad599ab4.jpg Image File: 01681d52ad599ab4.jpg TextFile: 01681d52ad599ab4.txt TextFile Content : Sink,0.249529,0.420054,0.659844,0.682363 .txt file has the dimensions of the bounding boxes. It can have multiple entries in case if the image has multiple objects. Note: Keep in mind that every time you run this command the old data will get deleted. So if you want to use the command again, better try it in some other folder to avoid the deletion of the previous downloading data. That’s all. Play around with it and download the custom data to train your custom computer vision model. Github link to the code https://github.com/mringupt/Colab/blob/master/Downloading_OpenImages_Custom_Dataset.ipynb
[ { "code": null, "e": 576, "s": 172, "text": "Want to train your Computer Vision model on a custom dataset but don't want to scrape the web for the images. Try out OpenImages, an open-source dataset having ~9 million varied images with 600 object categories and rich annotations provided by google. The dataset contains image-level labels annotations, object bounding boxes, object segmentation, visual relationships, localized narratives, and more." }, { "code": null, "e": 866, "s": 576, "text": "You can download the specific categories as per your interest instead of downloading the whole dataset. In this article, we will download some selected classes/categories using google colab and will save the data in Google Drive. You can use jupyter notebook as well in your local runtime." }, { "code": null, "e": 963, "s": 866, "text": "For this article, you need a google account and some space in google drive to download the data." }, { "code": null, "e": 997, "s": 963, "text": "Mount your Google Drive in Colab." }, { "code": null, "e": 1031, "s": 997, "text": "Mount your Google Drive in Colab." }, { "code": null, "e": 1135, "s": 1031, "text": "2. Create a folder where your data should be stored. Here, I have created a directory named OpenImages." }, { "code": null, "e": 1153, "s": 1135, "text": "!mkdir OpenImages" }, { "code": null, "e": 1275, "s": 1153, "text": "3. Change the working directory to the folder you have just created. Confirm your working directory using “!pwd” command." }, { "code": null, "e": 1289, "s": 1275, "text": "cd OpenImages" }, { "code": null, "e": 1408, "s": 1289, "text": "4. Run the below commands to download the annotations files for train, test, and validation along with the class file." }, { "code": null, "e": 1800, "s": 1408, "text": "# Download required meta-files!wget https://storage.googleapis.com/openimages/2018_04/class-descriptions-boxable.csv !wget https://storage.googleapis.com/openimages/2018_04/train/train-annotations-bbox.csv !wget https://storage.googleapis.com/openimages/2018_04/validation/validation-annotations-bbox.csv !wget https://storage.googleapis.com/openimages/2018_04/test/test-annotations-bbox.csv" }, { "code": null, "e": 2214, "s": 1800, "text": "5. Use the GitHub link to save the downloadOI.py in your working directory(https://github.com/spmallick/learnopencv/blob/master/downloadOpenImages/downloadOI.py) or copy the code present in the link and create the file directly as shown below. (Thanks to Sataya Mallick/learnopencv for this amazing code repository. Do check out this amazing Github repository if you are interested in Computer Vision and OpenCV)." }, { "code": null, "e": 5778, "s": 2214, "text": "#This magic function is used to create the files.downloadOI.py is the file name%%writefile downloadOI.py#Author : Sunita Nayak, Big Vision LLC#### Usage example: python3 downloadOI.py --classes 'Ice_cream,Cookie' --mode trainimport argparseimport csvimport subprocessimport osfrom tqdm import tqdmimport multiprocessingfrom multiprocessing import Pool as thread_poolcpu_count = multiprocessing.cpu_count()parser = argparse.ArgumentParser(description='Download Class specific images from OpenImagesV4')parser.add_argument(\"--mode\", help=\"Dataset category - train, validation or test\", required=True)parser.add_argument(\"--classes\", help=\"Names of object classes to be downloaded\", required=True)parser.add_argument(\"--nthreads\", help=\"Number of threads to use\", required=False, type=int, default=cpu_count*2)parser.add_argument(\"--occluded\", help=\"Include occluded images\", required=False, type=int, default=1)parser.add_argument(\"--truncated\", help=\"Include truncated images\", required=False, type=int, default=1)parser.add_argument(\"--groupOf\", help=\"Include groupOf images\", required=False, type=int, default=1)parser.add_argument(\"--depiction\", help=\"Include depiction images\", required=False, type=int, default=1)parser.add_argument(\"--inside\", help=\"Include inside images\", required=False, type=int, default=1)args = parser.parse_args()run_mode = args.modethreads = args.nthreadsclasses = []for class_name in args.classes.split(','): classes.append(class_name)with open('./class-descriptions-boxable.csv', mode='r') as infile: reader = csv.reader(infile) dict_list = {rows[1]:rows[0] for rows in reader}subprocess.run(['rm', '-rf', run_mode])subprocess.run([ 'mkdir', run_mode])pool = thread_pool(threads)commands = []cnt = 0for ind in range(0, len(classes)): class_name = classes[ind] print(\"Class \"+str(ind) + \" : \" + class_name) subprocess.run([ 'mkdir', run_mode+'/'+class_name]) command = \"grep \"+dict_list[class_name.replace('_', ' ')] + \" ./\" + run_mode + \"-annotations-bbox.csv\" class_annotations = subprocess.run(command.split(), stdout=subprocess.PIPE).stdout.decode('utf-8') class_annotations = class_annotations.splitlines() for line in class_annotations: line_parts = line.split(',') #IsOccluded,IsTruncated,IsGroupOf,IsDepiction,IsInside if (args.occluded==0 and int(line_parts[8])>0): print(\"Skipped %s\",line_parts[0]) continue if (args.truncated==0 and int(line_parts[9])>0): print(\"Skipped %s\",line_parts[0]) continue if (args.groupOf==0 and int(line_parts[10])>0): print(\"Skipped %s\",line_parts[0]) continue if (args.depiction==0 and int(line_parts[11])>0): print(\"Skipped %s\",line_parts[0]) continue if (args.inside==0 and int(line_parts[12])>0): print(\"Skipped %s\",line_parts[0]) continue cnt = cnt + 1 command = 'aws s3 --no-sign-request --only-show-errors cp s3://open-images-dataset/'+run_mode+'/'+line_parts[0]+'.jpg '+ run_mode+'/'+class_name+'/'+line_parts[0]+'.jpg' commands.append(command) with open('%s/%s/%s.txt'%(run_mode,class_name,line_parts[0]),'a') as f: f.write(','.join([class_name, line_parts[4], line_parts[5], line_parts[6], line_parts[7]])+'\\n')print(\"Annotation Count : \"+str(cnt))commands = list(set(commands))print(\"Number of images to be downloaded : \"+str(len(commands)))list(tqdm(pool.imap(os.system, commands), total = len(commands) ))pool.close()pool.join()" }, { "code": null, "e": 5843, "s": 5778, "text": "6. The content in the directory OpenImages should look like this" }, { "code": null, "e": 5923, "s": 5843, "text": "7. Run the below command to avoid “aws: not found sh: 1: aws: not found” error." }, { "code": null, "e": 5943, "s": 5923, "text": "!pip install awscli" }, { "code": null, "e": 6152, "s": 5943, "text": "8. Downloading the specific data. Here I am downloading 2 classes Sink and Toilet. You can try multiple classes and download the data. You can find all the class names in the “class-descriptions-boxable.csv”." }, { "code": null, "e": 6468, "s": 6152, "text": "# Download Sink and Toilet images for test !python3 downloadOI.py --classes \"Sink,Toilet\" --mode test# Download Sink and Toilet images for train!python3 downloadOI.py --classes \"Sink,Toilet\" --mode train# Download Sink and Toilet images for validation!python3 downloadOI.py --classes \"Sink,Toilet\" --mode validation" }, { "code": null, "e": 6508, "s": 6468, "text": "There are 3 mode options you can choose" }, { "code": null, "e": 6555, "s": 6508, "text": "a) — mode train: To download the training data" }, { "code": null, "e": 6597, "s": 6555, "text": "b) — mode test: To download the test data" }, { "code": null, "e": 6651, "s": 6597, "text": "c) — mode validation: To download the validation data" }, { "code": null, "e": 6726, "s": 6651, "text": "Each Category has an image file along with its annotations in a text file." }, { "code": null, "e": 6779, "s": 6726, "text": "Filepath: OpenImages/train/Sink/01681d52ad599ab4.jpg" }, { "code": null, "e": 6812, "s": 6779, "text": "Image File: 01681d52ad599ab4.jpg" }, { "code": null, "e": 6843, "s": 6812, "text": "TextFile: 01681d52ad599ab4.txt" }, { "code": null, "e": 6903, "s": 6843, "text": "TextFile Content : Sink,0.249529,0.420054,0.659844,0.682363" }, { "code": null, "e": 7027, "s": 6903, "text": ".txt file has the dimensions of the bounding boxes. It can have multiple entries in case if the image has multiple objects." }, { "code": null, "e": 7246, "s": 7027, "text": "Note: Keep in mind that every time you run this command the old data will get deleted. So if you want to use the command again, better try it in some other folder to avoid the deletion of the previous downloading data." }, { "code": null, "e": 7351, "s": 7246, "text": "That’s all. Play around with it and download the custom data to train your custom computer vision model." } ]
How To Dockerize an Existing Ruby on Rails Application | by Mahbub Zaman | Towards Data Science
Ruby on Rails is an open-source web application development framework based on Ruby. Many big companies use Rails to build their products, such as GitHub, Shopify, Airbnb, and Twitch. From this post, you’ll learn how to dockerize an existing Ruby on Rails application to make development faster and easier. First, we need need to install Docker and download a git repository from GitHub. For this setup, I’m using macOS. Now, we will create a Docker image that contains Ruby on Rails. Let’s break down the individual ingredients of the Dockerfile file. FROM ruby:3.0.0RUN apt-get update -qq \&& apt-get install -y nodejs postgresql-clientADD . /Rails-DockerWORKDIR /Rails-DockerRUN bundle installEXPOSE 3000CMD ["bash"] Here we are using the From instruction to define the parent image. We are using the pre-built official image of Ruby from Docker Hub. After that, we are installing all the dependencies using the RUN instruction. Now we need to add everything from the current folder into a directory in the image called Rails-Docker by using the ADD instruction. The WORKDIR instruction will set the working directory to Rails-Docker. Again we are using the RUN instruction to install our ruby gems. After that, we are exposing port 3000 for our container using the EXPOSE instruction. By default, Rails run on port 3000. Finally, the CMD instruction is used to run a command when a container starts. In this case, it’s used to open the bash shell. Now, we need to run the db and web containers. For this, we will create a Docker compose file. Let’s break down the individual ingredients of the docker-compose.yml file. version: '3.8'services: db: image: postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password volumes: - postgres:/var/lib/postgresql/data web: build: . command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'" volumes: - .:/Rails-Docker ports: - "3000:3000" depends_on: - dbvolumes: postgres: The version tag is used to define the Compose file format. The services tag is used to define the services we want to use for our application. Here, we have two services called db and web. Under the db service, we are using the pre-built postgres image to build the image. Then we have enviriomnt varaibles. Finally, we have a named volume called postgres to persist data. Under the web service, we are using the Dockerfile we created earlier to build the image. The command tag is used to run our application. We are using ‘0.0.0.0’ so that the server will listen to all available IP addresses. The ports tag is used to define both host and container ports. It maps port 3000 on the host to port 3000 on the container. Finally, the volumes tag is used to mount a folder from the host machine to the container. Now run the following commands from the same directory where the docker-compose.yml file is located. This command will start and run the entire app. docker compose up If you encounter the an error “ActiveRecord::NoDatabaseError” then run the following command to create the database. docker-compose run web rake db:create Congratulations! You can now access the Rails application via your favorite web browser by vising the URL http://localhost:3000/. I hope this will help you to get started with Rails and Docker. Now create your next big thing using Rails. Happy coding!
[ { "code": null, "e": 356, "s": 172, "text": "Ruby on Rails is an open-source web application development framework based on Ruby. Many big companies use Rails to build their products, such as GitHub, Shopify, Airbnb, and Twitch." }, { "code": null, "e": 479, "s": 356, "text": "From this post, you’ll learn how to dockerize an existing Ruby on Rails application to make development faster and easier." }, { "code": null, "e": 593, "s": 479, "text": "First, we need need to install Docker and download a git repository from GitHub. For this setup, I’m using macOS." }, { "code": null, "e": 725, "s": 593, "text": "Now, we will create a Docker image that contains Ruby on Rails. Let’s break down the individual ingredients of the Dockerfile file." }, { "code": null, "e": 892, "s": 725, "text": "FROM ruby:3.0.0RUN apt-get update -qq \\&& apt-get install -y nodejs postgresql-clientADD . /Rails-DockerWORKDIR /Rails-DockerRUN bundle installEXPOSE 3000CMD [\"bash\"]" }, { "code": null, "e": 1624, "s": 892, "text": "Here we are using the From instruction to define the parent image. We are using the pre-built official image of Ruby from Docker Hub. After that, we are installing all the dependencies using the RUN instruction. Now we need to add everything from the current folder into a directory in the image called Rails-Docker by using the ADD instruction. The WORKDIR instruction will set the working directory to Rails-Docker. Again we are using the RUN instruction to install our ruby gems. After that, we are exposing port 3000 for our container using the EXPOSE instruction. By default, Rails run on port 3000. Finally, the CMD instruction is used to run a command when a container starts. In this case, it’s used to open the bash shell." }, { "code": null, "e": 1795, "s": 1624, "text": "Now, we need to run the db and web containers. For this, we will create a Docker compose file. Let’s break down the individual ingredients of the docker-compose.yml file." }, { "code": null, "e": 2192, "s": 1795, "text": "version: '3.8'services: db: image: postgres environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: password volumes: - postgres:/var/lib/postgresql/data web: build: . command: bash -c \"rm -f tmp/pids/server.pid && bundle exec rails s -p 3000 -b '0.0.0.0'\" volumes: - .:/Rails-Docker ports: - \"3000:3000\" depends_on: - dbvolumes: postgres:" }, { "code": null, "e": 2381, "s": 2192, "text": "The version tag is used to define the Compose file format. The services tag is used to define the services we want to use for our application. Here, we have two services called db and web." }, { "code": null, "e": 2565, "s": 2381, "text": "Under the db service, we are using the pre-built postgres image to build the image. Then we have enviriomnt varaibles. Finally, we have a named volume called postgres to persist data." }, { "code": null, "e": 3003, "s": 2565, "text": "Under the web service, we are using the Dockerfile we created earlier to build the image. The command tag is used to run our application. We are using ‘0.0.0.0’ so that the server will listen to all available IP addresses. The ports tag is used to define both host and container ports. It maps port 3000 on the host to port 3000 on the container. Finally, the volumes tag is used to mount a folder from the host machine to the container." }, { "code": null, "e": 3152, "s": 3003, "text": "Now run the following commands from the same directory where the docker-compose.yml file is located. This command will start and run the entire app." }, { "code": null, "e": 3170, "s": 3152, "text": "docker compose up" }, { "code": null, "e": 3287, "s": 3170, "text": "If you encounter the an error “ActiveRecord::NoDatabaseError” then run the following command to create the database." }, { "code": null, "e": 3325, "s": 3287, "text": "docker-compose run web rake db:create" }, { "code": null, "e": 3455, "s": 3325, "text": "Congratulations! You can now access the Rails application via your favorite web browser by vising the URL http://localhost:3000/." } ]
How do I set browser width and height in Selenium WebDriver?
We can set browser width and height in Selenium webdriver. There are multiple methods available to achieve this. Whenever an application is launched, it opens in its default browser size. We can resize the browser with the help of the Dimension class in Java. We create an object of the Dimension class and pass the desired width and height of the browser as parameters to that class. Finally we pass the object of the Dimension class as an argument to the setSize method. Dimension dem = new Dimension(750,450); driver.manage().window().setSize(dem); We can also set the browser width and height with the help of Chrome options. We have to create an object of the ChromeOptions class and apply addArguments to it. The parameter window-size set with values of height and width of the browser are passed as arguments to the method. This knowledge is passed to the browser invocation method with the help of DesiredCapabilities class. ChromeOptions options = new ChromeOptions(); options.addArguments("window-size=750,450"); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, options); WebDriver driver = new ChromeDriver(capabilities); Code Implementation with Dimension class. import org.openqa.selenium.Dimension; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class BrowserResize{ 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); // Dimension class with browser width and height value passed Dimension dem = new Dimension(750,450); // passing the Dimension object as an argument to setSize method driver.manage().window().setSize(dem); Implementation with Chrome Options. import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class BrowserResizeOptions{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); // ChromeOptions class with addArguments method ChromeOptions options = new ChromeOptions(); options.addArguments("window-size=750,450"); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); capabilities.setCapability(ChromeOptions.CAPABILITY, options); WebDriver driver = new ChromeDriver(capabilities); String url = "https://www.tutorialspoint.com/tutor_connect/index.php"; driver.get(url); } }
[ { "code": null, "e": 1250, "s": 1062, "text": "We can set browser width and height in Selenium webdriver. There are multiple methods available to achieve this. Whenever an application is launched, it opens in its default browser size." }, { "code": null, "e": 1535, "s": 1250, "text": "We can resize the browser with the help of the Dimension class in Java. We create an object of the Dimension class and pass the desired width and height of the browser as parameters to that class. Finally we pass the object of the Dimension class as an argument to the setSize method." }, { "code": null, "e": 1614, "s": 1535, "text": "Dimension dem = new Dimension(750,450);\ndriver.manage().window().setSize(dem);" }, { "code": null, "e": 1995, "s": 1614, "text": "We can also set the browser width and height with the help of Chrome options. We have to create an object of the ChromeOptions class and apply addArguments to it. The parameter window-size set with values of height and width of the browser are passed as arguments to the method. This knowledge is passed to the browser invocation method with the help of DesiredCapabilities class." }, { "code": null, "e": 2265, "s": 1995, "text": "ChromeOptions options = new ChromeOptions();\noptions.addArguments(\"window-size=750,450\");\n\nDesiredCapabilities capabilities = DesiredCapabilities.chrome();\ncapabilities.setCapability(ChromeOptions.CAPABILITY, options);\nWebDriver driver = new ChromeDriver(capabilities);" }, { "code": null, "e": 2307, "s": 2265, "text": "Code Implementation with Dimension class." }, { "code": null, "e": 2987, "s": 2307, "text": "import org.openqa.selenium.Dimension;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class BrowserResize{\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\";\n driver.get(url);\n // Dimension class with browser width and height value passed\n Dimension dem = new Dimension(750,450);\n // passing the Dimension object as an argument to setSize method\n driver.manage().window().setSize(dem);" }, { "code": null, "e": 3023, "s": 2987, "text": "Implementation with Chrome Options." }, { "code": null, "e": 3860, "s": 3023, "text": "import org.openqa.selenium.chrome.ChromeOptions;\nimport org.openqa.selenium.remote.DesiredCapabilities;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.chrome.ChromeDriver;\npublic class BrowserResizeOptions{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n // ChromeOptions class with addArguments method\n ChromeOptions options = new ChromeOptions();\n options.addArguments(\"window-size=750,450\");\n DesiredCapabilities capabilities = DesiredCapabilities.chrome();\n capabilities.setCapability(ChromeOptions.CAPABILITY, options);\n WebDriver driver = new ChromeDriver(capabilities);\n String url = \"https://www.tutorialspoint.com/tutor_connect/index.php\";\n driver.get(url);\n }\n}" } ]
JSF - h:selectOneListbox
The h:selectOneListbox tag renders an HTML input element of the type "select" with size specified. <h:selectOneListbox value = "#{userData.data}"> <f:selectItem itemValue = "1" itemLabel = "Item 1" /> <f:selectItem itemValue = "2" itemLabel = "Item 2" /> </h:selectOneListbox> <select name = "j_idt6:j_idt8" size = "2"> <option value = "1">Item 1</option> <option value = "2">Item 2</option> </select> id Identifier for a component binding Reference to the component that can be used in a backing bean rendered A boolean; false suppresses rendering styleClass Cascading stylesheet (CSS) class name value A component’s value, typically a value binding valueChangeListener A method binding to a method that responds to value changes converter Converter class name validator Class name of a validator that’s created and attached to a component required A boolean; if true, requires a value to be entered in the associated field accesskey A key, typically combined with a system-defined metakey, that gives focus to an element accept Comma-separated list of content types for a form accept-charset Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset. alt Alternative text for nontextual elements such as images or applets charset Character encoding for a linked resource coords Coordinates for an element whose shape is a rectangle, circle, or polygon dir Direction for text. Valid values are ltr (left to right) and rtl (right to left) disabled Disabled state of an input element or button hreflang Base language of a resource specified with the href attribute; hreflang may only be used with href. lang Base language of an element’s attributes and text maxlength Maximum number of characters for text fields readonly Read-only state of an input field; text can be selected in a readonly field but not edited rel Relationship between the current document and a link specified with the href attribute rev Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types rows Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute. shape Shape of a region. Valid values: default, rect, circle, poly. (default signifies the entire region) style Inline style information tabindex Numerical value specifying a tab index target The name of a frame in which a document is opened title A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value type Type of a link; for example, stylesheet width Width of an element onblur Element loses focus onchange Element’s value changes onclick Mouse button is clicked over the element ondblclick Mouse button is double-clicked over the element onfocus Element receives focus onkeydown Key is pressed onkeypress Key is pressed and subsequently released onkeyup Key is released onmousedown Mouse button is pressed over the element onmousemove Mouse moves over the element onmouseout Mouse leaves the element’s area onmouseover Mouse moves onto an element onmouseup Mouse button is released onreset Form is reset onselect Text is selected in an input field size Size of input field Let us create a test JSF application to test the above tag. package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; public String data = "1"; public String getData() { return data; } public void setData(String data) { this.data = data; } } <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <head> <title>JSF Tutorial!</title> </head> <h:body> <h2>h::selectOneListbox example</h2> <hr /> <h:form> <h3>List Box</h3> <h:selectOneListbox value = "#{userData.data}"> <f:selectItem itemValue = "1" itemLabel = "Item 1" /> <f:selectItem itemValue = "2" itemLabel = "Item 2" /> <f:selectItem itemValue = "3" itemLabel = "Item 3" /> <f:selectItem itemValue = "4" itemLabel = "Item 4" /> <f:selectItem itemValue = "5" itemLabel = "Item 5" /> </h:selectOneListbox> <h:commandButton value = "Submit" action = "result" /> </h:form> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <head> <title>JSF Tutorial!</title> </head> <h:body> <h2>Result</h2> <hr /> #{userData.data} </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. Select any option and press Submit button. We've selected item 3. You will see the selected results. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2051, "s": 1952, "text": "The h:selectOneListbox tag renders an HTML input element of the type \"select\" with size specified." }, { "code": null, "e": 2241, "s": 2051, "text": "<h:selectOneListbox value = \"#{userData.data}\"> \n <f:selectItem itemValue = \"1\" itemLabel = \"Item 1\" /> \n <f:selectItem itemValue = \"2\" itemLabel = \"Item 2\" /> \n</h:selectOneListbox> " }, { "code": null, "e": 2376, "s": 2241, "text": "<select name = \"j_idt6:j_idt8\" size = \"2\"> \n <option value = \"1\">Item 1</option> \n <option value = \"2\">Item 2</option> \n</select>" }, { "code": null, "e": 2379, "s": 2376, "text": "id" }, { "code": null, "e": 2406, "s": 2379, "text": "Identifier for a component" }, { "code": null, "e": 2414, "s": 2406, "text": "binding" }, { "code": null, "e": 2476, "s": 2414, "text": "Reference to the component that can be used in a backing bean" }, { "code": null, "e": 2485, "s": 2476, "text": "rendered" }, { "code": null, "e": 2523, "s": 2485, "text": "A boolean; false suppresses rendering" }, { "code": null, "e": 2534, "s": 2523, "text": "styleClass" }, { "code": null, "e": 2572, "s": 2534, "text": "Cascading stylesheet (CSS) class name" }, { "code": null, "e": 2578, "s": 2572, "text": "value" }, { "code": null, "e": 2625, "s": 2578, "text": "A component’s value, typically a value binding" }, { "code": null, "e": 2645, "s": 2625, "text": "valueChangeListener" }, { "code": null, "e": 2705, "s": 2645, "text": "A method binding to a method that responds to value changes" }, { "code": null, "e": 2715, "s": 2705, "text": "converter" }, { "code": null, "e": 2736, "s": 2715, "text": "Converter class name" }, { "code": null, "e": 2746, "s": 2736, "text": "validator" }, { "code": null, "e": 2815, "s": 2746, "text": "Class name of a validator that’s created and attached to a component" }, { "code": null, "e": 2824, "s": 2815, "text": "required" }, { "code": null, "e": 2899, "s": 2824, "text": "A boolean; if true, requires a value to be entered in the associated field" }, { "code": null, "e": 2909, "s": 2899, "text": "accesskey" }, { "code": null, "e": 2997, "s": 2909, "text": "A key, typically combined with a system-defined metakey, that gives focus to an element" }, { "code": null, "e": 3004, "s": 2997, "text": "accept" }, { "code": null, "e": 3053, "s": 3004, "text": "Comma-separated list of content types for a form" }, { "code": null, "e": 3068, "s": 3053, "text": "accept-charset" }, { "code": null, "e": 3225, "s": 3068, "text": "Comma- or space-separated list of character encodings for a form. The accept-charset attribute is specified with the JSF HTML attribute named acceptcharset." }, { "code": null, "e": 3229, "s": 3225, "text": "alt" }, { "code": null, "e": 3296, "s": 3229, "text": "Alternative text for nontextual elements such as images or applets" }, { "code": null, "e": 3304, "s": 3296, "text": "charset" }, { "code": null, "e": 3345, "s": 3304, "text": "Character encoding for a linked resource" }, { "code": null, "e": 3352, "s": 3345, "text": "coords" }, { "code": null, "e": 3426, "s": 3352, "text": "Coordinates for an element whose shape is a rectangle, circle, or polygon" }, { "code": null, "e": 3430, "s": 3426, "text": "dir" }, { "code": null, "e": 3511, "s": 3430, "text": "Direction for text. Valid values are ltr (left to right) and rtl (right to left)" }, { "code": null, "e": 3520, "s": 3511, "text": "disabled" }, { "code": null, "e": 3565, "s": 3520, "text": "Disabled state of an input element or button" }, { "code": null, "e": 3574, "s": 3565, "text": "hreflang" }, { "code": null, "e": 3674, "s": 3574, "text": "Base language of a resource specified with the href attribute; hreflang may only be used with href." }, { "code": null, "e": 3679, "s": 3674, "text": "lang" }, { "code": null, "e": 3729, "s": 3679, "text": "Base language of an element’s attributes and text" }, { "code": null, "e": 3739, "s": 3729, "text": "maxlength" }, { "code": null, "e": 3784, "s": 3739, "text": "Maximum number of characters for text fields" }, { "code": null, "e": 3793, "s": 3784, "text": "readonly" }, { "code": null, "e": 3884, "s": 3793, "text": "Read-only state of an input field; text can be selected in a readonly field but not edited" }, { "code": null, "e": 3888, "s": 3884, "text": "rel" }, { "code": null, "e": 3975, "s": 3888, "text": "Relationship between the current document and a link specified with the href attribute" }, { "code": null, "e": 3979, "s": 3975, "text": "rev" }, { "code": null, "e": 4120, "s": 3979, "text": "Reverse link from the anchor specified with href to the current document. The value of the attribute is a space-separated list of link types" }, { "code": null, "e": 4125, "s": 4120, "text": "rows" }, { "code": null, "e": 4243, "s": 4125, "text": "Number of visible rows in a text area. h:dataTable has a rows attribute, but it’s not an HTML pass-through attribute." }, { "code": null, "e": 4249, "s": 4243, "text": "shape" }, { "code": null, "e": 4349, "s": 4249, "text": "Shape of a region. Valid values: default, rect, circle, poly. (default signifies the entire region)" }, { "code": null, "e": 4355, "s": 4349, "text": "style" }, { "code": null, "e": 4380, "s": 4355, "text": "Inline style information" }, { "code": null, "e": 4389, "s": 4380, "text": "tabindex" }, { "code": null, "e": 4428, "s": 4389, "text": "Numerical value specifying a tab index" }, { "code": null, "e": 4435, "s": 4428, "text": "target" }, { "code": null, "e": 4485, "s": 4435, "text": "The name of a frame in which a document is opened" }, { "code": null, "e": 4491, "s": 4485, "text": "title" }, { "code": null, "e": 4615, "s": 4491, "text": "A title, used for accessibility, that describes an element. Visual browsers typically create tooltips for the title’s value" }, { "code": null, "e": 4620, "s": 4615, "text": "type" }, { "code": null, "e": 4660, "s": 4620, "text": "Type of a link; for example, stylesheet" }, { "code": null, "e": 4666, "s": 4660, "text": "width" }, { "code": null, "e": 4686, "s": 4666, "text": "Width of an element" }, { "code": null, "e": 4693, "s": 4686, "text": "onblur" }, { "code": null, "e": 4713, "s": 4693, "text": "Element loses focus" }, { "code": null, "e": 4722, "s": 4713, "text": "onchange" }, { "code": null, "e": 4746, "s": 4722, "text": "Element’s value changes" }, { "code": null, "e": 4754, "s": 4746, "text": "onclick" }, { "code": null, "e": 4795, "s": 4754, "text": "Mouse button is clicked over the element" }, { "code": null, "e": 4806, "s": 4795, "text": "ondblclick" }, { "code": null, "e": 4854, "s": 4806, "text": "Mouse button is double-clicked over the element" }, { "code": null, "e": 4862, "s": 4854, "text": "onfocus" }, { "code": null, "e": 4885, "s": 4862, "text": "Element receives focus" }, { "code": null, "e": 4895, "s": 4885, "text": "onkeydown" }, { "code": null, "e": 4910, "s": 4895, "text": "Key is pressed" }, { "code": null, "e": 4921, "s": 4910, "text": "onkeypress" }, { "code": null, "e": 4962, "s": 4921, "text": "Key is pressed and subsequently released" }, { "code": null, "e": 4970, "s": 4962, "text": "onkeyup" }, { "code": null, "e": 4986, "s": 4970, "text": "Key is released" }, { "code": null, "e": 4998, "s": 4986, "text": "onmousedown" }, { "code": null, "e": 5039, "s": 4998, "text": "Mouse button is pressed over the element" }, { "code": null, "e": 5051, "s": 5039, "text": "onmousemove" }, { "code": null, "e": 5080, "s": 5051, "text": "Mouse moves over the element" }, { "code": null, "e": 5091, "s": 5080, "text": "onmouseout" }, { "code": null, "e": 5123, "s": 5091, "text": "Mouse leaves the element’s area" }, { "code": null, "e": 5135, "s": 5123, "text": "onmouseover" }, { "code": null, "e": 5163, "s": 5135, "text": "Mouse moves onto an element" }, { "code": null, "e": 5173, "s": 5163, "text": "onmouseup" }, { "code": null, "e": 5198, "s": 5173, "text": "Mouse button is released" }, { "code": null, "e": 5206, "s": 5198, "text": "onreset" }, { "code": null, "e": 5220, "s": 5206, "text": "Form is reset" }, { "code": null, "e": 5229, "s": 5220, "text": "onselect" }, { "code": null, "e": 5264, "s": 5229, "text": "Text is selected in an input field" }, { "code": null, "e": 5269, "s": 5264, "text": "size" }, { "code": null, "e": 5289, "s": 5269, "text": "Size of input field" }, { "code": null, "e": 5349, "s": 5289, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 5804, "s": 5349, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n public String data = \"1\";\n\n public String getData() {\n return data;\n }\n\n public void setData(String data) {\n this.data = data;\n }\n}" }, { "code": null, "e": 6845, "s": 5804, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?> \n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"> \n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\"> \n \n <head> \n <title>JSF Tutorial!</title> \n </head> \n \n <h:body> \n <h2>h::selectOneListbox example</h2> \n <hr /> \n \n <h:form> \n <h3>List Box</h3> \n <h:selectOneListbox value = \"#{userData.data}\"> \n <f:selectItem itemValue = \"1\" itemLabel = \"Item 1\" /> \n <f:selectItem itemValue = \"2\" itemLabel = \"Item 2\" /> \n <f:selectItem itemValue = \"3\" itemLabel = \"Item 3\" /> \n <f:selectItem itemValue = \"4\" itemLabel = \"Item 4\" /> \n <f:selectItem itemValue = \"5\" itemLabel = \"Item 5\" /> \n </h:selectOneListbox> \n <h:commandButton value = \"Submit\" action = \"result\" /> \n </h:form> \n \n </h:body>\n</html>" }, { "code": null, "e": 7356, "s": 6845, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <head>\n <title>JSF Tutorial!</title>\n </head>\n \n <h:body>\n <h2>Result</h2>\n <hr />\n #{userData.data}\n </h:body>\n</html> " }, { "code": null, "e": 7572, "s": 7356, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 7673, "s": 7572, "text": "Select any option and press Submit button. We've selected item 3. You will see the selected results." }, { "code": null, "e": 7708, "s": 7673, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7723, "s": 7708, "text": " Chaand Sheikh" }, { "code": null, "e": 7730, "s": 7723, "text": " Print" }, { "code": null, "e": 7741, "s": 7730, "text": " Add Notes" } ]
How to use user variables in MySQL LIKE clause?
Using the CONCAT() function, we can work with user variables in LIKE clause. The syntax is as follows. set @anyVariableName='anyValue'; select yourColumnName1,yourColumnName2,yourColumnName3,...N from yourTableName whereyourColumnName like CONCAT('%', @anyVariableName, '%'); To understand the above syntax, let us first create a table. The query to create a table is as follows. mysql> create table UserVariableInLike -> ( -> id int, -> Name varchar(100), -> Age int -> ); Query OK, 0 rows affected (0.83 sec) Insert records in the table using insert command. The query is as follows. mysql> insert into UserVariableInLike values(101,'John',23); Query OK, 1 row affected (0.23 sec) mysql> insert into UserVariableInLike values(102,'John Smith',24); Query OK, 1 row affected (0.20 sec) mysql> insert into UserVariableInLike values(103,'Carol Smith',23); Query OK, 1 row affected (0.15 sec) mysql> insert into UserVariableInLike values(104,'Johnson',25); Query OK, 1 row affected (0.20 sec) mysql> insert into UserVariableInLike values(105,'Adam Smith',26); Query OK, 1 row affected (0.21 sec) Display all records from the table using select statement. The query is as follows mysql> select *from UserVariableInLike; The following is the output. +------+-------------+------+ | id | Name | Age | +------+-------------+------+ | 101 | John | 23 | | 102 | John Smith | 24 | | 103 | Carol Smith | 23 | | 104 | Johnson | 25 | | 105 | Adam Smith | 26 | +------+-------------+------+ 5 rows in set (0.00 sec) Here is the query which uses the user variable in the LIKE clause. The query is as follows − mysql> set @searchName='John'; Query OK, 0 rows affected (0.00 sec) mysql> select id,Name,Age from UserVariableInLike where Name like CONCAT('%', @searchName, '%'); The following is the output. +------+------------+------+ | id | Name | Age | +------+------------+------+ | 101 | John | 23 | | 102 | JohnSmith | 24 | | 104 | Johnson | 25 | +------+------------+------+ 3 rows in set (0.05 sec)
[ { "code": null, "e": 1165, "s": 1062, "text": "Using the CONCAT() function, we can work with user variables in LIKE clause. The syntax is as follows." }, { "code": null, "e": 1338, "s": 1165, "text": "set @anyVariableName='anyValue';\nselect yourColumnName1,yourColumnName2,yourColumnName3,...N from yourTableName\nwhereyourColumnName like CONCAT('%', @anyVariableName, '%');" }, { "code": null, "e": 1442, "s": 1338, "text": "To understand the above syntax, let us first create a table. The query to create a table is as follows." }, { "code": null, "e": 1573, "s": 1442, "text": "mysql> create table UserVariableInLike\n-> (\n-> id int,\n-> Name varchar(100),\n-> Age int\n-> );\nQuery OK, 0 rows affected (0.83 sec)" }, { "code": null, "e": 1648, "s": 1573, "text": "Insert records in the table using insert command. The query is as follows." }, { "code": null, "e": 2159, "s": 1648, "text": "mysql> insert into UserVariableInLike values(101,'John',23);\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into UserVariableInLike values(102,'John Smith',24);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into UserVariableInLike values(103,'Carol Smith',23);\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into UserVariableInLike values(104,'Johnson',25);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into UserVariableInLike values(105,'Adam Smith',26);\nQuery OK, 1 row affected (0.21 sec)" }, { "code": null, "e": 2242, "s": 2159, "text": "Display all records from the table using select statement. The query is as follows" }, { "code": null, "e": 2282, "s": 2242, "text": "mysql> select *from UserVariableInLike;" }, { "code": null, "e": 2311, "s": 2282, "text": "The following is the output." }, { "code": null, "e": 2606, "s": 2311, "text": "+------+-------------+------+\n| id | Name | Age |\n+------+-------------+------+\n| 101 | John | 23 |\n| 102 | John Smith | 24 |\n| 103 | Carol Smith | 23 |\n| 104 | Johnson | 25 |\n| 105 | Adam Smith | 26 |\n+------+-------------+------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2699, "s": 2606, "text": "Here is the query which uses the user variable in the LIKE clause. The query is as follows −" }, { "code": null, "e": 2865, "s": 2699, "text": "mysql> set @searchName='John';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> select id,Name,Age from UserVariableInLike where Name like CONCAT('%',\n@searchName, '%');" }, { "code": null, "e": 2894, "s": 2865, "text": "The following is the output." }, { "code": null, "e": 3122, "s": 2894, "text": "+------+------------+------+\n| id | Name | Age |\n+------+------------+------+\n| 101 | John | 23 |\n| 102 | JohnSmith | 24 |\n| 104 | Johnson | 25 |\n+------+------------+------+\n3 rows in set (0.05 sec)" } ]
Understand TextRank for Keyword Extraction by Python | by Xu LIANG | Towards Data Science
TextRank is an algorithm based on PageRank, which often used in keyword extraction and text summarization. In this article, I will help you understand how TextRank works with a keyword extraction example and show the implementation by Python. Understand PageRank Implementation of PageRank Keyword Extraction by TextRank Implementation of Keyword Extraction There are tons of articles talking about PageRank, so I just give a brief introduction to PageRank. This will help us understand TextRank later because it is based on PageRank. PageRank (PR) is an algorithm used to calculate the weight for web pages. We can take all web pages as a big directed graph. In this graph, a node is a webpage. If webpage A has the link to web page B, it can be represented as a directed edge from A to B. After we construct the whole graph, we can assign weights for web pages by the following formula. Here is an example to better understand the notation above. We have a graph to represent how web pages link to each other. Each node represents a webpage, and the arrows represent edges. We want to get the weight of webpage e. We can rewrite the summation part in the above function to a simpler version. We can get the weight of webpage e by the following function. We can see the weight of the webpage e is dependent on the weights of its inbound pages. We need to run this iteration much time to get the final weight. In the initialization, the importance of each webpage is 1. We can use a matrix to represent the inbound and outbound links among a, b, e, f in the graph. Each node in a row means the inbound links from other nodes. For example, for the e row, node a and b have outbound links to node e. This presentation will simplify the calculation for updating the weight. According to the 1/|Out(Vi)| from the function, we should normalize each column. We use this matrix to multiply with the weight of all nodes. This is just one iteration without dumping factor d. We can use Python to iterate many times. import numpy as npg = [[0, 0, 0, 0], [0, 0, 0, 0], [1, 0.5, 0, 0], [0, 0.5, 0, 0]]g = np.array(g)pr = np.array([1, 1, 1, 1]) # initialization for a, b, e, f is 1d = 0.85for iter in range(10): pr = 0.15 + 0.85 * np.dot(g, pr) print(iter) print(pr) Output 0[0.15 0.15 1.425 0.575]1[0.15 0.15 0.34125 0.21375]2[0.15 0.15 0.34125 0.21375]3[0.15 0.15 0.34125 0.21375]4[0.15 0.15 0.34125 0.21375]5[0.15 0.15 0.34125 0.21375]6[0.15 0.15 0.34125 0.21375]7[0.15 0.15 0.34125 0.21375]8[0.15 0.15 0.34125 0.21375]9[0.15 0.15 0.34125 0.21375]10[0.15 0.15 0.34125 0.21375] So the weight (PageRank value) of e is 0.34125. If we change the directed edge as the undirected edge, we can change the matrix correspondingly. Normalize it. We should change the code correspondingly. import numpy as npg = [[0, 0, 0.5, 0], [0, 0, 0.5, 1], [1, 0.5, 0, 0], [0, 0.5, 0, 0]]g = np.array(g)pr = np.array([1, 1, 1, 1]) # initialization for a, b, e, f is 1d = 0.85for iter in range(10): pr = 0.15 + 0.85 * np.dot(g, pr) print(iter) print(pr) Output 0[0.575 1.425 1.425 0.575]1[0.755625 1.244375 1.244375 0.755625]2[0.67885937 1.32114062 1.32114062 0.67885937]3[0.71148477 1.28851523 1.28851523 0.71148477]4[0.69761897 1.30238103 1.30238103 0.69761897]5[0.70351194 1.29648806 1.29648806 0.70351194]6[0.70100743 1.29899257 1.29899257 0.70100743]7[0.70207184 1.29792816 1.29792816 0.70207184]8[0.70161947 1.29838053 1.29838053 0.70161947]9[0.70181173 1.29818827 1.29818827 0.70181173] So the weight (PageRank value) of e is 1.29818827. What the difference between TextRank and PageTank? The simple answer is PageRank is for webpage ranking, and TextRank is for text ranking. The webpage in PageRank is the text in TextRank, so the basic idea is the same. Here we have some text, taken from here. I will use spaCy We split a document into several sentences, and we only store those words with specific POS tags. We use spaCy for POS tagging. import spacynlp = spacy.load('en_core_web_sm')content = '''The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics. At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking. While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.'''doc = nlp(content)for sents in doc.sents: print(sents.text) We split the paragraph into three sentences. The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics.At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking.While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse. Because most of the words in a sentence are not useful to determine the importance, we only consider the words with NOUN, PROPN, VERB POS tags. This is optional, you can also use all words. candidate_pos = ['NOUN', 'PROPN', 'VERB']sentences = []​for sent in doc.sents: selected_words = [] for token in sent: if token.pos_ in candidate_pos and token.is_stop is False: selected_words.append(token) sentences.append(selected_words)​print(sentences) Output [[Wandering, Earth, described, China, budget, science, fiction, thriller, screens, AMC, theaters, North, America, weekend, shows, filmmaking, focused, spectacles, China, epics], [time, Wandering, Earth, feels, throwback, eras, filmmaking], [film, cast, setting, tone, science, fiction, fans, going, lot, screen, reminds, movies]] Each word is a node in PageRank. We set the window size as k. [w1, w2, ..., w_k], [w2, w3, ..., w_{k+1}], [w3, w4, ..., w_{k+2}]are windows. Any two-word pairs in a window are considered have an undirected edge. We take [time, Wandering, Earth, feels, throwback, eras, filmmaking] as the example, and set the window size k=4, so we get 4 windows, [time, Wandering, Earth, feels], [Wandering, Earth, feels, throwback], [Earth, feels, throwback, eras], [feels, throwback, eras, filmmaking]. For window [time, Wandering, Earth, feels], any two words pair has an undirected edge. So we get (time, Wandering), (time, Earth), (time, feels), (Wandering, Earth), (Wandering, feels), (Earth, feels). Based on this graph, we can calculate the weight for each node(word). The most important words can be used as keywords. Here I implement a complete example by Python, and we use spaCy to get the POS tag of words. This TextRank4Keyword implements all functions I described in the last section. We can see the output of one paragraph. text = '''The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics. At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking. While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.'''​tr4w = TextRank4Keyword()tr4w.analyze(text, candidate_pos = ['NOUN', 'PROPN'], window_size=4, lower=False)tr4w.get_keywords(10) Output science - 1.717603106506989fiction - 1.6952610926181002filmmaking - 1.4388798751402918China - 1.4259793786986021Earth - 1.3088154732297723tone - 1.1145002295684114Chinese - 1.0996896235078055Wandering - 1.0071059904601571weekend - 1.002449354657688America - 0.9976329264870932budget - 0.9857269586649321North - 0.9711240881032547 Check out my other posts on Medium, with a better TOC list view!GitHub: https://github.com/BrambleXuLinkedIn: www.linkedin.com/in/xu-liangBlog: https://bramblexu.org I also implement TextRank for extracting keywords from news and visualize it. Welcome to check it. github.com Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu
[ { "code": null, "e": 415, "s": 172, "text": "TextRank is an algorithm based on PageRank, which often used in keyword extraction and text summarization. In this article, I will help you understand how TextRank works with a keyword extraction example and show the implementation by Python." }, { "code": null, "e": 435, "s": 415, "text": "Understand PageRank" }, { "code": null, "e": 462, "s": 435, "text": "Implementation of PageRank" }, { "code": null, "e": 493, "s": 462, "text": "Keyword Extraction by TextRank" }, { "code": null, "e": 530, "s": 493, "text": "Implementation of Keyword Extraction" }, { "code": null, "e": 707, "s": 530, "text": "There are tons of articles talking about PageRank, so I just give a brief introduction to PageRank. This will help us understand TextRank later because it is based on PageRank." }, { "code": null, "e": 963, "s": 707, "text": "PageRank (PR) is an algorithm used to calculate the weight for web pages. We can take all web pages as a big directed graph. In this graph, a node is a webpage. If webpage A has the link to web page B, it can be represented as a directed edge from A to B." }, { "code": null, "e": 1061, "s": 963, "text": "After we construct the whole graph, we can assign weights for web pages by the following formula." }, { "code": null, "e": 1288, "s": 1061, "text": "Here is an example to better understand the notation above. We have a graph to represent how web pages link to each other. Each node represents a webpage, and the arrows represent edges. We want to get the weight of webpage e." }, { "code": null, "e": 1366, "s": 1288, "text": "We can rewrite the summation part in the above function to a simpler version." }, { "code": null, "e": 1428, "s": 1366, "text": "We can get the weight of webpage e by the following function." }, { "code": null, "e": 1642, "s": 1428, "text": "We can see the weight of the webpage e is dependent on the weights of its inbound pages. We need to run this iteration much time to get the final weight. In the initialization, the importance of each webpage is 1." }, { "code": null, "e": 1737, "s": 1642, "text": "We can use a matrix to represent the inbound and outbound links among a, b, e, f in the graph." }, { "code": null, "e": 1943, "s": 1737, "text": "Each node in a row means the inbound links from other nodes. For example, for the e row, node a and b have outbound links to node e. This presentation will simplify the calculation for updating the weight." }, { "code": null, "e": 2024, "s": 1943, "text": "According to the 1/|Out(Vi)| from the function, we should normalize each column." }, { "code": null, "e": 2085, "s": 2024, "text": "We use this matrix to multiply with the weight of all nodes." }, { "code": null, "e": 2138, "s": 2085, "text": "This is just one iteration without dumping factor d." }, { "code": null, "e": 2179, "s": 2138, "text": "We can use Python to iterate many times." }, { "code": null, "e": 2447, "s": 2179, "text": "import numpy as npg = [[0, 0, 0, 0], [0, 0, 0, 0], [1, 0.5, 0, 0], [0, 0.5, 0, 0]]g = np.array(g)pr = np.array([1, 1, 1, 1]) # initialization for a, b, e, f is 1d = 0.85for iter in range(10): pr = 0.15 + 0.85 * np.dot(g, pr) print(iter) print(pr)" }, { "code": null, "e": 2454, "s": 2447, "text": "Output" }, { "code": null, "e": 2822, "s": 2454, "text": "0[0.15 0.15 1.425 0.575]1[0.15 0.15 0.34125 0.21375]2[0.15 0.15 0.34125 0.21375]3[0.15 0.15 0.34125 0.21375]4[0.15 0.15 0.34125 0.21375]5[0.15 0.15 0.34125 0.21375]6[0.15 0.15 0.34125 0.21375]7[0.15 0.15 0.34125 0.21375]8[0.15 0.15 0.34125 0.21375]9[0.15 0.15 0.34125 0.21375]10[0.15 0.15 0.34125 0.21375]" }, { "code": null, "e": 2870, "s": 2822, "text": "So the weight (PageRank value) of e is 0.34125." }, { "code": null, "e": 2967, "s": 2870, "text": "If we change the directed edge as the undirected edge, we can change the matrix correspondingly." }, { "code": null, "e": 2981, "s": 2967, "text": "Normalize it." }, { "code": null, "e": 3024, "s": 2981, "text": "We should change the code correspondingly." }, { "code": null, "e": 3296, "s": 3024, "text": "import numpy as npg = [[0, 0, 0.5, 0], [0, 0, 0.5, 1], [1, 0.5, 0, 0], [0, 0.5, 0, 0]]g = np.array(g)pr = np.array([1, 1, 1, 1]) # initialization for a, b, e, f is 1d = 0.85for iter in range(10): pr = 0.15 + 0.85 * np.dot(g, pr) print(iter) print(pr)" }, { "code": null, "e": 3303, "s": 3296, "text": "Output" }, { "code": null, "e": 3736, "s": 3303, "text": "0[0.575 1.425 1.425 0.575]1[0.755625 1.244375 1.244375 0.755625]2[0.67885937 1.32114062 1.32114062 0.67885937]3[0.71148477 1.28851523 1.28851523 0.71148477]4[0.69761897 1.30238103 1.30238103 0.69761897]5[0.70351194 1.29648806 1.29648806 0.70351194]6[0.70100743 1.29899257 1.29899257 0.70100743]7[0.70207184 1.29792816 1.29792816 0.70207184]8[0.70161947 1.29838053 1.29838053 0.70161947]9[0.70181173 1.29818827 1.29818827 0.70181173]" }, { "code": null, "e": 3787, "s": 3736, "text": "So the weight (PageRank value) of e is 1.29818827." }, { "code": null, "e": 3838, "s": 3787, "text": "What the difference between TextRank and PageTank?" }, { "code": null, "e": 4006, "s": 3838, "text": "The simple answer is PageRank is for webpage ranking, and TextRank is for text ranking. The webpage in PageRank is the text in TextRank, so the basic idea is the same." }, { "code": null, "e": 4064, "s": 4006, "text": "Here we have some text, taken from here. I will use spaCy" }, { "code": null, "e": 4192, "s": 4064, "text": "We split a document into several sentences, and we only store those words with specific POS tags. We use spaCy for POS tagging." }, { "code": null, "e": 4922, "s": 4192, "text": "import spacynlp = spacy.load('en_core_web_sm')content = '''The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics. At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking. While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.'''doc = nlp(content)for sents in doc.sents: print(sents.text)" }, { "code": null, "e": 4967, "s": 4922, "text": "We split the paragraph into three sentences." }, { "code": null, "e": 5571, "s": 4967, "text": "The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics.At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking.While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse." }, { "code": null, "e": 5761, "s": 5571, "text": "Because most of the words in a sentence are not useful to determine the importance, we only consider the words with NOUN, PROPN, VERB POS tags. This is optional, you can also use all words." }, { "code": null, "e": 6044, "s": 5761, "text": "candidate_pos = ['NOUN', 'PROPN', 'VERB']sentences = []​for sent in doc.sents: selected_words = [] for token in sent: if token.pos_ in candidate_pos and token.is_stop is False: selected_words.append(token) sentences.append(selected_words)​print(sentences)" }, { "code": null, "e": 6051, "s": 6044, "text": "Output" }, { "code": null, "e": 6381, "s": 6051, "text": "[[Wandering, Earth, described, China, budget, science, fiction, thriller, screens, AMC, theaters, North, America, weekend, shows, filmmaking, focused, spectacles, China, epics], [time, Wandering, Earth, feels, throwback, eras, filmmaking], [film, cast, setting, tone, science, fiction, fans, going, lot, screen, reminds, movies]]" }, { "code": null, "e": 6443, "s": 6381, "text": "Each word is a node in PageRank. We set the window size as k." }, { "code": null, "e": 6593, "s": 6443, "text": "[w1, w2, ..., w_k], [w2, w3, ..., w_{k+1}], [w3, w4, ..., w_{k+2}]are windows. Any two-word pairs in a window are considered have an undirected edge." }, { "code": null, "e": 6870, "s": 6593, "text": "We take [time, Wandering, Earth, feels, throwback, eras, filmmaking] as the example, and set the window size k=4, so we get 4 windows, [time, Wandering, Earth, feels], [Wandering, Earth, feels, throwback], [Earth, feels, throwback, eras], [feels, throwback, eras, filmmaking]." }, { "code": null, "e": 7072, "s": 6870, "text": "For window [time, Wandering, Earth, feels], any two words pair has an undirected edge. So we get (time, Wandering), (time, Earth), (time, feels), (Wandering, Earth), (Wandering, feels), (Earth, feels)." }, { "code": null, "e": 7192, "s": 7072, "text": "Based on this graph, we can calculate the weight for each node(word). The most important words can be used as keywords." }, { "code": null, "e": 7285, "s": 7192, "text": "Here I implement a complete example by Python, and we use spaCy to get the POS tag of words." }, { "code": null, "e": 7405, "s": 7285, "text": "This TextRank4Keyword implements all functions I described in the last section. We can see the output of one paragraph." }, { "code": null, "e": 8152, "s": 7405, "text": "text = '''The Wandering Earth, described as China’s first big-budget science fiction thriller, quietly made it onto screens at AMC theaters in North America this weekend, and it shows a new side of Chinese filmmaking — one focused toward futuristic spectacles rather than China’s traditionally grand, massive historical epics. At the same time, The Wandering Earth feels like a throwback to a few familiar eras of American filmmaking. While the film’s cast, setting, and tone are all Chinese, longtime science fiction fans are going to see a lot on the screen that reminds them of other movies, for better or worse.'''​tr4w = TextRank4Keyword()tr4w.analyze(text, candidate_pos = ['NOUN', 'PROPN'], window_size=4, lower=False)tr4w.get_keywords(10)" }, { "code": null, "e": 8159, "s": 8152, "text": "Output" }, { "code": null, "e": 8489, "s": 8159, "text": "science - 1.717603106506989fiction - 1.6952610926181002filmmaking - 1.4388798751402918China - 1.4259793786986021Earth - 1.3088154732297723tone - 1.1145002295684114Chinese - 1.0996896235078055Wandering - 1.0071059904601571weekend - 1.002449354657688America - 0.9976329264870932budget - 0.9857269586649321North - 0.9711240881032547" }, { "code": null, "e": 8655, "s": 8489, "text": "Check out my other posts on Medium, with a better TOC list view!GitHub: https://github.com/BrambleXuLinkedIn: www.linkedin.com/in/xu-liangBlog: https://bramblexu.org" }, { "code": null, "e": 8754, "s": 8655, "text": "I also implement TextRank for extracting keywords from news and visualize it. Welcome to check it." }, { "code": null, "e": 8765, "s": 8754, "text": "github.com" } ]
Bootstrap 4 .card-group class
Use the card-group class to create a group of cards in Bootstrap 4 − <div class="card-group"> <div class="card bg-success"> <! - - One - - > </div> <div class="card bg-success"> <! - - Two - - > </div> <div class="card bg-success"> <! - - Three - - > </div> </div> Let us create a group of cards like a grid in Bootstrap − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h3>Group of Messages</h3> <div class="card-group"> <div class="card bg-success"> <div class="card-body text-center text-white"> <p class="card-text">Argentina won convincingly!</p> </div> </div> <div class="card bg-primary"> <div class="card-body text-center"> <p class="card-text">Demo Text!</p> </div> </div> <div class="card bg-warning"> <div class="card-body text-center text-white"> <p class="card-text">Do not cross!</p> </div> </div> <div class="card bg-success"> <div class="card-body text-center"> <p class="card-text">I did it!</p> </div> </div> <div class="card bg-success"> <div class="card-body text-center"> <p class="card-text">It worked!</p> </div> </div> </div> </div> </body> </html>
[ { "code": null, "e": 1131, "s": 1062, "text": "Use the card-group class to create a group of cards in Bootstrap 4 −" }, { "code": null, "e": 1359, "s": 1131, "text": "<div class=\"card-group\">\n\n <div class=\"card bg-success\">\n <! - - One - - >\n </div>\n <div class=\"card bg-success\">\n <! - - Two - - >\n </div>\n <div class=\"card bg-success\">\n <! - - Three - - >\n </div>\n\n</div>" }, { "code": null, "e": 1417, "s": 1359, "text": "Let us create a group of cards like a grid in Bootstrap −" }, { "code": null, "e": 1427, "s": 1417, "text": "Live Demo" }, { "code": null, "e": 2850, "s": 1427, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js\"></script>\n </head>\n<body>\n <div class=\"container\">\n <h3>Group of Messages</h3>\n <div class=\"card-group\">\n <div class=\"card bg-success\">\n <div class=\"card-body text-center text-white\">\n <p class=\"card-text\">Argentina won convincingly!</p>\n </div>\n </div>\n <div class=\"card bg-primary\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">Demo Text!</p>\n </div>\n </div>\n <div class=\"card bg-warning\">\n <div class=\"card-body text-center text-white\">\n <p class=\"card-text\">Do not cross!</p>\n </div>\n </div>\n <div class=\"card bg-success\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">I did it!</p>\n </div>\n </div>\n <div class=\"card bg-success\">\n <div class=\"card-body text-center\">\n <p class=\"card-text\">It worked!</p>\n </div>\n </div>\n </div>\n </div>\n</body>\n</html>" } ]
Dimensionality Reduction for Data Visualization: PCA vs TSNE vs UMAP vs LDA | by Sivakar Sivarajah | Towards Data Science
In this story, we are gonna go through three Dimensionality reduction techniques specifically used for Data Visualization: PCA, t-SNE, LDA and UMAP. We are going to explore them in details using the Sign Language MNIST Dataset, without going in-depth with the maths behind the algorithms. Many Machine Learning problems involve thousands of features, having such a large number of features bring along many problems, the most important ones are: Makes the training extremely slow Makes it difficult to find a good solution This is known as the curse of dimensionality and the Dimensionality Reduction is the process of reducing the number of features to the most relevant ones in simple terms. Reducing the dimensionality does lose some information, however as most compressing processes it comes with some drawbacks, even though we get the training faster, we make the system perform slightly worse, but this is ok! “sometimes reducing the dimensionality can filter out some of the noise present and some of the unnecessary details”. Most Dimensionality Reduction applications are used for: Data Compression Noise Reduction Data Classification Data Visualization One of the most important aspects of Dimensionality reduction, it is Data Visualization. Having to drop the dimensionality down to two or three, make it possible to visualize the data on a 2d or 3d plot, meaning important insights can be gained by analysing these patterns in terms of clusters and much more. The two main approaches to reducing dimensionality: Projection and Manifold Learning. Projection: This technique deals with projecting every data point which is in high dimension, onto a subspace suitable lower-dimensional space in a way which approximately preserves the distances between the points. Manifold Learning: Many dimensionality reductions algorithm work by modelling the manifold on which the training instance lie; this is called Manifold learning. It relies on the manifold hypothesis or assumption, which holds that most real-world high-dimensional datasets lie close to a much lower-dimensional manifold, this assumption in most of the cases is based on observation or experience rather than theory or pure logic.[4] Now let's briefly explain the three techniques before jumping into solving the use case. One of the most known dimensionality reduction “unsupervised” algorithm is PCA(Principal Component Analysis). This works by identifying the hyperplane which lies closest to the data and then projects the data on that hyperplane while retaining most of the variation in the data set. The axis that explains the maximum amount of variance in the training set is called the Principal Components. The axis orthogonal to this axis is called the second principal component. As we go for higher dimensions, PCA would find a third component orthogonal to the other two components and so on, for visualization purposes we always stick to 2 or maximum 3 principal components. It is very important to choose the right hyperplane so that when the data is projected onto it, it the maximum amount of information about how the original data is distributed. (t-SNE) or T-distributed stochastic neighbour embedding created in 2008 by (Laurens van der Maaten and Geoffrey Hinton) for dimensionality reduction that is particularly well suited for the visualization of high-dimensional datasets. (t-SNE) takes a high dimensional data set and reduces it to a low dimensional graph that retains a lot of the original information. It does so by giving each data point a location in a two or three-dimensional map. This technique finds clusters in data thereby making sure that an embedding preserves the meaning in the data. t-SNE reduces dimensionality while trying to keep similar instances close and dissimilar instances apart.[2] For a quick a Visualization of this technique, refer to the animation below (it is taken from an amazing tutorial by Cyrille Rossant, I highly recommend to check out his amazing tutorial. link: https://www.oreilly.com/content/an-illustrated-introduction-to-the-t-sne-algorithm/ Linear Discriminant Analysis (LDA) is most commonly used as a dimensionality reduction technique in the pre-processing step for pattern-classification. The goal is to project a dataset onto a lower-dimensional space with good class-separability in order to avoid overfitting and also reduce computational costs. The general approach is very similar to PCA, rather than finding the component axes that maximize the variance of our data, we are additionally interested in the axes that maximize the separation between multiple classes (LDA)[5]. LDA is “supervised” and computes the directions (“linear discriminants”) that will represent the axes that maximize the separation between multiple classes. Uniform Manifold Approximation and Projection created in 2018 by (Leland McInnes, John Healy, James Melville) is a general-purpose manifold learning and dimension reduction algorithm. UMAP is a nonlinear dimensionality reduction method, it is very effective for visualizing clusters or groups of data points and their relative proximities. The significant difference with TSNE is scalability, it can be applied directly to sparse matrices thereby eliminating the need to applying any Dimensionality reduction such as PCA or Truncated SVD(Singular Value Decomposition) as a prior pre-processing step.[1] Put simply, it is similar to t-SNE but with probably higher processing speed, therefore, faster and probably better visualization. (let’s find it out in the tutorial below) Now we are going to go through the above-mentioned use case where all the three techniques will be applied: specifically, we will try to visualize a high dimensional dataset using these techniques: The Sign-Language-MNIST Dataset:https://www.kaggle.com/datamunge/sign-language-mnist Note that: There are 25 unique labels representing the number of distinct sign-languages. Now for better visualization (“ it is very difficult to observe all 24 classes in a single visualization”) and for faster computation. I am only keeping the first 10 labels, omitting the rest. After applying PCA, the new dimensionality of the data now has only 3 features compared to the 784 features of the x data. The number of dimensions has been cut down drastically whilst trying to retain as much of the ‘variation’ in the information as possible. plot_2d(principalComponents[:, 0],principalComponents[:, 1]) From the 2D plot, we can see the two components definitely hold some information, especially for specific digits, but clearly not enough to set all of them apart. plot_3d(principalComponents[:, 0],principalComponents[:, 1],principalComponents[:, 2]) One thing to note down is that t-SNE is very computationally expensive, hence it is mentioned in its documentation that : “It is highly recommended to use another dimensionality reduction method (e.g. PCA for dense data or TruncatedSVD for sparse data) to reduce the number of dimensions to a reasonable amount (e.g. 50) if the number of features is very high. This will suppress some noise and speed up the computation of pairwise distances between samples.”[2] Thus, I have applied PCA choosing to retain 50 principal components from the original data to cut down the need for more processing power and it will require time to compute the dimensionality reduction if we had considered the original data. The speed of the three techniques will be analysed and compared in the following sections further down in details. plot_2d(tsne[:, 0],tsne[:, 1]) Compared to the PCA 2d result, we can clearly see the presence of different clusters and how they are positioned. plot_3d(tsne[:, 0],tsne[:, 1],tsne[:, 2]) UMAP has different hyperparameters that can have an impact on the resulting embeddings: n_neighbors This parameter controls how UMAP balances local versus global structure in the data. This low values of n_neighbours forces UMAP to focus on very local structures while the higher values will make UMAP focus on the larger neighbourhoods. min_dist This parameter controls how tightly UMAP is allowed to pack points together. Lower values mean the points will be clustered closely and vice versa. n_components This parameter allows the user to determine the dimensionality of the reduced dimension space. metric This parameter controls how distance is computed in the ambient space of the input data. For more detailed information, I suggest to check out the UMAP documentation://umap-learn.readthedocs.io/en/latest/ For this tutorial, I have chosen to keep the default setting apart for n_components which I set to 3 for the 3d space plot. It would be best to experiment with different hyper-parameter settings to obtain the best out of the algorithm. plot_2d(reducer.embedding_[:, 0],reducer.embedding_[:, 1]) We can clearly see that the UMAP does a great job in separating the data points compared to t-SNE and PCA in terms of separation. However, there are no big clusters separating the sign sufficiently, There are similar data points agglomerated together in other parts too from a 2d prospective. plot_3d(reducer.embedding_[:, 0],reducer.embedding_[:, 1],reducer.embedding_[:, 2]) plot_2d(X_LDA[:, 0],X_LDA[:, 1]) With LDA we can clearly identify the presence of these nine clusters with a significant separation. If with UMAP and t-SNE we could barely see the backbone of the clusters with LDA we can see the whole clusters of data points agglomerated in the same cluster zones. plot_3d(X_LDA[:, 0],X_LDA[:, 1],X_LDA[:, 2]) Note that: the above table was constructed considering the computation time taken on a Kernel on Kaggle using their GPU. PCA was not able to do such a good job in differentiating the signs. The main drawback of PCA is that it is highly influenced by outliers present in the data. PCA is a linear projection, which means it can’t capture non-linear dependencies, its goal is to find the directions (the so-called principal components) that maximize the variance in a dataset. t-SNE does a better job(it tries to preserve topology neighbourhood structure) as compared to PCA when it comes to visualising the different patterns of the clusters. Similar labels are clustered together, even though there are big agglomerates of data points on top of each other, certainly not good enough to expect a clustering algorithm to perform well. UMAP outperformed t-SNE and PCA, if we look at the 2d and 3d plot, we can see mini-clusters that are being separated well. It is very effective for visualizing clusters or groups of data points and their relative proximities. However, for this use case certainly not good enough to expect a clustering algorithm to distinguish the patterns.UMAP is much faster than t-SNE, another problem faced by the latter is the need for another dimensionality reduction method prior, otherwise, it would take a longer time to compute. Finally, LDA outperformed all the previous techniques in all aspects. Excellent computation time (second fastest) as well as proving the well-separated clusters we were expecting. Note: it is not surprising that LDA performed better than the other techiniques ,that was what we were expecting . PCA, TSNE and UMAP are performed without the knowledge of the true class label, unlike LDA. We have explored four dimensionality reduction techniques for data visualization : (PCA, t-SNE, UMAP, LDA)and tried to use them to visualize a high-dimensional dataset in 2d and 3d plots. Note: It is not difficult to fall into the trap of considering one technique better than the other, at the end of the day there is no way to map a high-dimensional data into low dimensions and preserving the whole structure at the same time, there is always a trade-off of qualities one technique will have compared to the other. Thanks again for reaching until here, hope it has been an informative post! worth your time. There are many other variants and many other use cases, I highly encourage you to explore this amazing and well-developed area of Science. [1] McInnes, L., & Healy, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction. ArXiv e-prints. [2] van der Maaten, L.J.P. t-Distributed Stochastic Neighbor Embedding lvdmaaten.github.io [3]Kaggle.com. 2020. Visualizing Kannada MNIST With T-SNE. Available at: https://www.kaggle.com/parulpandey/visualizing-kannada-mnist-with-t-sne [4]Hands on Machine Learning with Scikit-Learn, Keras & Tensorflow by Aurelien Geron
[ { "code": null, "e": 461, "s": 172, "text": "In this story, we are gonna go through three Dimensionality reduction techniques specifically used for Data Visualization: PCA, t-SNE, LDA and UMAP. We are going to explore them in details using the Sign Language MNIST Dataset, without going in-depth with the maths behind the algorithms." }, { "code": null, "e": 618, "s": 461, "text": "Many Machine Learning problems involve thousands of features, having such a large number of features bring along many problems, the most important ones are:" }, { "code": null, "e": 652, "s": 618, "text": "Makes the training extremely slow" }, { "code": null, "e": 695, "s": 652, "text": "Makes it difficult to find a good solution" }, { "code": null, "e": 866, "s": 695, "text": "This is known as the curse of dimensionality and the Dimensionality Reduction is the process of reducing the number of features to the most relevant ones in simple terms." }, { "code": null, "e": 1207, "s": 866, "text": "Reducing the dimensionality does lose some information, however as most compressing processes it comes with some drawbacks, even though we get the training faster, we make the system perform slightly worse, but this is ok! “sometimes reducing the dimensionality can filter out some of the noise present and some of the unnecessary details”." }, { "code": null, "e": 1264, "s": 1207, "text": "Most Dimensionality Reduction applications are used for:" }, { "code": null, "e": 1281, "s": 1264, "text": "Data Compression" }, { "code": null, "e": 1297, "s": 1281, "text": "Noise Reduction" }, { "code": null, "e": 1317, "s": 1297, "text": "Data Classification" }, { "code": null, "e": 1336, "s": 1317, "text": "Data Visualization" }, { "code": null, "e": 1645, "s": 1336, "text": "One of the most important aspects of Dimensionality reduction, it is Data Visualization. Having to drop the dimensionality down to two or three, make it possible to visualize the data on a 2d or 3d plot, meaning important insights can be gained by analysing these patterns in terms of clusters and much more." }, { "code": null, "e": 1731, "s": 1645, "text": "The two main approaches to reducing dimensionality: Projection and Manifold Learning." }, { "code": null, "e": 1947, "s": 1731, "text": "Projection: This technique deals with projecting every data point which is in high dimension, onto a subspace suitable lower-dimensional space in a way which approximately preserves the distances between the points." }, { "code": null, "e": 2379, "s": 1947, "text": "Manifold Learning: Many dimensionality reductions algorithm work by modelling the manifold on which the training instance lie; this is called Manifold learning. It relies on the manifold hypothesis or assumption, which holds that most real-world high-dimensional datasets lie close to a much lower-dimensional manifold, this assumption in most of the cases is based on observation or experience rather than theory or pure logic.[4]" }, { "code": null, "e": 2468, "s": 2379, "text": "Now let's briefly explain the three techniques before jumping into solving the use case." }, { "code": null, "e": 2578, "s": 2468, "text": "One of the most known dimensionality reduction “unsupervised” algorithm is PCA(Principal Component Analysis)." }, { "code": null, "e": 2751, "s": 2578, "text": "This works by identifying the hyperplane which lies closest to the data and then projects the data on that hyperplane while retaining most of the variation in the data set." }, { "code": null, "e": 2861, "s": 2751, "text": "The axis that explains the maximum amount of variance in the training set is called the Principal Components." }, { "code": null, "e": 3134, "s": 2861, "text": "The axis orthogonal to this axis is called the second principal component. As we go for higher dimensions, PCA would find a third component orthogonal to the other two components and so on, for visualization purposes we always stick to 2 or maximum 3 principal components." }, { "code": null, "e": 3311, "s": 3134, "text": "It is very important to choose the right hyperplane so that when the data is projected onto it, it the maximum amount of information about how the original data is distributed." }, { "code": null, "e": 3545, "s": 3311, "text": "(t-SNE) or T-distributed stochastic neighbour embedding created in 2008 by (Laurens van der Maaten and Geoffrey Hinton) for dimensionality reduction that is particularly well suited for the visualization of high-dimensional datasets." }, { "code": null, "e": 3980, "s": 3545, "text": "(t-SNE) takes a high dimensional data set and reduces it to a low dimensional graph that retains a lot of the original information. It does so by giving each data point a location in a two or three-dimensional map. This technique finds clusters in data thereby making sure that an embedding preserves the meaning in the data. t-SNE reduces dimensionality while trying to keep similar instances close and dissimilar instances apart.[2]" }, { "code": null, "e": 4168, "s": 3980, "text": "For a quick a Visualization of this technique, refer to the animation below (it is taken from an amazing tutorial by Cyrille Rossant, I highly recommend to check out his amazing tutorial." }, { "code": null, "e": 4258, "s": 4168, "text": "link: https://www.oreilly.com/content/an-illustrated-introduction-to-the-t-sne-algorithm/" }, { "code": null, "e": 4410, "s": 4258, "text": "Linear Discriminant Analysis (LDA) is most commonly used as a dimensionality reduction technique in the pre-processing step for pattern-classification." }, { "code": null, "e": 4570, "s": 4410, "text": "The goal is to project a dataset onto a lower-dimensional space with good class-separability in order to avoid overfitting and also reduce computational costs." }, { "code": null, "e": 4801, "s": 4570, "text": "The general approach is very similar to PCA, rather than finding the component axes that maximize the variance of our data, we are additionally interested in the axes that maximize the separation between multiple classes (LDA)[5]." }, { "code": null, "e": 4958, "s": 4801, "text": "LDA is “supervised” and computes the directions (“linear discriminants”) that will represent the axes that maximize the separation between multiple classes." }, { "code": null, "e": 5142, "s": 4958, "text": "Uniform Manifold Approximation and Projection created in 2018 by (Leland McInnes, John Healy, James Melville) is a general-purpose manifold learning and dimension reduction algorithm." }, { "code": null, "e": 5298, "s": 5142, "text": "UMAP is a nonlinear dimensionality reduction method, it is very effective for visualizing clusters or groups of data points and their relative proximities." }, { "code": null, "e": 5561, "s": 5298, "text": "The significant difference with TSNE is scalability, it can be applied directly to sparse matrices thereby eliminating the need to applying any Dimensionality reduction such as PCA or Truncated SVD(Singular Value Decomposition) as a prior pre-processing step.[1]" }, { "code": null, "e": 5734, "s": 5561, "text": "Put simply, it is similar to t-SNE but with probably higher processing speed, therefore, faster and probably better visualization. (let’s find it out in the tutorial below)" }, { "code": null, "e": 6017, "s": 5734, "text": "Now we are going to go through the above-mentioned use case where all the three techniques will be applied: specifically, we will try to visualize a high dimensional dataset using these techniques: The Sign-Language-MNIST Dataset:https://www.kaggle.com/datamunge/sign-language-mnist" }, { "code": null, "e": 6300, "s": 6017, "text": "Note that: There are 25 unique labels representing the number of distinct sign-languages. Now for better visualization (“ it is very difficult to observe all 24 classes in a single visualization”) and for faster computation. I am only keeping the first 10 labels, omitting the rest." }, { "code": null, "e": 6423, "s": 6300, "text": "After applying PCA, the new dimensionality of the data now has only 3 features compared to the 784 features of the x data." }, { "code": null, "e": 6561, "s": 6423, "text": "The number of dimensions has been cut down drastically whilst trying to retain as much of the ‘variation’ in the information as possible." }, { "code": null, "e": 6622, "s": 6561, "text": "plot_2d(principalComponents[:, 0],principalComponents[:, 1])" }, { "code": null, "e": 6785, "s": 6622, "text": "From the 2D plot, we can see the two components definitely hold some information, especially for specific digits, but clearly not enough to set all of them apart." }, { "code": null, "e": 6872, "s": 6785, "text": "plot_3d(principalComponents[:, 0],principalComponents[:, 1],principalComponents[:, 2])" }, { "code": null, "e": 6994, "s": 6872, "text": "One thing to note down is that t-SNE is very computationally expensive, hence it is mentioned in its documentation that :" }, { "code": null, "e": 7335, "s": 6994, "text": "“It is highly recommended to use another dimensionality reduction method (e.g. PCA for dense data or TruncatedSVD for sparse data) to reduce the number of dimensions to a reasonable amount (e.g. 50) if the number of features is very high. This will suppress some noise and speed up the computation of pairwise distances between samples.”[2]" }, { "code": null, "e": 7578, "s": 7335, "text": "Thus, I have applied PCA choosing to retain 50 principal components from the original data to cut down the need for more processing power and it will require time to compute the dimensionality reduction if we had considered the original data." }, { "code": null, "e": 7693, "s": 7578, "text": "The speed of the three techniques will be analysed and compared in the following sections further down in details." }, { "code": null, "e": 7724, "s": 7693, "text": "plot_2d(tsne[:, 0],tsne[:, 1])" }, { "code": null, "e": 7838, "s": 7724, "text": "Compared to the PCA 2d result, we can clearly see the presence of different clusters and how they are positioned." }, { "code": null, "e": 7880, "s": 7838, "text": "plot_3d(tsne[:, 0],tsne[:, 1],tsne[:, 2])" }, { "code": null, "e": 7968, "s": 7880, "text": "UMAP has different hyperparameters that can have an impact on the resulting embeddings:" }, { "code": null, "e": 7980, "s": 7968, "text": "n_neighbors" }, { "code": null, "e": 8218, "s": 7980, "text": "This parameter controls how UMAP balances local versus global structure in the data. This low values of n_neighbours forces UMAP to focus on very local structures while the higher values will make UMAP focus on the larger neighbourhoods." }, { "code": null, "e": 8227, "s": 8218, "text": "min_dist" }, { "code": null, "e": 8375, "s": 8227, "text": "This parameter controls how tightly UMAP is allowed to pack points together. Lower values mean the points will be clustered closely and vice versa." }, { "code": null, "e": 8388, "s": 8375, "text": "n_components" }, { "code": null, "e": 8483, "s": 8388, "text": "This parameter allows the user to determine the dimensionality of the reduced dimension space." }, { "code": null, "e": 8490, "s": 8483, "text": "metric" }, { "code": null, "e": 8579, "s": 8490, "text": "This parameter controls how distance is computed in the ambient space of the input data." }, { "code": null, "e": 8695, "s": 8579, "text": "For more detailed information, I suggest to check out the UMAP documentation://umap-learn.readthedocs.io/en/latest/" }, { "code": null, "e": 8931, "s": 8695, "text": "For this tutorial, I have chosen to keep the default setting apart for n_components which I set to 3 for the 3d space plot. It would be best to experiment with different hyper-parameter settings to obtain the best out of the algorithm." }, { "code": null, "e": 8990, "s": 8931, "text": "plot_2d(reducer.embedding_[:, 0],reducer.embedding_[:, 1])" }, { "code": null, "e": 9283, "s": 8990, "text": "We can clearly see that the UMAP does a great job in separating the data points compared to t-SNE and PCA in terms of separation. However, there are no big clusters separating the sign sufficiently, There are similar data points agglomerated together in other parts too from a 2d prospective." }, { "code": null, "e": 9367, "s": 9283, "text": "plot_3d(reducer.embedding_[:, 0],reducer.embedding_[:, 1],reducer.embedding_[:, 2])" }, { "code": null, "e": 9400, "s": 9367, "text": "plot_2d(X_LDA[:, 0],X_LDA[:, 1])" }, { "code": null, "e": 9666, "s": 9400, "text": "With LDA we can clearly identify the presence of these nine clusters with a significant separation. If with UMAP and t-SNE we could barely see the backbone of the clusters with LDA we can see the whole clusters of data points agglomerated in the same cluster zones." }, { "code": null, "e": 9711, "s": 9666, "text": "plot_3d(X_LDA[:, 0],X_LDA[:, 1],X_LDA[:, 2])" }, { "code": null, "e": 9832, "s": 9711, "text": "Note that: the above table was constructed considering the computation time taken on a Kernel on Kaggle using their GPU." }, { "code": null, "e": 10186, "s": 9832, "text": "PCA was not able to do such a good job in differentiating the signs. The main drawback of PCA is that it is highly influenced by outliers present in the data. PCA is a linear projection, which means it can’t capture non-linear dependencies, its goal is to find the directions (the so-called principal components) that maximize the variance in a dataset." }, { "code": null, "e": 10544, "s": 10186, "text": "t-SNE does a better job(it tries to preserve topology neighbourhood structure) as compared to PCA when it comes to visualising the different patterns of the clusters. Similar labels are clustered together, even though there are big agglomerates of data points on top of each other, certainly not good enough to expect a clustering algorithm to perform well." }, { "code": null, "e": 11066, "s": 10544, "text": "UMAP outperformed t-SNE and PCA, if we look at the 2d and 3d plot, we can see mini-clusters that are being separated well. It is very effective for visualizing clusters or groups of data points and their relative proximities. However, for this use case certainly not good enough to expect a clustering algorithm to distinguish the patterns.UMAP is much faster than t-SNE, another problem faced by the latter is the need for another dimensionality reduction method prior, otherwise, it would take a longer time to compute." }, { "code": null, "e": 11246, "s": 11066, "text": "Finally, LDA outperformed all the previous techniques in all aspects. Excellent computation time (second fastest) as well as proving the well-separated clusters we were expecting." }, { "code": null, "e": 11453, "s": 11246, "text": "Note: it is not surprising that LDA performed better than the other techiniques ,that was what we were expecting . PCA, TSNE and UMAP are performed without the knowledge of the true class label, unlike LDA." }, { "code": null, "e": 11641, "s": 11453, "text": "We have explored four dimensionality reduction techniques for data visualization : (PCA, t-SNE, UMAP, LDA)and tried to use them to visualize a high-dimensional dataset in 2d and 3d plots." }, { "code": null, "e": 11971, "s": 11641, "text": "Note: It is not difficult to fall into the trap of considering one technique better than the other, at the end of the day there is no way to map a high-dimensional data into low dimensions and preserving the whole structure at the same time, there is always a trade-off of qualities one technique will have compared to the other." }, { "code": null, "e": 12203, "s": 11971, "text": "Thanks again for reaching until here, hope it has been an informative post! worth your time. There are many other variants and many other use cases, I highly encourage you to explore this amazing and well-developed area of Science." }, { "code": null, "e": 12333, "s": 12203, "text": "[1] McInnes, L., & Healy, J. (2018). UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction. ArXiv e-prints." }, { "code": null, "e": 12404, "s": 12333, "text": "[2] van der Maaten, L.J.P. t-Distributed Stochastic Neighbor Embedding" }, { "code": null, "e": 12424, "s": 12404, "text": "lvdmaaten.github.io" }, { "code": null, "e": 12569, "s": 12424, "text": "[3]Kaggle.com. 2020. Visualizing Kannada MNIST With T-SNE. Available at: https://www.kaggle.com/parulpandey/visualizing-kannada-mnist-with-t-sne" } ]