title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Install Pygame in MacOS
09 May, 2021 PyGame is a collection of modules that break through the language of Python applications. These modules are designed to edit video games. PyGame, therefore, includes computer graphics and audio libraries created for the use and language of Python programs. At first, open the Terminal which is located at Applications -> Utilities -> Terminal and make sure that the Python3 is installed in your system. If it is not installed then type the below command. brew install python3 XCode: The first step for PyGame is to install Apple’s Xcode program. In your Terminal app, enter and run the following command to install XCode. xcode-select --install Be sure to click on all the verification recommendations that require XCode We can now install the latest version of PyGame. Type the following command in Terminal and press Enter. pip3 install pygame To test if PyGame has been installed on your Mac, open terminal and type python, and import pygame as follows If you don’t see any errors, it means that PyGame has been successfully installed on your Mac. Picked Python-PyGame 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 Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n09 May, 2021" }, { "code": null, "e": 285, "s": 28, "text": "PyGame is a collection of modules that break through the language of Python applications. These modules are designed to edit video games. PyGame, therefore, includes computer graphics and audio libraries created for the use and language of Python programs." }, { "code": null, "e": 483, "s": 285, "text": "At first, open the Terminal which is located at Applications -> Utilities -> Terminal and make sure that the Python3 is installed in your system. If it is not installed then type the below command." }, { "code": null, "e": 504, "s": 483, "text": "brew install python3" }, { "code": null, "e": 650, "s": 504, "text": "XCode: The first step for PyGame is to install Apple’s Xcode program. In your Terminal app, enter and run the following command to install XCode." }, { "code": null, "e": 673, "s": 650, "text": "xcode-select --install" }, { "code": null, "e": 749, "s": 673, "text": "Be sure to click on all the verification recommendations that require XCode" }, { "code": null, "e": 854, "s": 749, "text": "We can now install the latest version of PyGame. Type the following command in Terminal and press Enter." }, { "code": null, "e": 874, "s": 854, "text": "pip3 install pygame" }, { "code": null, "e": 984, "s": 874, "text": "To test if PyGame has been installed on your Mac, open terminal and type python, and import pygame as follows" }, { "code": null, "e": 1079, "s": 984, "text": "If you don’t see any errors, it means that PyGame has been successfully installed on your Mac." }, { "code": null, "e": 1086, "s": 1079, "text": "Picked" }, { "code": null, "e": 1100, "s": 1086, "text": "Python-PyGame" }, { "code": null, "e": 1107, "s": 1100, "text": "Python" }, { "code": null, "e": 1205, "s": 1107, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1237, "s": 1205, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1264, "s": 1237, "text": "Python Classes and Objects" }, { "code": null, "e": 1285, "s": 1264, "text": "Python OOPs Concepts" }, { "code": null, "e": 1316, "s": 1285, "text": "Python | os.path.join() method" }, { "code": null, "e": 1372, "s": 1316, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1395, "s": 1372, "text": "Introduction To PYTHON" }, { "code": null, "e": 1437, "s": 1395, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1479, "s": 1437, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1518, "s": 1479, "text": "Python | datetime.timedelta() function" } ]
Python | All occurrences of substring in string
25 Jun, 2019 Many times while working with strings, we have problems dealing with substrings. This may include the problem of finding all positions of a particular substrings in a string. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + startswith()This task can be performed using the two functionalities. The startswith function primarily performs the task of getting the starting indices of substring and list comprehension is used to iterate through the whole target string. # Python3 code to demonstrate working of# All occurrences of substring in string# Using list comprehension + startswith() # initializing string test_str = "GeeksforGeeks is best for Geeks" # initializing substringtest_sub = "Geeks" # printing original string print("The original string is : " + test_str) # printing substring print("The substring to find : " + test_sub) # using list comprehension + startswith()# All occurrences of substring in string res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)] # printing result print("The start indices of the substrings are : " + str(res)) The original string is : GeeksforGeeks is best for Geeks The substring to find : Geeks The start indices of the substrings are : [0, 8, 26] Method #2 : Using re.finditer()The finditer function of the regex library can help us perform the task of finding the occurrences of the substring in the target string and the start function can return the resultant index of each of them. # Python3 code to demonstrate working of# All occurrences of substring in string# Using re.finditer()import re # initializing string test_str = "GeeksforGeeks is best for Geeks" # initializing substringtest_sub = "Geeks" # printing original string print("The original string is : " + test_str) # printing substring print("The substring to find : " + test_sub) # using re.finditer()# All occurrences of substring in string res = [i.start() for i in re.finditer(test_sub, test_str)] # printing result print("The start indices of the substrings are : " + str(res)) The original string is : GeeksforGeeks is best for Geeks The substring to find : Geeks The start indices of the substrings are : [0, 8, 26] Python string-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 How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 53, "s": 25, "text": "\n25 Jun, 2019" }, { "code": null, "e": 292, "s": 53, "text": "Many times while working with strings, we have problems dealing with substrings. This may include the problem of finding all positions of a particular substrings in a string. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 573, "s": 292, "text": "Method #1 : Using list comprehension + startswith()This task can be performed using the two functionalities. The startswith function primarily performs the task of getting the starting indices of substring and list comprehension is used to iterate through the whole target string." }, { "code": "# Python3 code to demonstrate working of# All occurrences of substring in string# Using list comprehension + startswith() # initializing string test_str = \"GeeksforGeeks is best for Geeks\" # initializing substringtest_sub = \"Geeks\" # printing original string print(\"The original string is : \" + test_str) # printing substring print(\"The substring to find : \" + test_sub) # using list comprehension + startswith()# All occurrences of substring in string res = [i for i in range(len(test_str)) if test_str.startswith(test_sub, i)] # printing result print(\"The start indices of the substrings are : \" + str(res))", "e": 1189, "s": 573, "text": null }, { "code": null, "e": 1330, "s": 1189, "text": "The original string is : GeeksforGeeks is best for Geeks\nThe substring to find : Geeks\nThe start indices of the substrings are : [0, 8, 26]\n" }, { "code": null, "e": 1571, "s": 1332, "text": "Method #2 : Using re.finditer()The finditer function of the regex library can help us perform the task of finding the occurrences of the substring in the target string and the start function can return the resultant index of each of them." }, { "code": "# Python3 code to demonstrate working of# All occurrences of substring in string# Using re.finditer()import re # initializing string test_str = \"GeeksforGeeks is best for Geeks\" # initializing substringtest_sub = \"Geeks\" # printing original string print(\"The original string is : \" + test_str) # printing substring print(\"The substring to find : \" + test_sub) # using re.finditer()# All occurrences of substring in string res = [i.start() for i in re.finditer(test_sub, test_str)] # printing result print(\"The start indices of the substrings are : \" + str(res))", "e": 2139, "s": 1571, "text": null }, { "code": null, "e": 2280, "s": 2139, "text": "The original string is : GeeksforGeeks is best for Geeks\nThe substring to find : Geeks\nThe start indices of the substrings are : [0, 8, 26]\n" }, { "code": null, "e": 2303, "s": 2280, "text": "Python string-programs" }, { "code": null, "e": 2310, "s": 2303, "text": "Python" }, { "code": null, "e": 2326, "s": 2310, "text": "Python Programs" }, { "code": null, "e": 2424, "s": 2326, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2466, "s": 2424, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2488, "s": 2466, "text": "Enumerate() in Python" }, { "code": null, "e": 2520, "s": 2488, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2549, "s": 2520, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2576, "s": 2549, "text": "Python Classes and Objects" }, { "code": null, "e": 2598, "s": 2576, "text": "Defaultdict in Python" }, { "code": null, "e": 2637, "s": 2598, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2675, "s": 2637, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2724, "s": 2675, "text": "Python | Convert string dictionary to dictionary" } ]
EIGRP Configuration
03 Dec, 2021 Prerequisite – EIGRP fundamentalsEnhanced Interior Gateway Routing Protocol (EIGRP) is a dynamic routing network-layer Protocol which works on protocol number 88. EIGRP supports classless routing, VLSM, route summarization, load balancing, and many other useful features. It is a Cisco proprietary protocol, so all routers in a network that is running EIGRP must be Cisco routers but now EIGRP is moving towards becoming an open standard protocol. EIGRP exchange messages for communication between the routers operating EIGRP. Configuration – There is small topology in which there are 3 routers (on which user will configure EIGRP) namely GfGNoida, GfGDelhi, GfGBangalore. As seen, GfGBangalore router has to advertise the networks 10.10.10.0/24, 10.10.11.0/24, 172.16.10.0/30, 172.16.10.4/30. Therefore now configuring EIGRP for router GfGBangalore. GfGB(config)#router eigrp 1 GfGB(config-router)#network 10.10.10.0 GfGB(config-router)#network 10.10.11.0 GfGB(config-router)#network 172.16.10.0 GfGB(config-router)#network 172.16.10.4 Here, first created an EIGRP instance by router eigrp 1command where 1 is the autonomous system number. Now, for configuring EIGRP for GfGDelhi router, the network to be advertised are 10.10.40.0/24, 10.10.50.0/24 and 172.16.10.4/30 GfGDelhi(config)#router eigrp 1 GfGDelhi(config-router)#network 172.16.10.4 GfGDelhi(config-router)#network 10.10.50.0 GfGDelhi(config-router)#network 10.10.40.0 Now, similarly configuring EIGRP for GfGNoida, the networks to be advertised are 10.10.20.0/24, 10.10.30.0/24, 172.16.10.0/30 GfGN(config)#router eigrp 1 GfGN(config-router)#network 172.16.10.0 GfGN(config-router)#network 10.10.20.0 GfGN(config-router)#network 10.10.30.0 This is a simple configuration in which user has to write the network I’d of the network to be advertised with network command. Troubleshooting –As configured EIGRP, user should see problems occurring in forming neighbourship between EIGRP operating routers. The neighbourship will not be formed if: the interface is configured as passive the k values doesn’t match the autonomous system number is different EIGRP authentication is misconfigured interface between devices are down If in case, adjacency is up but the router doesn’t receive the network updates then these can be the following reasons: proper networks are not advertised ACL is applied on the interface auto summary command causes summarization of networks which are not needed Now, observing all these things in our configured scenario, see that: the autonomous system is same on all routers (as configured 1).the default K values are used (10100) as shown in the above figure.no authentication is applied.the interfaces are up.Also, no ACL has been applied. the autonomous system is same on all routers (as configured 1). the default K values are used (10100) as shown in the above figure. no authentication is applied. the interfaces are up. Also, no ACL has been applied. The problem occurring in this scenario is network updates are being summarized. Why? Because auto-summary has been enabled. This is the most common problem occurs during configuration of EIGRP. By default the auto-summary command is enabled in EIGRP, therefore here the routes are summarized. Therefore the situation looks like the below image: Therefore, user have to disable the auto-summary command on all routers. GfGB(config-router)#no auto-summary Similarly, on routers GfGDelhi and GfGN, no auto-summary commands will be configured. Now, user can see that all the correct routes are exchanged (not the summarized routes). anikaseth98 23603vaibhav2021 Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GSM in Wireless Communication Differences between IPv4 and IPv6 Secure Socket Layer (SSL) Wireless Application Protocol Mobile Internet Protocol (or Mobile IP) UDP Server-Client implementation in C User Datagram Protocol (UDP) Introduction of Mobile Ad hoc Network (MANET) Advanced Encryption Standard (AES) Types of area networks - LAN, MAN and WAN
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Dec, 2021" }, { "code": null, "e": 476, "s": 28, "text": "Prerequisite – EIGRP fundamentalsEnhanced Interior Gateway Routing Protocol (EIGRP) is a dynamic routing network-layer Protocol which works on protocol number 88. EIGRP supports classless routing, VLSM, route summarization, load balancing, and many other useful features. It is a Cisco proprietary protocol, so all routers in a network that is running EIGRP must be Cisco routers but now EIGRP is moving towards becoming an open standard protocol." }, { "code": null, "e": 555, "s": 476, "text": "EIGRP exchange messages for communication between the routers operating EIGRP." }, { "code": null, "e": 571, "s": 555, "text": "Configuration –" }, { "code": null, "e": 823, "s": 571, "text": "There is small topology in which there are 3 routers (on which user will configure EIGRP) namely GfGNoida, GfGDelhi, GfGBangalore. As seen, GfGBangalore router has to advertise the networks 10.10.10.0/24, 10.10.11.0/24, 172.16.10.0/30, 172.16.10.4/30." }, { "code": null, "e": 880, "s": 823, "text": "Therefore now configuring EIGRP for router GfGBangalore." }, { "code": null, "e": 1067, "s": 880, "text": "GfGB(config)#router eigrp 1\nGfGB(config-router)#network 10.10.10.0\nGfGB(config-router)#network 10.10.11.0\nGfGB(config-router)#network 172.16.10.0\nGfGB(config-router)#network 172.16.10.4 " }, { "code": null, "e": 1300, "s": 1067, "text": "Here, first created an EIGRP instance by router eigrp 1command where 1 is the autonomous system number. Now, for configuring EIGRP for GfGDelhi router, the network to be advertised are 10.10.40.0/24, 10.10.50.0/24 and 172.16.10.4/30" }, { "code": null, "e": 1464, "s": 1300, "text": "GfGDelhi(config)#router eigrp 1\nGfGDelhi(config-router)#network 172.16.10.4 \nGfGDelhi(config-router)#network 10.10.50.0\nGfGDelhi(config-router)#network 10.10.40.0 " }, { "code": null, "e": 1590, "s": 1464, "text": "Now, similarly configuring EIGRP for GfGNoida, the networks to be advertised are 10.10.20.0/24, 10.10.30.0/24, 172.16.10.0/30" }, { "code": null, "e": 1737, "s": 1590, "text": "GfGN(config)#router eigrp 1\nGfGN(config-router)#network 172.16.10.0\nGfGN(config-router)#network 10.10.20.0\nGfGN(config-router)#network 10.10.30.0 " }, { "code": null, "e": 1865, "s": 1737, "text": "This is a simple configuration in which user has to write the network I’d of the network to be advertised with network command." }, { "code": null, "e": 2037, "s": 1865, "text": "Troubleshooting –As configured EIGRP, user should see problems occurring in forming neighbourship between EIGRP operating routers. The neighbourship will not be formed if:" }, { "code": null, "e": 2076, "s": 2037, "text": "the interface is configured as passive" }, { "code": null, "e": 2103, "s": 2076, "text": "the k values doesn’t match" }, { "code": null, "e": 2145, "s": 2103, "text": "the autonomous system number is different" }, { "code": null, "e": 2183, "s": 2145, "text": "EIGRP authentication is misconfigured" }, { "code": null, "e": 2218, "s": 2183, "text": "interface between devices are down" }, { "code": null, "e": 2338, "s": 2218, "text": "If in case, adjacency is up but the router doesn’t receive the network updates then these can be the following reasons:" }, { "code": null, "e": 2373, "s": 2338, "text": "proper networks are not advertised" }, { "code": null, "e": 2405, "s": 2373, "text": "ACL is applied on the interface" }, { "code": null, "e": 2480, "s": 2405, "text": "auto summary command causes summarization of networks which are not needed" }, { "code": null, "e": 2550, "s": 2480, "text": "Now, observing all these things in our configured scenario, see that:" }, { "code": null, "e": 2762, "s": 2550, "text": "the autonomous system is same on all routers (as configured 1).the default K values are used (10100) as shown in the above figure.no authentication is applied.the interfaces are up.Also, no ACL has been applied." }, { "code": null, "e": 2826, "s": 2762, "text": "the autonomous system is same on all routers (as configured 1)." }, { "code": null, "e": 2894, "s": 2826, "text": "the default K values are used (10100) as shown in the above figure." }, { "code": null, "e": 2924, "s": 2894, "text": "no authentication is applied." }, { "code": null, "e": 2947, "s": 2924, "text": "the interfaces are up." }, { "code": null, "e": 2978, "s": 2947, "text": "Also, no ACL has been applied." }, { "code": null, "e": 3063, "s": 2978, "text": "The problem occurring in this scenario is network updates are being summarized. Why?" }, { "code": null, "e": 3323, "s": 3063, "text": "Because auto-summary has been enabled. This is the most common problem occurs during configuration of EIGRP. By default the auto-summary command is enabled in EIGRP, therefore here the routes are summarized. Therefore the situation looks like the below image:" }, { "code": null, "e": 3396, "s": 3323, "text": "Therefore, user have to disable the auto-summary command on all routers." }, { "code": null, "e": 3433, "s": 3396, "text": "GfGB(config-router)#no auto-summary " }, { "code": null, "e": 3519, "s": 3433, "text": "Similarly, on routers GfGDelhi and GfGN, no auto-summary commands will be configured." }, { "code": null, "e": 3608, "s": 3519, "text": "Now, user can see that all the correct routes are exchanged (not the summarized routes)." }, { "code": null, "e": 3620, "s": 3608, "text": "anikaseth98" }, { "code": null, "e": 3637, "s": 3620, "text": "23603vaibhav2021" }, { "code": null, "e": 3655, "s": 3637, "text": "Computer Networks" }, { "code": null, "e": 3673, "s": 3655, "text": "Computer Networks" }, { "code": null, "e": 3771, "s": 3673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3801, "s": 3771, "text": "GSM in Wireless Communication" }, { "code": null, "e": 3835, "s": 3801, "text": "Differences between IPv4 and IPv6" }, { "code": null, "e": 3861, "s": 3835, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 3891, "s": 3861, "text": "Wireless Application Protocol" }, { "code": null, "e": 3931, "s": 3891, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 3969, "s": 3931, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 3998, "s": 3969, "text": "User Datagram Protocol (UDP)" }, { "code": null, "e": 4044, "s": 3998, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 4079, "s": 4044, "text": "Advanced Encryption Standard (AES)" } ]
Python | Math operations for Data analysis
18 Aug, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.There are some important math operations that can be performed on a pandas series to simplify data analysis using Python and save a lot of time. To get the data-set used, click here. s=read_csv("stock.csv", squeeze=True) #reading csv file and making series Returns mean of all values in series. Equals to s.sum()/s.count() Returns series with frequency of each value Returns a series with information like mean, mode, etc depending on dtype of data passed Code #1: Python3 # import pandas for reading csv fileimport pandas as pd #reading csv files = pd.read_csv("stock.csv", squeeze = True) #using count functionprint(s.count()) #using sum functionprint(s.sum()) #using mean functionprint(s.mean()) #calculation averageprint(s.sum()/s.count()) #using std functionprint(s.std()) #using min functionprint(s.min()) #using max functionprint(s.max()) #using count functionprint(s.median()) #using mode functionprint(s.mode()) Output: 3012 1006942.0 334.3100929614874 334.3100929614874 173.18720477113115 49.95 782.22 283.315 0 291.21 Code #2: Python3 # import pandas for reading csv fileimport pandas as pd #reading csv files = pd.read_csv("stock.csv", squeeze = True) #using describe functionprint(s.describe()) #using count functionprint(s.idxmax()) #using idxmin functionprint(s.idxmin()) #count of elements having value 3print(s.value_counts().head(3)) Output: dtype: float64 count 3012.000000 mean 334.310093 std 173.187205 min 49.950000 25% 218.045000 50% 283.315000 75% 443.000000 max 782.220000 Name: Stock Price, dtype: float64 3011 11 291.21 5 288.47 3 194.80 3 Name: Stock Price, dtype: int64 Unexpected Outputs and Restrictions: .sum(), .mean(), .mode(), .median() and other such mathematical operations are not applicable on string or any other data type than numeric value..sum() on a string series would give an unexpected output and return a string by concatenating every string. .sum(), .mean(), .mode(), .median() and other such mathematical operations are not applicable on string or any other data type than numeric value. .sum() on a string series would give an unexpected output and return a string by concatenating every string. sagar0719kumar gulshankumarar231 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Enumerate() in Python Deque in Python Queue in Python Read a file line by line in Python Defaultdict in Python Python Dictionary Stack in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Aug, 2021" }, { "code": null, "e": 410, "s": 52, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.There are some important math operations that can be performed on a pandas series to simplify data analysis using Python and save a lot of time." }, { "code": null, "e": 449, "s": 410, "text": "To get the data-set used, click here. " }, { "code": null, "e": 523, "s": 449, "text": "s=read_csv(\"stock.csv\", squeeze=True)\n#reading csv file and making series" }, { "code": null, "e": 591, "s": 523, "text": "Returns mean of all values in series. Equals to s.sum()/s.count() " }, { "code": null, "e": 639, "s": 593, "text": "Returns series with frequency of each value " }, { "code": null, "e": 732, "s": 641, "text": "Returns a series with information like mean, mode, etc depending on dtype of data passed " }, { "code": null, "e": 744, "s": 734, "text": "Code #1: " }, { "code": null, "e": 752, "s": 744, "text": "Python3" }, { "code": "# import pandas for reading csv fileimport pandas as pd #reading csv files = pd.read_csv(\"stock.csv\", squeeze = True) #using count functionprint(s.count()) #using sum functionprint(s.sum()) #using mean functionprint(s.mean()) #calculation averageprint(s.sum()/s.count()) #using std functionprint(s.std()) #using min functionprint(s.min()) #using max functionprint(s.max()) #using count functionprint(s.median()) #using mode functionprint(s.mode())", "e": 1200, "s": 752, "text": null }, { "code": null, "e": 1210, "s": 1200, "text": "Output: " }, { "code": null, "e": 1313, "s": 1210, "text": "3012\n1006942.0\n334.3100929614874\n334.3100929614874\n173.18720477113115\n49.95\n782.22\n283.315\n0 291.21" }, { "code": null, "e": 1323, "s": 1313, "text": "Code #2: " }, { "code": null, "e": 1331, "s": 1323, "text": "Python3" }, { "code": "# import pandas for reading csv fileimport pandas as pd #reading csv files = pd.read_csv(\"stock.csv\", squeeze = True) #using describe functionprint(s.describe()) #using count functionprint(s.idxmax()) #using idxmin functionprint(s.idxmin()) #count of elements having value 3print(s.value_counts().head(3))", "e": 1637, "s": 1331, "text": null }, { "code": null, "e": 1646, "s": 1637, "text": "Output: " }, { "code": null, "e": 1940, "s": 1646, "text": "dtype: float64\ncount 3012.000000\nmean 334.310093\nstd 173.187205\nmin 49.950000\n25% 218.045000\n50% 283.315000\n75% 443.000000\nmax 782.220000\nName: Stock Price, dtype: float64\n\n3011\n11\n291.21 5\n288.47 3\n194.80 3\nName: Stock Price, dtype: int64" }, { "code": null, "e": 1977, "s": 1940, "text": "Unexpected Outputs and Restrictions:" }, { "code": null, "e": 2232, "s": 1977, "text": ".sum(), .mean(), .mode(), .median() and other such mathematical operations are not applicable on string or any other data type than numeric value..sum() on a string series would give an unexpected output and return a string by concatenating every string." }, { "code": null, "e": 2379, "s": 2232, "text": ".sum(), .mean(), .mode(), .median() and other such mathematical operations are not applicable on string or any other data type than numeric value." }, { "code": null, "e": 2488, "s": 2379, "text": ".sum() on a string series would give an unexpected output and return a string by concatenating every string." }, { "code": null, "e": 2503, "s": 2488, "text": "sagar0719kumar" }, { "code": null, "e": 2521, "s": 2503, "text": "gulshankumarar231" }, { "code": null, "e": 2536, "s": 2521, "text": "python-modules" }, { "code": null, "e": 2543, "s": 2536, "text": "Python" }, { "code": null, "e": 2641, "s": 2543, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2671, "s": 2641, "text": "Iterate over a list in Python" }, { "code": null, "e": 2716, "s": 2671, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2766, "s": 2716, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2788, "s": 2766, "text": "Enumerate() in Python" }, { "code": null, "e": 2804, "s": 2788, "text": "Deque in Python" }, { "code": null, "e": 2820, "s": 2804, "text": "Queue in Python" }, { "code": null, "e": 2855, "s": 2820, "text": "Read a file line by line in Python" }, { "code": null, "e": 2877, "s": 2855, "text": "Defaultdict in Python" }, { "code": null, "e": 2895, "s": 2877, "text": "Python Dictionary" } ]
What is the meaning of the ‘detached HEAD’ state in git?
Explanation − In git HEAD is a reference pointer and points to the current commit in the current branch. The below diagram shows that there are two commits ‘Commit#1’ and ‘Commit#2’, where ‘Commit#2’ is the latest commit. Every commit in Git will have a reference to its previous commit. Here, ‘Commit#2’ will have a reference to ‘Commit#1’. The current branch is master. The master pointer points to the latest commit i.e., ‘Commit#2’. The HEAD points to the master. In other words, the HEAD points to the last commit via the master. To check where the HEAD is pointing to, we can use the following command in Git bash $ cat .git/HEAD ref: refs/heads/master The output clearly shows that the HEAD refers to the master. In the above example, HEAD points to a branch, which in turn points to a commit. In short, the HEAD points to the commit indirectly. In such a case, the HEAD is said to be attached. When the HEAD pointer is moved from its default position, we get a warning “detached HEAD state”. This simply means that HEAD is not pointing to any branch, rather it now points to a specific commit. In other words, if the HEAD points to a specific commit, it is said to be detached. Let us understand this with an example. Execute the following command in the Git bash terminal to view the commit history − $ git log −−oneline The output given below indicates that there are 3 commits and the HEAD pointer currently points to master 089ddf4 (HEAD −>master) new line c81c9ab This is a short description 8a3d6ed first commit Now let us move the HEAD pointer from its default position and make it point to one of the commit hashes displayed in the output. Here, we will make the HEAD point to the commit hash ‘8a3d6ed’ using the git checkout command. $ git checkout 8a3d6ed The output is as shown in the following screenshot. dell@DESKTOP−N961NR5 MINGw64 /e/tut_repo (master) $ git checkout 8a3d6ed Note: switching to '8a3d6ed' . You are in 'detached HEAD' state. You can look around, make experimental changes and commit them, and you can di scard any commits you make in this state without impacting any branches by switching back to a branch. If you want to create a new branch to retain commits you create, you may do so (now or later) by using −c with the switch command. Example: git switch −c Or undo this operation with: git switch − Turn off this advice by setting config variable advice . detachedHead to fal se HEAD is now at 8a3d6ed first commit dell@DESKTop−N961NR5 MINGW64 /e/tut_repo ((8a3d6ed.. .)) The warning indicates that the HEAD is detached. This means that HEAD is now pointing to the commit ‘8a3d6ed’. Let us verify this by executing the following command − $ cat .git/HEAD The above command will return the contents of the HEAD pointer. 8a3d6ed9e95a94bc78d497fa20bc3d84a7e762fd
[ { "code": null, "e": 1722, "s": 1187, "text": "Explanation − In git HEAD is a reference pointer and points to the current commit in the current branch. The below diagram shows that there are two commits ‘Commit#1’ and ‘Commit#2’, where ‘Commit#2’ is the latest commit. Every commit in Git will have a reference to its previous commit. Here, ‘Commit#2’ will have a reference to ‘Commit#1’. The current branch is master. The master pointer points to the latest commit i.e., ‘Commit#2’. The HEAD points to the master. In other words, the HEAD points to the last commit via the master." }, { "code": null, "e": 1807, "s": 1722, "text": "To check where the HEAD is pointing to, we can use the following command in Git bash" }, { "code": null, "e": 1823, "s": 1807, "text": "$ cat .git/HEAD" }, { "code": null, "e": 1846, "s": 1823, "text": "ref: refs/heads/master" }, { "code": null, "e": 1907, "s": 1846, "text": "The output clearly shows that the HEAD refers to the master." }, { "code": null, "e": 2089, "s": 1907, "text": "In the above example, HEAD points to a branch, which in turn points to a commit. In short, the HEAD points to the commit indirectly. In such a case, the HEAD is said to be attached." }, { "code": null, "e": 2373, "s": 2089, "text": "When the HEAD pointer is moved from its default position, we get a warning “detached HEAD state”. This simply means that HEAD is not pointing to any branch, rather it now points to a specific commit. In other words, if the HEAD points to a specific commit, it is said to be detached." }, { "code": null, "e": 2497, "s": 2373, "text": "Let us understand this with an example. Execute the following command in the Git bash terminal to view the commit history −" }, { "code": null, "e": 2517, "s": 2497, "text": "$ git log −−oneline" }, { "code": null, "e": 2623, "s": 2517, "text": "The output given below indicates that there are 3 commits and the HEAD pointer currently points to master" }, { "code": null, "e": 2713, "s": 2623, "text": "089ddf4 (HEAD −>master) new line\nc81c9ab This is a short description 8a3d6ed first commit" }, { "code": null, "e": 2938, "s": 2713, "text": "Now let us move the HEAD pointer from its default position and make it point to one of the commit hashes displayed in the output. Here, we will make the HEAD point to the commit hash ‘8a3d6ed’ using the git checkout command." }, { "code": null, "e": 2961, "s": 2938, "text": "$ git checkout 8a3d6ed" }, { "code": null, "e": 3013, "s": 2961, "text": "The output is as shown in the following screenshot." }, { "code": null, "e": 3713, "s": 3013, "text": "dell@DESKTOP−N961NR5 MINGw64 /e/tut_repo (master)\n$ git checkout 8a3d6ed\nNote: switching to '8a3d6ed' .\n\nYou are in 'detached HEAD' state. You can look around, make experimental\nchanges and commit them, and you can di scard any commits you make in this\nstate without impacting any branches by switching back to a branch.\n\nIf you want to create a new branch to retain commits you create, you may\ndo so (now or later) by using −c with the switch command. Example:\n\n git switch −c\nOr undo this operation with:\n git switch −\n\nTurn off this advice by setting config variable advice . detachedHead to fal se\n\nHEAD is now at 8a3d6ed first commit\ndell@DESKTop−N961NR5 MINGW64 /e/tut_repo ((8a3d6ed.. .))" }, { "code": null, "e": 3880, "s": 3713, "text": "The warning indicates that the HEAD is detached. This means that HEAD is now pointing to the commit ‘8a3d6ed’. Let us verify this by executing the following command −" }, { "code": null, "e": 3896, "s": 3880, "text": "$ cat .git/HEAD" }, { "code": null, "e": 3960, "s": 3896, "text": "The above command will return the contents of the HEAD pointer." }, { "code": null, "e": 4001, "s": 3960, "text": "8a3d6ed9e95a94bc78d497fa20bc3d84a7e762fd" } ]
The importance of layered thinking in data engineering | by Joel Schwarzmann | Towards Data Science
Are you a data scientist or data engineer keen to build sustainable and robust data pipelines? Then this article is for you! We’ll walk through a real-world example and by the end of this article you’ll understand why you need a layered data engineering convention to avoid the mistakes we made in the past 🙈. We are QuantumBlack and we’ll talk about our open-source Python framework: Kedro. Experienced data scientists, analysts and engineers know, only too well, that not all data is designed for analytics. Often it exists ‘by accident’, a random byproduct of some other business process. When this happens, it’s common for the data quality to be poor and the infrastructure to be unreliable. Here are some examples of common situations found in the world of enterprise organisations which illustrate how one invariably ends up in this situation: The shift-manager of a production line still maintains schedules in Excel instead of using the fancy piece of enterprise software they have available because it’s a system that works, can be emailed around and migrating would interrupt business-critical timelines. The inventory system of a multinational pharmaceutical company may quite literally still be a mainframe computer from the 1980s (hey, it does the job!). It has some basic reporting and forecasting functionality, but it was purposely designed to manage stock, not for analytics. Many organisations, especially large ones, are not ‘internet natives’ and are now retroactively building machine learning into their operations. In this context, we have to take a flexible and iterative approach to building out ML use cases. One cannot expect data to be neatly structured and ready to go. For example, you see digital banks like Monzo think very carefully how they seperate PII data from analytics at source. This is something that more traditional institutions have to unpick across disparate systems when trying to do the same sort of analytics. In the real world, reverse engineering data designed for one purpose into something useful for analytics is a big part of building out ML pipelines. Acknowledging this situation and using a standardised project template is an effective mechanism for simplifying ones codebase and working mental model. One group to turn to for an opinionated set of best practices in this matter is Cookiecutter Data Science. Their mission is to facilitate correctness and reproducibility in data science and, as it happens, they also employ a layered approach to data engineering... Cookiecutter and the associated Cookiecutter Data Science project are leaders in the field with their rock-solid opinions. If you haven’t had a chance to read their methodology in detail, check them out. We’ll wait it’s fine 😀 ⏳. In summary, their thinking is underpinned by the following 6 rules: 1. Data is immutable2. Notebooks are for exploration and communication3. Analysis is a DAG4. Build from the environment up5. Keep secrets and configuration out of version control6. Be conservative in changing the default folder structure You can see from the standard Cookiecutter directory structure that a clear and concise form of data engineering convention is enforced: ...├── data│ ├── external <- Data from third party sources.│ ├── interim <- Transformed intermediate data.│ ├── processed <- The final data sets for modeling.│ └── raw <- The original, immutable data dump.│... Whilst this is a great framework to work with, as our projects grew in size and complexity we felt more nuance was needed in our approach. There was a time where every project QuantumBlack delivered looked different. People started from scratch each time, the same pitfalls were experienced independently, reproducibility was time consuming and only members of the original project team really understood each codebase. Enter Kedro, an open-source Python framework for creating reproducible, maintainable and modular data science code. If you’ve never heard of the Kedro framework before, you can learn more here. We built Kedro from scar tissue. We needed to enforce consistency and software engineering best practices across our own work. Kedro gave us the super-power to move people from project to project and it was game-changing. After working with Kedro once, you can land in another project and know how the codebase is structured, where everything is and most importantly how you can help. Kedro is a framework focused on the development and experimentation phase of ML product development. It is not centred upon executing the ‘finished article’ — that’s called ‘orchestration’ and is something we view as downstream to a deployed Kedro project. If you’re interested in how to use orchestrators, please read about our deployment guide. The Cookiecutter project’s core opinions are a huge influence on us and something we try to embody in Kedro. The initial premise for Kedro’s project structure extends the Cookiecutter directory structure. In addition, it powers the kedro new command(s) and the Kedro Starters functionality today. As mentioned earlier, we found that our development process required a slightly more nuanced set of ‘layers’: ...├── data│ ├── 01_raw <-- Raw immutable data│ ├── 02_intermediate <-- Typed data│ ├── 03_primary <-- Domain model data│ ├── 04_feature <-- Model features│ ├── 05_model_input <-- Often called 'master tables'│ ├── 06_models <-- Serialised models│ ├── 07_model_output <-- Data generated by model runs│ ├── 08_reporting <-- Ad hoc descriptive cuts... The complicated diagram below represents what this thinking looked like before Kedro came to exist. It was (and still is) a playbook for working with data before we had standardised tooling to build out our pipelines. There is a well-defined sets of rules to ensure a clear understanding of which tasks need to be performed at each layer. Today, this has been simplified and translated into Kedro’s working pattern. A table describing how these work at a high level has been included below, but we’ll also take you through an end to end example shortly. In the Kedro project template we generate a file structure that implements this convention. This is very much intended to nudge users towards this way of thinking — however, in practice we expect users to store their data in the cloud or data lake/warehouse. If you’re looking for an example, this is a good place to start! One of the other key benefits of using this approach is the ability to visualise the layers in kedro-viz, our documentation on this can be found here. shuttles: type: pandas.ExcelDataSet filepath: data/01_raw/shuttles.xlsx layer: raw The layer key can be applied to the first level of any catalog entry and reflects how the dataset will be visualised in kedro-viz. In Kedro world we call the Domain level data the primary layer... but more on that later. Let’s take the following example question and discuss the difference between source and domain data models. Which machine in a factory is going to break down next? We start with two raw data sources: Inventory - Tracks the equipment available Maintenance schedule - Which mechanics work which shifts These data sources were not designed for analytics, but a line between the two systems allows us to create a Machine shutdowns dataset relevant to the problem at hand. Whereas the two original datasets were received in whatever shape they were originally designed for, the Machine shutdowns reflects the problem being solved. With this derived dataset we can start to evaluate our hypotheses regarding what causes shutdowns. The most important difference is how we have split the ‘interim’ section into distinct subsections with clear responsibilities. For reference, here is the full Cookiecutter directory structure. In this section we will bring it all together. Let’s take our predictive maintenance example from above (in concept, the data is different) and ground it in a realistic version of a machine learning use-case. Two key points to mention before we start: 🧢 This has been written with a data engineering hat on and as such the data science workflow is somewhat simplified. The modelling approach applied is also indicative rather than a robust piece of work.🤷‍♀️ Ultimately these are all suggestions not rules — this article aims to contextualise our rationale, but ultimately you should feel free to follow this way of thinking, come up with your own layers, or completely disregard it. The data necessary to build the pipeline and overall ML use-case is currently sat across multiple systems and parts of the business which rarely speak to each other. If we could control how this data arrived it would be well documented, typed and accessible. In practice, it’s typical for things to arrive in err...how do we say this delicately... less than ideal formats 💩. ️We never mutate the data here, only work on copies In this example theraw layer is populated with data that comes from a large, distributed organisation. The following data sources are present: An Excel based maintenance log, which details when machines were serviced etc.A list of machine operators from a ERP system like SAP, describing which operators use different machine at different times.A static cut from an unknown equipment inventory SQL database that provides other metadata about the various machines in scope. The export has been provided in multiple parts. An Excel based maintenance log, which details when machines were serviced etc. A list of machine operators from a ERP system like SAP, describing which operators use different machine at different times. A static cut from an unknown equipment inventory SQL database that provides other metadata about the various machines in scope. The export has been provided in multiple parts. Now we’ve set the scene — familiarise yourself with the pipeline below before we walk through how the data flows through the layers. In practice the intermediate layer only needs to be a typed mirror of the raw layer still within the ‘source’ data model Once the intermediate layer exists, you never have to touch the raw layer and we eliminate the risks associated with mutating the original data. We permit minor transformations of the data — in this example we have combined the multi-part equipment extract into a single dataset, but have not changed the structure of the data. Cleaning column names, parsing dates and dropping completely null columns are other ‘transformations’ commonly performed at this stage. We use a modern, typed data format like Apache Parquet. If your data is already typed and structured it is okay to start at this point — but treat it as immutable. There is often a performance gain found running your pipelines from here instead of the raw layer. Typing and parsing large CSV or Excel files can be non-trivial activities in terms of computation. Profiling, EDA and any data quality assessments should be performed at this point. The primary layer contains datasets which have been structured in respect to the problem being solved. Two domain level datasets have been constructed from the intermediate layer which describe both equipment shutdowns and operator actions. Both of these primary datasets have been built in a way that each row describes an action/event at a fixed point in time allowing us to ask questions of data in an intuitive way. The concepts of migrating from the source to your domain model are critical here. This is where data is engineered into a structure fit for the analytical purpose. Additionally redundant source-level datapoints will be discarded as we flow through the layers, simplifying our working mental model. From this we have a platform which we can use to build out our feature layer. The feature layer is constructed from inputs which sit in the primary layer. It’s seen as good practice to exclusively build feature tables from the preceding primary layer (and to not jump from the intermediate one). However, as with everything in Kedro this is a suggestion, not a hard rule. In a mature situation, these will be saved in feature store which gives users a versioned and centralised location ready for low-latency serving. Feature are typically engineered at a consistent level of aggregation (often known as the ‘unit of analysis’ or table ‘grain’). In this example, one could potentially transform the data so that each row corresponds to one unique piece of equipment. Target variable(s) reside within this layer and are treated as generic features. In this example, the 3 features created represent some variables which could be predictors or signals of equipment shutdowns: a) Days between last shutdown and last maintenanceb) Maintenance hours over the last 6 monthsc) Days since last shutdown We feel the term ‘master table’ isn’t precise enough and have opted to use this nomenclature instead This is where we join all the features together to create inputs to our models In practice it’s typical to experiment with multiple models and therefore multiple ‘model input’ tables are required. The first example here is time-series based table, whereas the other table is equipment centric without a temporal element. In this example we use a simple ‘Spine’ joining table in order to to anchor each input table to the correct ‘grain’ / ‘unit of analysis’. This is where trained models are serialised with reproducibility in mind In this example, we have two models which we save as pickles for safekeeping. As with the rest of the layers, the ‘Model’ layer is conceptual box to help organise your team’s (or your own) thinking when building out pipelines. In a modern production environment it is common to see model registries used at this point of the process. The results of the various model runs live here In this example, the two distinct modeling approaches output recommendations and scored results in different formats which are consumed downstream. In this example, the feature engineering work performed has also made it possible to provide the business with a descriptive helicopter view of the maintenance activities not previously accessible. Extra credit —In this example we used an advanced modular pipeline pattern in order to to re-use the same Data Science pipeline across both models (hence the mirrored structure). By doing this we can re-use the same code by simply overriding the relevant inputs and outputs for each pipeline — see Kedro the code here. The real world is one where data often hasn’t been designed with analytics in mind. It helps to have a framework for getting your data into a format suitable for analytics and, it just so happens, we’ve developed one which helps us make sense of the complexity and avoid common mistakes. This article gives an idea of how we developed our thinking and provides a worked example of how Kedro’s data convention is set out. What do you, the readers, use to guide your data engineering? Let us know in the comments! 📦 GitHub💬 Discord🐍 PyPi🤓 Read The Docs Are you a software engineer, product manager, data scientist or designer? Are you looking to work as part of a multidisciplinary team on innovative products and technologies? Then check out our QuantumBlack Labs page for more information.
[ { "code": null, "e": 563, "s": 171, "text": "Are you a data scientist or data engineer keen to build sustainable and robust data pipelines? Then this article is for you! We’ll walk through a real-world example and by the end of this article you’ll understand why you need a layered data engineering convention to avoid the mistakes we made in the past 🙈. We are QuantumBlack and we’ll talk about our open-source Python framework: Kedro." }, { "code": null, "e": 763, "s": 563, "text": "Experienced data scientists, analysts and engineers know, only too well, that not all data is designed for analytics. Often it exists ‘by accident’, a random byproduct of some other business process." }, { "code": null, "e": 867, "s": 763, "text": "When this happens, it’s common for the data quality to be poor and the infrastructure to be unreliable." }, { "code": null, "e": 1021, "s": 867, "text": "Here are some examples of common situations found in the world of enterprise organisations which illustrate how one invariably ends up in this situation:" }, { "code": null, "e": 1286, "s": 1021, "text": "The shift-manager of a production line still maintains schedules in Excel instead of using the fancy piece of enterprise software they have available because it’s a system that works, can be emailed around and migrating would interrupt business-critical timelines." }, { "code": null, "e": 1564, "s": 1286, "text": "The inventory system of a multinational pharmaceutical company may quite literally still be a mainframe computer from the 1980s (hey, it does the job!). It has some basic reporting and forecasting functionality, but it was purposely designed to manage stock, not for analytics." }, { "code": null, "e": 1806, "s": 1564, "text": "Many organisations, especially large ones, are not ‘internet natives’ and are now retroactively building machine learning into their operations. In this context, we have to take a flexible and iterative approach to building out ML use cases." }, { "code": null, "e": 2129, "s": 1806, "text": "One cannot expect data to be neatly structured and ready to go. For example, you see digital banks like Monzo think very carefully how they seperate PII data from analytics at source. This is something that more traditional institutions have to unpick across disparate systems when trying to do the same sort of analytics." }, { "code": null, "e": 2278, "s": 2129, "text": "In the real world, reverse engineering data designed for one purpose into something useful for analytics is a big part of building out ML pipelines." }, { "code": null, "e": 2431, "s": 2278, "text": "Acknowledging this situation and using a standardised project template is an effective mechanism for simplifying ones codebase and working mental model." }, { "code": null, "e": 2696, "s": 2431, "text": "One group to turn to for an opinionated set of best practices in this matter is Cookiecutter Data Science. Their mission is to facilitate correctness and reproducibility in data science and, as it happens, they also employ a layered approach to data engineering..." }, { "code": null, "e": 2926, "s": 2696, "text": "Cookiecutter and the associated Cookiecutter Data Science project are leaders in the field with their rock-solid opinions. If you haven’t had a chance to read their methodology in detail, check them out. We’ll wait it’s fine 😀 ⏳." }, { "code": null, "e": 2994, "s": 2926, "text": "In summary, their thinking is underpinned by the following 6 rules:" }, { "code": null, "e": 3232, "s": 2994, "text": "1. Data is immutable2. Notebooks are for exploration and communication3. Analysis is a DAG4. Build from the environment up5. Keep secrets and configuration out of version control6. Be conservative in changing the default folder structure" }, { "code": null, "e": 3369, "s": 3232, "text": "You can see from the standard Cookiecutter directory structure that a clear and concise form of data engineering convention is enforced:" }, { "code": null, "e": 3616, "s": 3369, "text": "...├── data│ ├── external <- Data from third party sources.│ ├── interim <- Transformed intermediate data.│ ├── processed <- The final data sets for modeling.│ └── raw <- The original, immutable data dump.│..." }, { "code": null, "e": 3755, "s": 3616, "text": "Whilst this is a great framework to work with, as our projects grew in size and complexity we felt more nuance was needed in our approach." }, { "code": null, "e": 4036, "s": 3755, "text": "There was a time where every project QuantumBlack delivered looked different. People started from scratch each time, the same pitfalls were experienced independently, reproducibility was time consuming and only members of the original project team really understood each codebase." }, { "code": null, "e": 4230, "s": 4036, "text": "Enter Kedro, an open-source Python framework for creating reproducible, maintainable and modular data science code. If you’ve never heard of the Kedro framework before, you can learn more here." }, { "code": null, "e": 4263, "s": 4230, "text": "We built Kedro from scar tissue." }, { "code": null, "e": 4452, "s": 4263, "text": "We needed to enforce consistency and software engineering best practices across our own work. Kedro gave us the super-power to move people from project to project and it was game-changing." }, { "code": null, "e": 4615, "s": 4452, "text": "After working with Kedro once, you can land in another project and know how the codebase is structured, where everything is and most importantly how you can help." }, { "code": null, "e": 4962, "s": 4615, "text": "Kedro is a framework focused on the development and experimentation phase of ML product development. It is not centred upon executing the ‘finished article’ — that’s called ‘orchestration’ and is something we view as downstream to a deployed Kedro project. If you’re interested in how to use orchestrators, please read about our deployment guide." }, { "code": null, "e": 5259, "s": 4962, "text": "The Cookiecutter project’s core opinions are a huge influence on us and something we try to embody in Kedro. The initial premise for Kedro’s project structure extends the Cookiecutter directory structure. In addition, it powers the kedro new command(s) and the Kedro Starters functionality today." }, { "code": null, "e": 5369, "s": 5259, "text": "As mentioned earlier, we found that our development process required a slightly more nuanced set of ‘layers’:" }, { "code": null, "e": 5779, "s": 5369, "text": "...├── data│ ├── 01_raw <-- Raw immutable data│ ├── 02_intermediate <-- Typed data│ ├── 03_primary <-- Domain model data│ ├── 04_feature <-- Model features│ ├── 05_model_input <-- Often called 'master tables'│ ├── 06_models <-- Serialised models│ ├── 07_model_output <-- Data generated by model runs│ ├── 08_reporting <-- Ad hoc descriptive cuts..." }, { "code": null, "e": 5997, "s": 5779, "text": "The complicated diagram below represents what this thinking looked like before Kedro came to exist. It was (and still is) a playbook for working with data before we had standardised tooling to build out our pipelines." }, { "code": null, "e": 6118, "s": 5997, "text": "There is a well-defined sets of rules to ensure a clear understanding of which tasks need to be performed at each layer." }, { "code": null, "e": 6333, "s": 6118, "text": "Today, this has been simplified and translated into Kedro’s working pattern. A table describing how these work at a high level has been included below, but we’ll also take you through an end to end example shortly." }, { "code": null, "e": 6657, "s": 6333, "text": "In the Kedro project template we generate a file structure that implements this convention. This is very much intended to nudge users towards this way of thinking — however, in practice we expect users to store their data in the cloud or data lake/warehouse. If you’re looking for an example, this is a good place to start!" }, { "code": null, "e": 6808, "s": 6657, "text": "One of the other key benefits of using this approach is the ability to visualise the layers in kedro-viz, our documentation on this can be found here." }, { "code": null, "e": 6894, "s": 6808, "text": "shuttles: type: pandas.ExcelDataSet filepath: data/01_raw/shuttles.xlsx layer: raw" }, { "code": null, "e": 7025, "s": 6894, "text": "The layer key can be applied to the first level of any catalog entry and reflects how the dataset will be visualised in kedro-viz." }, { "code": null, "e": 7115, "s": 7025, "text": "In Kedro world we call the Domain level data the primary layer... but more on that later." }, { "code": null, "e": 7223, "s": 7115, "text": "Let’s take the following example question and discuss the difference between source and domain data models." }, { "code": null, "e": 7279, "s": 7223, "text": "Which machine in a factory is going to break down next?" }, { "code": null, "e": 7315, "s": 7279, "text": "We start with two raw data sources:" }, { "code": null, "e": 7358, "s": 7315, "text": "Inventory - Tracks the equipment available" }, { "code": null, "e": 7415, "s": 7358, "text": "Maintenance schedule - Which mechanics work which shifts" }, { "code": null, "e": 7583, "s": 7415, "text": "These data sources were not designed for analytics, but a line between the two systems allows us to create a Machine shutdowns dataset relevant to the problem at hand." }, { "code": null, "e": 7840, "s": 7583, "text": "Whereas the two original datasets were received in whatever shape they were originally designed for, the Machine shutdowns reflects the problem being solved. With this derived dataset we can start to evaluate our hypotheses regarding what causes shutdowns." }, { "code": null, "e": 8034, "s": 7840, "text": "The most important difference is how we have split the ‘interim’ section into distinct subsections with clear responsibilities. For reference, here is the full Cookiecutter directory structure." }, { "code": null, "e": 8243, "s": 8034, "text": "In this section we will bring it all together. Let’s take our predictive maintenance example from above (in concept, the data is different) and ground it in a realistic version of a machine learning use-case." }, { "code": null, "e": 8286, "s": 8243, "text": "Two key points to mention before we start:" }, { "code": null, "e": 8718, "s": 8286, "text": "🧢 This has been written with a data engineering hat on and as such the data science workflow is somewhat simplified. The modelling approach applied is also indicative rather than a robust piece of work.🤷‍♀️ Ultimately these are all suggestions not rules — this article aims to contextualise our rationale, but ultimately you should feel free to follow this way of thinking, come up with your own layers, or completely disregard it." }, { "code": null, "e": 8884, "s": 8718, "text": "The data necessary to build the pipeline and overall ML use-case is currently sat across multiple systems and parts of the business which rarely speak to each other." }, { "code": null, "e": 9093, "s": 8884, "text": "If we could control how this data arrived it would be well documented, typed and accessible. In practice, it’s typical for things to arrive in err...how do we say this delicately... less than ideal formats 💩." }, { "code": null, "e": 9145, "s": 9093, "text": "️We never mutate the data here, only work on copies" }, { "code": null, "e": 9288, "s": 9145, "text": "In this example theraw layer is populated with data that comes from a large, distributed organisation. The following data sources are present:" }, { "code": null, "e": 9666, "s": 9288, "text": "An Excel based maintenance log, which details when machines were serviced etc.A list of machine operators from a ERP system like SAP, describing which operators use different machine at different times.A static cut from an unknown equipment inventory SQL database that provides other metadata about the various machines in scope. The export has been provided in multiple parts." }, { "code": null, "e": 9745, "s": 9666, "text": "An Excel based maintenance log, which details when machines were serviced etc." }, { "code": null, "e": 9870, "s": 9745, "text": "A list of machine operators from a ERP system like SAP, describing which operators use different machine at different times." }, { "code": null, "e": 10046, "s": 9870, "text": "A static cut from an unknown equipment inventory SQL database that provides other metadata about the various machines in scope. The export has been provided in multiple parts." }, { "code": null, "e": 10179, "s": 10046, "text": "Now we’ve set the scene — familiarise yourself with the pipeline below before we walk through how the data flows through the layers." }, { "code": null, "e": 10300, "s": 10179, "text": "In practice the intermediate layer only needs to be a typed mirror of the raw layer still within the ‘source’ data model" }, { "code": null, "e": 10445, "s": 10300, "text": "Once the intermediate layer exists, you never have to touch the raw layer and we eliminate the risks associated with mutating the original data." }, { "code": null, "e": 10628, "s": 10445, "text": "We permit minor transformations of the data — in this example we have combined the multi-part equipment extract into a single dataset, but have not changed the structure of the data." }, { "code": null, "e": 10764, "s": 10628, "text": "Cleaning column names, parsing dates and dropping completely null columns are other ‘transformations’ commonly performed at this stage." }, { "code": null, "e": 10820, "s": 10764, "text": "We use a modern, typed data format like Apache Parquet." }, { "code": null, "e": 10928, "s": 10820, "text": "If your data is already typed and structured it is okay to start at this point — but treat it as immutable." }, { "code": null, "e": 11126, "s": 10928, "text": "There is often a performance gain found running your pipelines from here instead of the raw layer. Typing and parsing large CSV or Excel files can be non-trivial activities in terms of computation." }, { "code": null, "e": 11209, "s": 11126, "text": "Profiling, EDA and any data quality assessments should be performed at this point." }, { "code": null, "e": 11312, "s": 11209, "text": "The primary layer contains datasets which have been structured in respect to the problem being solved." }, { "code": null, "e": 11450, "s": 11312, "text": "Two domain level datasets have been constructed from the intermediate layer which describe both equipment shutdowns and operator actions." }, { "code": null, "e": 11629, "s": 11450, "text": "Both of these primary datasets have been built in a way that each row describes an action/event at a fixed point in time allowing us to ask questions of data in an intuitive way." }, { "code": null, "e": 11793, "s": 11629, "text": "The concepts of migrating from the source to your domain model are critical here. This is where data is engineered into a structure fit for the analytical purpose." }, { "code": null, "e": 11927, "s": 11793, "text": "Additionally redundant source-level datapoints will be discarded as we flow through the layers, simplifying our working mental model." }, { "code": null, "e": 12005, "s": 11927, "text": "From this we have a platform which we can use to build out our feature layer." }, { "code": null, "e": 12082, "s": 12005, "text": "The feature layer is constructed from inputs which sit in the primary layer." }, { "code": null, "e": 12299, "s": 12082, "text": "It’s seen as good practice to exclusively build feature tables from the preceding primary layer (and to not jump from the intermediate one). However, as with everything in Kedro this is a suggestion, not a hard rule." }, { "code": null, "e": 12445, "s": 12299, "text": "In a mature situation, these will be saved in feature store which gives users a versioned and centralised location ready for low-latency serving." }, { "code": null, "e": 12694, "s": 12445, "text": "Feature are typically engineered at a consistent level of aggregation (often known as the ‘unit of analysis’ or table ‘grain’). In this example, one could potentially transform the data so that each row corresponds to one unique piece of equipment." }, { "code": null, "e": 12775, "s": 12694, "text": "Target variable(s) reside within this layer and are treated as generic features." }, { "code": null, "e": 12901, "s": 12775, "text": "In this example, the 3 features created represent some variables which could be predictors or signals of equipment shutdowns:" }, { "code": null, "e": 13022, "s": 12901, "text": "a) Days between last shutdown and last maintenanceb) Maintenance hours over the last 6 monthsc) Days since last shutdown" }, { "code": null, "e": 13123, "s": 13022, "text": "We feel the term ‘master table’ isn’t precise enough and have opted to use this nomenclature instead" }, { "code": null, "e": 13202, "s": 13123, "text": "This is where we join all the features together to create inputs to our models" }, { "code": null, "e": 13320, "s": 13202, "text": "In practice it’s typical to experiment with multiple models and therefore multiple ‘model input’ tables are required." }, { "code": null, "e": 13444, "s": 13320, "text": "The first example here is time-series based table, whereas the other table is equipment centric without a temporal element." }, { "code": null, "e": 13582, "s": 13444, "text": "In this example we use a simple ‘Spine’ joining table in order to to anchor each input table to the correct ‘grain’ / ‘unit of analysis’." }, { "code": null, "e": 13655, "s": 13582, "text": "This is where trained models are serialised with reproducibility in mind" }, { "code": null, "e": 13733, "s": 13655, "text": "In this example, we have two models which we save as pickles for safekeeping." }, { "code": null, "e": 13882, "s": 13733, "text": "As with the rest of the layers, the ‘Model’ layer is conceptual box to help organise your team’s (or your own) thinking when building out pipelines." }, { "code": null, "e": 13989, "s": 13882, "text": "In a modern production environment it is common to see model registries used at this point of the process." }, { "code": null, "e": 14037, "s": 13989, "text": "The results of the various model runs live here" }, { "code": null, "e": 14185, "s": 14037, "text": "In this example, the two distinct modeling approaches output recommendations and scored results in different formats which are consumed downstream." }, { "code": null, "e": 14383, "s": 14185, "text": "In this example, the feature engineering work performed has also made it possible to provide the business with a descriptive helicopter view of the maintenance activities not previously accessible." }, { "code": null, "e": 14702, "s": 14383, "text": "Extra credit —In this example we used an advanced modular pipeline pattern in order to to re-use the same Data Science pipeline across both models (hence the mirrored structure). By doing this we can re-use the same code by simply overriding the relevant inputs and outputs for each pipeline — see Kedro the code here." }, { "code": null, "e": 14990, "s": 14702, "text": "The real world is one where data often hasn’t been designed with analytics in mind. It helps to have a framework for getting your data into a format suitable for analytics and, it just so happens, we’ve developed one which helps us make sense of the complexity and avoid common mistakes." }, { "code": null, "e": 15123, "s": 14990, "text": "This article gives an idea of how we developed our thinking and provides a worked example of how Kedro’s data convention is set out." }, { "code": null, "e": 15214, "s": 15123, "text": "What do you, the readers, use to guide your data engineering? Let us know in the comments!" }, { "code": null, "e": 15253, "s": 15214, "text": "📦 GitHub💬 Discord🐍 PyPi🤓 Read The Docs" } ]
Generate Random Variable Using Inverse Transform Method in Python | by Raden Aurelius Andhika Viadinugroho | Towards Data Science
Motivation In simulation theory, generating random variables become one of the most important “building block”, where these random variables are mostly generated from Uniform distributed random variable. One of the methods that can be used to generate the random variables is the Inverse Transform method. In this article, I will show you how to generate random variables (both discrete and continuous case) using the Inverse Transform method in Python. The Concept Given random variable U where U is uniformly distributed in (0,1). Suppose that we want to generate random variable X where the Cumulative Distribution Function (CDF) is The idea of the inverse transform method is to generate a random number from any probability distribution by using its inverse CDF as follows. For discrete random variables, the steps are slightly different. Suppose that we want to generate the value of a discrete random variable X that has a Probability Mass Function (PMF) To generate the value of X, generate a random variable U where U is uniformly distributed in (0,1) and set From the steps above, we can create the inverse transform method’s algorithm as follows. Implementation : Continuous r.v. case First, we implement this method for generating continuous random variables. Suppose that we want to simulate a random variable X that follows the exponential distribution with mean λ (i.e. X~EXP(λ)). We know that the Probability Distribution Function (PDF) of the exponential distribution is with the CDF as follows. Then, we can write the inverse CDF as follows. In Python, we can simply implement it by writing these lines of code as follows. ### Generate exponential distributed random variables given the mean ### and number of random variablesdef exponential_inverse_trans(n=1,mean=1): U=uniform.rvs(size=n) X=-mean*np.log(1-U) actual=expon.rvs(size=n,scale=mean) plt.figure(figsize=(12,9)) plt.hist(X, bins=50, alpha=0.5, label="Generated r.v.") plt.hist(actual, bins=50, alpha=0.5, label="Actual r.v.") plt.title("Generated vs Actual %i Exponential Random Variables" %n) plt.legend() plt.show() return X We can try the code above by running some examples below. Note that the result might be different since we want to generate random variables. cont_example1=exponential_inverse_trans(n=100,mean=4)cont_example2=exponential_inverse_trans(n=500,mean=4)cont_example3=exponential_inverse_trans(n=1000,mean=4) Looks interesting. We can see that the generated random variable having a pretty similar result if we compare it with the actual one. You can adjust the mean (Please note that the mean that I define for expon.rvs() function is a scale parameter in exponential distribution) and/or the number of generated random variables to see different results. Implementation : Discrete r.v. case For discrete random variable case, suppose that we want to simulate a discrete random variable case X that follows the following distribution First, we write the function to generate the discrete random variable for one sample with these lines of code. ### Generate arbitary discrete distributed random variables given ### the probability vectordef discrete_inverse_trans(prob_vec): U=uniform.rvs(size=1) if U<=prob_vec[0]: return 1 else: for i in range(1,len(prob_vec)+1): if sum(prob_vec[0:i])<U and sum(prob_vec[0:i+1])>U: return i+1 Then, we create a function to generate many random variable samples with these lines of code. def discrete_samples(prob_vec,n=1): sample=[] for i in range(0,n): sample.append(discrete_inverse_trans(prob_vec)) return np.array(sample) Finally, we create a function to simulate the result and compare it with the actual one by these lines of code. def discrete_simulate(prob_vec,numbers,n=1): sample_disc=discrete_samples(prob_vec,n) unique, counts=np.unique(sample_disc,return_counts=True) fig=plt.figure() ax=fig.add_axes([0,0,1,1]) prob=counts/n ax.bar(numbers,prob) ax.set_title("Simulation of Generating %i Discrete Random Variables" %n) plt.show() data={'X':unique,'Number of samples':counts,'Empirical Probability':prob,'Actual Probability':prob_vec} df=pd.DataFrame(data=data) return df We can run some examples below to see the results. Again, note that the result might be different since we want to generate random variables. prob_vec=np.array([0.1,0.3,0.5,0.05,0.05])numbers=np.array([1,2,3,4,5])dis_example1=discrete_simulate(prob_vec, numbers, n=100)dis_example2=discrete_simulate(prob_vec, numbers, n=500)dis_example3=discrete_simulate(prob_vec, numbers, n=1000) In[11]: dis_example1Out[11]: X Number of samples Empirical Probability Actual Probability0 1 8 0.08 0.101 2 35 0.35 0.302 3 50 0.50 0.503 4 5 0.05 0.054 5 2 0.02 0.05In[12]: dis_example2Out[12]: X Number of samples Empirical Probability Actual Probability0 1 53 0.106 0.101 2 159 0.318 0.302 3 234 0.468 0.503 4 30 0.060 0.054 5 24 0.048 0.05In[13]: dis_example3Out[13]: X Number of samples Empirical Probability Actual Probability0 1 108 0.108 0.101 2 290 0.290 0.302 3 491 0.491 0.503 4 51 0.051 0.054 5 60 0.060 0.05 The result is interesting! We can see that the empirical probability is getting closer to the actual probability as we increase the number of random variable samples. Try to experiment with a different number of samples and/or different distribution to see different results. Conclusion And that’s it! This inverse transform method is a very important tool in statistics, especially in simulation theory where we want to generate random variables given random variables that are uniformly distributed in (0,1). The study case itself is pretty wide, you can use this method from generating Empirical CDF to predictive analytics. See you in the next post! Author Contact LinkedIn : Raden Aurelius Andhika Viadinugroho References [1] Sheldon M. Ross, Simulation, 5th ed (2013), Elsevier [2] Sheldon M. Ross, Introduction to Probability and Statistics for Engineers and Scientists, 5th ed (2014), Elsevier
[ { "code": null, "e": 183, "s": 172, "text": "Motivation" }, { "code": null, "e": 626, "s": 183, "text": "In simulation theory, generating random variables become one of the most important “building block”, where these random variables are mostly generated from Uniform distributed random variable. One of the methods that can be used to generate the random variables is the Inverse Transform method. In this article, I will show you how to generate random variables (both discrete and continuous case) using the Inverse Transform method in Python." }, { "code": null, "e": 638, "s": 626, "text": "The Concept" }, { "code": null, "e": 808, "s": 638, "text": "Given random variable U where U is uniformly distributed in (0,1). Suppose that we want to generate random variable X where the Cumulative Distribution Function (CDF) is" }, { "code": null, "e": 951, "s": 808, "text": "The idea of the inverse transform method is to generate a random number from any probability distribution by using its inverse CDF as follows." }, { "code": null, "e": 1134, "s": 951, "text": "For discrete random variables, the steps are slightly different. Suppose that we want to generate the value of a discrete random variable X that has a Probability Mass Function (PMF)" }, { "code": null, "e": 1241, "s": 1134, "text": "To generate the value of X, generate a random variable U where U is uniformly distributed in (0,1) and set" }, { "code": null, "e": 1330, "s": 1241, "text": "From the steps above, we can create the inverse transform method’s algorithm as follows." }, { "code": null, "e": 1368, "s": 1330, "text": "Implementation : Continuous r.v. case" }, { "code": null, "e": 1660, "s": 1368, "text": "First, we implement this method for generating continuous random variables. Suppose that we want to simulate a random variable X that follows the exponential distribution with mean λ (i.e. X~EXP(λ)). We know that the Probability Distribution Function (PDF) of the exponential distribution is" }, { "code": null, "e": 1685, "s": 1660, "text": "with the CDF as follows." }, { "code": null, "e": 1732, "s": 1685, "text": "Then, we can write the inverse CDF as follows." }, { "code": null, "e": 1813, "s": 1732, "text": "In Python, we can simply implement it by writing these lines of code as follows." }, { "code": null, "e": 2313, "s": 1813, "text": "### Generate exponential distributed random variables given the mean ### and number of random variablesdef exponential_inverse_trans(n=1,mean=1): U=uniform.rvs(size=n) X=-mean*np.log(1-U) actual=expon.rvs(size=n,scale=mean) plt.figure(figsize=(12,9)) plt.hist(X, bins=50, alpha=0.5, label=\"Generated r.v.\") plt.hist(actual, bins=50, alpha=0.5, label=\"Actual r.v.\") plt.title(\"Generated vs Actual %i Exponential Random Variables\" %n) plt.legend() plt.show() return X" }, { "code": null, "e": 2455, "s": 2313, "text": "We can try the code above by running some examples below. Note that the result might be different since we want to generate random variables." }, { "code": null, "e": 2616, "s": 2455, "text": "cont_example1=exponential_inverse_trans(n=100,mean=4)cont_example2=exponential_inverse_trans(n=500,mean=4)cont_example3=exponential_inverse_trans(n=1000,mean=4)" }, { "code": null, "e": 2964, "s": 2616, "text": "Looks interesting. We can see that the generated random variable having a pretty similar result if we compare it with the actual one. You can adjust the mean (Please note that the mean that I define for expon.rvs() function is a scale parameter in exponential distribution) and/or the number of generated random variables to see different results." }, { "code": null, "e": 3000, "s": 2964, "text": "Implementation : Discrete r.v. case" }, { "code": null, "e": 3142, "s": 3000, "text": "For discrete random variable case, suppose that we want to simulate a discrete random variable case X that follows the following distribution" }, { "code": null, "e": 3253, "s": 3142, "text": "First, we write the function to generate the discrete random variable for one sample with these lines of code." }, { "code": null, "e": 3586, "s": 3253, "text": "### Generate arbitary discrete distributed random variables given ### the probability vectordef discrete_inverse_trans(prob_vec): U=uniform.rvs(size=1) if U<=prob_vec[0]: return 1 else: for i in range(1,len(prob_vec)+1): if sum(prob_vec[0:i])<U and sum(prob_vec[0:i+1])>U: return i+1" }, { "code": null, "e": 3680, "s": 3586, "text": "Then, we create a function to generate many random variable samples with these lines of code." }, { "code": null, "e": 3835, "s": 3680, "text": "def discrete_samples(prob_vec,n=1): sample=[] for i in range(0,n): sample.append(discrete_inverse_trans(prob_vec)) return np.array(sample)" }, { "code": null, "e": 3947, "s": 3835, "text": "Finally, we create a function to simulate the result and compare it with the actual one by these lines of code." }, { "code": null, "e": 4435, "s": 3947, "text": "def discrete_simulate(prob_vec,numbers,n=1): sample_disc=discrete_samples(prob_vec,n) unique, counts=np.unique(sample_disc,return_counts=True) fig=plt.figure() ax=fig.add_axes([0,0,1,1]) prob=counts/n ax.bar(numbers,prob) ax.set_title(\"Simulation of Generating %i Discrete Random Variables\" %n) plt.show() data={'X':unique,'Number of samples':counts,'Empirical Probability':prob,'Actual Probability':prob_vec} df=pd.DataFrame(data=data) return df" }, { "code": null, "e": 4577, "s": 4435, "text": "We can run some examples below to see the results. Again, note that the result might be different since we want to generate random variables." }, { "code": null, "e": 4818, "s": 4577, "text": "prob_vec=np.array([0.1,0.3,0.5,0.05,0.05])numbers=np.array([1,2,3,4,5])dis_example1=discrete_simulate(prob_vec, numbers, n=100)dis_example2=discrete_simulate(prob_vec, numbers, n=500)dis_example3=discrete_simulate(prob_vec, numbers, n=1000)" }, { "code": null, "e": 6094, "s": 4818, "text": "In[11]: dis_example1Out[11]: X Number of samples Empirical Probability Actual Probability0 1 8 0.08 0.101 2 35 0.35 0.302 3 50 0.50 0.503 4 5 0.05 0.054 5 2 0.02 0.05In[12]: dis_example2Out[12]: X Number of samples Empirical Probability Actual Probability0 1 53 0.106 0.101 2 159 0.318 0.302 3 234 0.468 0.503 4 30 0.060 0.054 5 24 0.048 0.05In[13]: dis_example3Out[13]: X Number of samples Empirical Probability Actual Probability0 1 108 0.108 0.101 2 290 0.290 0.302 3 491 0.491 0.503 4 51 0.051 0.054 5 60 0.060 0.05" }, { "code": null, "e": 6370, "s": 6094, "text": "The result is interesting! We can see that the empirical probability is getting closer to the actual probability as we increase the number of random variable samples. Try to experiment with a different number of samples and/or different distribution to see different results." }, { "code": null, "e": 6381, "s": 6370, "text": "Conclusion" }, { "code": null, "e": 6722, "s": 6381, "text": "And that’s it! This inverse transform method is a very important tool in statistics, especially in simulation theory where we want to generate random variables given random variables that are uniformly distributed in (0,1). The study case itself is pretty wide, you can use this method from generating Empirical CDF to predictive analytics." }, { "code": null, "e": 6748, "s": 6722, "text": "See you in the next post!" }, { "code": null, "e": 6763, "s": 6748, "text": "Author Contact" }, { "code": null, "e": 6810, "s": 6763, "text": "LinkedIn : Raden Aurelius Andhika Viadinugroho" }, { "code": null, "e": 6821, "s": 6810, "text": "References" }, { "code": null, "e": 6878, "s": 6821, "text": "[1] Sheldon M. Ross, Simulation, 5th ed (2013), Elsevier" } ]
7 Best UI Graphics Tools For Python Developers With Starter Codes | by Bharath K | Towards Data Science
Python is such a versatile language that it can accomplish most tasks that different programming languages are meant to achieve. Although Python is used more frequently for applications and projects related to artificial intelligence, data science, data visualizations, data analytics, and other similar operations, we are by no means limited to these boundaries. You can perform web development, build games, construct numerous GUI tools, and so much more as a developer with Python. The Graphics User Interface (GUI) built with Python are extremely useful for a variety of projects. You can use these technologies to make your projects unique, aesthetically pleasing, visually appealing, highly interactive environment, and provide users with other similar wonderful features. You can even use these tools for developing artificial intelligence projects with machine learning or deep learning models to make them stand out from other such project ideas. In this article, we will objectively look at some of the best GUI tools that are available to the developers with the help of Python coding. We will explore seven such libraries that give users the best aim of implementing their desired GUI applications. To follow along with this article and implement all your codes accordingly, I would suggest the viewers pick the editor of their favorite choice and get their hands dirty with some code. I am personally using Visual Studio Code for my programming, but you can feel free to use your preferred choices. However, if you are having a tough time choosing the best option for you, the following link on the list of over ten awesome Python editors with pros and cons will help you decide the best-suited editor for your coding. towardsdatascience.com The Tkinter package that is available in Python is one of the best tools for most graphics-related applications. It is available for both Windows and Linux platforms with a simple pip installation. The Tkinter library allows the users to develop high-quality graphic interfaces with the help of the numerous options it contains. Tkinter has various options for providing a valuable structure to your desired application with the help of frames, buttons, and check buttons for creating interactive selections, displaying information with labels, draw data and statistical information with Canvas, and so much more. The starter code The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information. from tkinter import *master = Tk()Label(master, text='Enter Your Name').grid(row=0)Label(master, text='Enter Your Email').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop() In the following code block shown above, we are creating a simple program with which we are creating two simple grid boxes that will register the name and email of a particular individual. Feel free to explore the library further and construct more complex projects. The Qt is a set of cross-platform C++ libraries that implement high-level APIs for accessing many aspects of modern desktop and mobile systems. The Qt platform offers developers a wide variety of unique solutions to develop numerous applications and solve a humungous array of complex tasks. With a simple pip install command, you can start with the following GUI application. The development of GUI applications with the help of Python and the PyQt5 library is rather simple and can be completed with a few lines of code. Below is a code block demonstration of how we can generate interactive GUI interfaces with this package. import sysfrom PyQt5.QtCore import *from PyQt5.QtGui import *from PyQt5.QtWidgets import *def window(): app = QApplication(sys.argv) w = QWidget() b = QLabel(w) b.setText("Welcome!") w.setGeometry(100,100,200,50) b.move(50,20) w.setWindowTitle("PyQt5") w.show() sys.exit(app.exec_())if __name__ == '__main__': window() The following code block will display a graphical user interface with a Welcome command. Further advanced widgets and elements can be added to make the code more appealing. The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information. Unlike the two previously discussed GUI tools, Pygame is slightly different in comparison. With Pygame, you can construct and build Python games from scratch. While their performance and graphics might not be the best in comparison to some other programming languages like C# and some elite game designing software’s it is still a great way for most beginners to get started due to the ease of coding procedures. One of the main advantages of working with Pygame, apart from building games, is the GUI capabilities that it has. It allows the developers to create a GUI interface with which numerous actions can be controlled. There are a lot of options available in Pygame to develop entities (like widgets or icons) in the user interface and control some desirable actions. Below is some starter code to get more experience with this module for developing more projects from scratch. #imports the pygame library moduleimport pygame# initilize the pygame modulepygame.init()# Setting your screen size with a tuple of the screen width and screen heightdisplay_screen = pygame.display.set_mode((800,600))# Setting a random caption title for your pygame graphical window.pygame.display.set_caption("pygame test")# Update your screen when requiredpygame.display.update()# quit the pygame initialization and modulepygame.quit()# End the programquit() In the above coding section, we have discussed some starter code for creating a graphical window of a particular size with Pygame. There are tons more applications and games that you can build with the help of this Python library. To understand five reasons why every developer should invest their time developing a game with Python and AI, check out one of my previous articles on five reasons why you should do so. towardsdatascience.com Open-CV is one of the best libraries for computer vision tasks and image processing. This library offers fantastic utility for performing a wide array of tasks. With the help of Open-CV, it is also possible to construct GUI applications as well with a customizable interface. While the options that are available for Open for GUI are not as vast as the other options, there is a vast amount of technical stuff you can build. Save the above image in your desktop (or download it from the mentioned link) as Lena, and ensure that is in a .png format. Below is the starter code for some of the actions that you can perform with the Open-CV library. # Importing the opencv moduleimport cv2# Read The Imageimage = cv2.imread("lena.png")# Frame Title with the image to be displayedcv2.imshow("Picture", image) cv2.waitKey(0)# Convert the color image to grayscale imagegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Display Grayscale imagecv2.imshow("Gray Picture", gray)cv2.waitKey(0) The above starter code explores the basic implementation of some of the functionalities of the Open-CV library. If you are interested to dwell further into exploring more about this particular library and understand more about computer vision, check out one of my previous articles that covers the complete beginner’s guide on getting started with Open-CV from the following link provided below. towardsdatascience.com Another fantastic open-source package that allows users to create some high-quality graphical user interfaces is Kivy. It can be installed with the pip installation for Python. It offers developers one of the best business-friendly cross-development platforms with the addition of GPU accelerated support for most applications. Apart from providing these fabulous features, it also allows the developers to implement their codes across devices like the Raspberry Pi. Below is a simple code block demonstrating a working example of Kivy in action. The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information. from kivy.app import Appfrom kivy.uix.widget import Widgetfrom kivy.graphics import Color, Ellipseclass MyPaintWidget(Widget): def on_touch_down(self, touch): with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))class MyPaintApp(App): def build(self): return MyPaintWidget()if __name__ == '__main__': MyPaintApp().run() The GUI interface designed in the above code block will help you to draw an ellipse-shaped object with the help of each click. I decided to draw a random face with the following option, and this function is noticeable in the above image posted. Have fun and make your own innovative designs, as well as check out further options for the Kivy package. The wxPython is easy to install with a simple pip install command and can be used to create amazing GUI frameworks. They are basically an extension of the wrapper class in Python for creating numerous applications. It is a great cross-platform alternative for some of the other GUI options mentioned in this article to create some simple projects. This package is extremely easy to use and creates GUI interfaces. Due to its simplicity, we can create windows, panels, labels, and other features with ease. The below code block is a representation of how you can construct a GUI to display some labels. The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information. import wx app = wx.App() window = wx.Frame(None, title = "wxPython Frame", size = (300,200)) panel = wx.Panel(window) label = wx.StaticText(panel, label = "Hello World", pos = (100,50)) window.Show(True) app.MainLoop() While the other sections in this article have extensively covered the working procedures of different types of Graphical User Interfaces (GUI) on the desktop, we will look at two web development tools for constructing web-based GUI’s. Flask and Django are two Python libraries that will help to perform numerous actions and operations to create a web-based GUI network. In the below section, we have discussed some simple code blocks for both Flask and Django. These codes are just for beginners to explore the high amount of potential they have. The Flask code will enable you to run the desired print command in the local desktop host that is provided to you after you run the program. In future articles, we will explore both Flask and Django separately and understood how to code machine learning projects with them as well. Some applications are AI video surveillance on the web. from flask import Flask, render_template, redirect, url_forapp = Flask(__name__)@app.route("/")@app.route("/home")def home(): # return "<h1>HELLO!</h1>This is the home page " return render_template("home.html") # Render the home.html in the templates folderif __name__ == "__main__": app.run(debug=True) #Debugable mode # app.run() # Normal Run from django.http import HttpResponsedef index(request): return HttpResponse('Hello, World!') “Design is everywhere. From the dress you’re wearing to the smartphone you’re holding, it’s design.” — Samadara Ginige The Python programming language offers enormous potential to create fabulous graphics user interface tools for performing a variety of projects. Apart from adding visual and aesthetic appeal to numerous tasks, it also allows the developers to make their projects highly interactive. These GUI tools are highly effective for most practical applications, including software designing projects, AI projects, machine learning or deep learning models, web development, and so much more. In this article, we explored some fantastic Graphics User Interface tools with which developers can implement some unique features. With the help of Python and the spectacular library options it offers the developers, we can construct a classic GUI framework with Tkinter or PyQt5. We can also construct more unique GUIs with Pygame or Open-CV for games and computer vision applications, respectively. Kivy and wxPython are two other fantastic desktop GUI options. Finally, we also explored Flask and Django, with which we can construct web-based GUI’s. While we have explored seven fantastic GUI tools and libraries that are available in Python for the development of unique applications, there are still so many fabulous tools out there to explore. If you have any other cool suggestions, make sure to comment them down below. If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible. Check out some of my other articles that you might enjoy reading! towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com towardsdatascience.com Thank you all for sticking on till the end. I hope all of you enjoyed reading the article. Wish you all a wonderful day!
[ { "code": null, "e": 657, "s": 172, "text": "Python is such a versatile language that it can accomplish most tasks that different programming languages are meant to achieve. Although Python is used more frequently for applications and projects related to artificial intelligence, data science, data visualizations, data analytics, and other similar operations, we are by no means limited to these boundaries. You can perform web development, build games, construct numerous GUI tools, and so much more as a developer with Python." }, { "code": null, "e": 1128, "s": 657, "text": "The Graphics User Interface (GUI) built with Python are extremely useful for a variety of projects. You can use these technologies to make your projects unique, aesthetically pleasing, visually appealing, highly interactive environment, and provide users with other similar wonderful features. You can even use these tools for developing artificial intelligence projects with machine learning or deep learning models to make them stand out from other such project ideas." }, { "code": null, "e": 1570, "s": 1128, "text": "In this article, we will objectively look at some of the best GUI tools that are available to the developers with the help of Python coding. We will explore seven such libraries that give users the best aim of implementing their desired GUI applications. To follow along with this article and implement all your codes accordingly, I would suggest the viewers pick the editor of their favorite choice and get their hands dirty with some code." }, { "code": null, "e": 1904, "s": 1570, "text": "I am personally using Visual Studio Code for my programming, but you can feel free to use your preferred choices. However, if you are having a tough time choosing the best option for you, the following link on the list of over ten awesome Python editors with pros and cons will help you decide the best-suited editor for your coding." }, { "code": null, "e": 1927, "s": 1904, "text": "towardsdatascience.com" }, { "code": null, "e": 2256, "s": 1927, "text": "The Tkinter package that is available in Python is one of the best tools for most graphics-related applications. It is available for both Windows and Linux platforms with a simple pip installation. The Tkinter library allows the users to develop high-quality graphic interfaces with the help of the numerous options it contains." }, { "code": null, "e": 2695, "s": 2256, "text": "Tkinter has various options for providing a valuable structure to your desired application with the help of frames, buttons, and check buttons for creating interactive selections, displaying information with labels, draw data and statistical information with Canvas, and so much more. The starter code The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information." }, { "code": null, "e": 2923, "s": 2695, "text": "from tkinter import *master = Tk()Label(master, text='Enter Your Name').grid(row=0)Label(master, text='Enter Your Email').grid(row=1)e1 = Entry(master)e2 = Entry(master)e1.grid(row=0, column=1)e2.grid(row=1, column=1)mainloop()" }, { "code": null, "e": 3190, "s": 2923, "text": "In the following code block shown above, we are creating a simple program with which we are creating two simple grid boxes that will register the name and email of a particular individual. Feel free to explore the library further and construct more complex projects." }, { "code": null, "e": 3567, "s": 3190, "text": "The Qt is a set of cross-platform C++ libraries that implement high-level APIs for accessing many aspects of modern desktop and mobile systems. The Qt platform offers developers a wide variety of unique solutions to develop numerous applications and solve a humungous array of complex tasks. With a simple pip install command, you can start with the following GUI application." }, { "code": null, "e": 3818, "s": 3567, "text": "The development of GUI applications with the help of Python and the PyQt5 library is rather simple and can be completed with a few lines of code. Below is a code block demonstration of how we can generate interactive GUI interfaces with this package." }, { "code": null, "e": 4157, "s": 3818, "text": "import sysfrom PyQt5.QtCore import *from PyQt5.QtGui import *from PyQt5.QtWidgets import *def window(): app = QApplication(sys.argv) w = QWidget() b = QLabel(w) b.setText(\"Welcome!\") w.setGeometry(100,100,200,50) b.move(50,20) w.setWindowTitle(\"PyQt5\") w.show() sys.exit(app.exec_())if __name__ == '__main__': window()" }, { "code": null, "e": 4467, "s": 4157, "text": "The following code block will display a graphical user interface with a Welcome command. Further advanced widgets and elements can be added to make the code more appealing. The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information." }, { "code": null, "e": 4880, "s": 4467, "text": "Unlike the two previously discussed GUI tools, Pygame is slightly different in comparison. With Pygame, you can construct and build Python games from scratch. While their performance and graphics might not be the best in comparison to some other programming languages like C# and some elite game designing software’s it is still a great way for most beginners to get started due to the ease of coding procedures." }, { "code": null, "e": 5352, "s": 4880, "text": "One of the main advantages of working with Pygame, apart from building games, is the GUI capabilities that it has. It allows the developers to create a GUI interface with which numerous actions can be controlled. There are a lot of options available in Pygame to develop entities (like widgets or icons) in the user interface and control some desirable actions. Below is some starter code to get more experience with this module for developing more projects from scratch." }, { "code": null, "e": 5813, "s": 5352, "text": "#imports the pygame library moduleimport pygame# initilize the pygame modulepygame.init()# Setting your screen size with a tuple of the screen width and screen heightdisplay_screen = pygame.display.set_mode((800,600))# Setting a random caption title for your pygame graphical window.pygame.display.set_caption(\"pygame test\")# Update your screen when requiredpygame.display.update()# quit the pygame initialization and modulepygame.quit()# End the programquit()" }, { "code": null, "e": 6230, "s": 5813, "text": "In the above coding section, we have discussed some starter code for creating a graphical window of a particular size with Pygame. There are tons more applications and games that you can build with the help of this Python library. To understand five reasons why every developer should invest their time developing a game with Python and AI, check out one of my previous articles on five reasons why you should do so." }, { "code": null, "e": 6253, "s": 6230, "text": "towardsdatascience.com" }, { "code": null, "e": 6678, "s": 6253, "text": "Open-CV is one of the best libraries for computer vision tasks and image processing. This library offers fantastic utility for performing a wide array of tasks. With the help of Open-CV, it is also possible to construct GUI applications as well with a customizable interface. While the options that are available for Open for GUI are not as vast as the other options, there is a vast amount of technical stuff you can build." }, { "code": null, "e": 6899, "s": 6678, "text": "Save the above image in your desktop (or download it from the mentioned link) as Lena, and ensure that is in a .png format. Below is the starter code for some of the actions that you can perform with the Open-CV library." }, { "code": null, "e": 7233, "s": 6899, "text": "# Importing the opencv moduleimport cv2# Read The Imageimage = cv2.imread(\"lena.png\")# Frame Title with the image to be displayedcv2.imshow(\"Picture\", image) cv2.waitKey(0)# Convert the color image to grayscale imagegray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)# Display Grayscale imagecv2.imshow(\"Gray Picture\", gray)cv2.waitKey(0)" }, { "code": null, "e": 7629, "s": 7233, "text": "The above starter code explores the basic implementation of some of the functionalities of the Open-CV library. If you are interested to dwell further into exploring more about this particular library and understand more about computer vision, check out one of my previous articles that covers the complete beginner’s guide on getting started with Open-CV from the following link provided below." }, { "code": null, "e": 7652, "s": 7629, "text": "towardsdatascience.com" }, { "code": null, "e": 7980, "s": 7652, "text": "Another fantastic open-source package that allows users to create some high-quality graphical user interfaces is Kivy. It can be installed with the pip installation for Python. It offers developers one of the best business-friendly cross-development platforms with the addition of GPU accelerated support for most applications." }, { "code": null, "e": 8336, "s": 7980, "text": "Apart from providing these fabulous features, it also allows the developers to implement their codes across devices like the Raspberry Pi. Below is a simple code block demonstrating a working example of Kivy in action. The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information." }, { "code": null, "e": 8760, "s": 8336, "text": "from kivy.app import Appfrom kivy.uix.widget import Widgetfrom kivy.graphics import Color, Ellipseclass MyPaintWidget(Widget): def on_touch_down(self, touch): with self.canvas: Color(1, 1, 0) d = 30. Ellipse(pos=(touch.x - d / 2, touch.y - d / 2), size=(d, d))class MyPaintApp(App): def build(self): return MyPaintWidget()if __name__ == '__main__': MyPaintApp().run()" }, { "code": null, "e": 9111, "s": 8760, "text": "The GUI interface designed in the above code block will help you to draw an ellipse-shaped object with the help of each click. I decided to draw a random face with the following option, and this function is noticeable in the above image posted. Have fun and make your own innovative designs, as well as check out further options for the Kivy package." }, { "code": null, "e": 9459, "s": 9111, "text": "The wxPython is easy to install with a simple pip install command and can be used to create amazing GUI frameworks. They are basically an extension of the wrapper class in Python for creating numerous applications. It is a great cross-platform alternative for some of the other GUI options mentioned in this article to create some simple projects." }, { "code": null, "e": 9850, "s": 9459, "text": "This package is extremely easy to use and creates GUI interfaces. Due to its simplicity, we can create windows, panels, labels, and other features with ease. The below code block is a representation of how you can construct a GUI to display some labels. The code reference for the following starter code is taken from this link. Check it out for more advanced codes and further information." }, { "code": null, "e": 10070, "s": 9850, "text": "import wx app = wx.App() window = wx.Frame(None, title = \"wxPython Frame\", size = (300,200)) panel = wx.Panel(window) label = wx.StaticText(panel, label = \"Hello World\", pos = (100,50)) window.Show(True) app.MainLoop()" }, { "code": null, "e": 10440, "s": 10070, "text": "While the other sections in this article have extensively covered the working procedures of different types of Graphical User Interfaces (GUI) on the desktop, we will look at two web development tools for constructing web-based GUI’s. Flask and Django are two Python libraries that will help to perform numerous actions and operations to create a web-based GUI network." }, { "code": null, "e": 10955, "s": 10440, "text": "In the below section, we have discussed some simple code blocks for both Flask and Django. These codes are just for beginners to explore the high amount of potential they have. The Flask code will enable you to run the desired print command in the local desktop host that is provided to you after you run the program. In future articles, we will explore both Flask and Django separately and understood how to code machine learning projects with them as well. Some applications are AI video surveillance on the web." }, { "code": null, "e": 11300, "s": 10955, "text": "from flask import Flask, render_template, redirect, url_forapp = Flask(__name__)@app.route(\"/\")@app.route(\"/home\")def home(): # return \"<h1>HELLO!</h1>This is the home page \" return render_template(\"home.html\") # Render the home.html in the templates folderif __name__ == \"__main__\": app.run(debug=True) #Debugable mode # app.run() # Normal Run" }, { "code": null, "e": 11396, "s": 11300, "text": "from django.http import HttpResponsedef index(request): return HttpResponse('Hello, World!')" }, { "code": null, "e": 11515, "s": 11396, "text": "“Design is everywhere. From the dress you’re wearing to the smartphone you’re holding, it’s design.” — Samadara Ginige" }, { "code": null, "e": 11997, "s": 11515, "text": "The Python programming language offers enormous potential to create fabulous graphics user interface tools for performing a variety of projects. Apart from adding visual and aesthetic appeal to numerous tasks, it also allows the developers to make their projects highly interactive. These GUI tools are highly effective for most practical applications, including software designing projects, AI projects, machine learning or deep learning models, web development, and so much more." }, { "code": null, "e": 12551, "s": 11997, "text": "In this article, we explored some fantastic Graphics User Interface tools with which developers can implement some unique features. With the help of Python and the spectacular library options it offers the developers, we can construct a classic GUI framework with Tkinter or PyQt5. We can also construct more unique GUIs with Pygame or Open-CV for games and computer vision applications, respectively. Kivy and wxPython are two other fantastic desktop GUI options. Finally, we also explored Flask and Django, with which we can construct web-based GUI’s." }, { "code": null, "e": 12826, "s": 12551, "text": "While we have explored seven fantastic GUI tools and libraries that are available in Python for the development of unique applications, there are still so many fabulous tools out there to explore. If you have any other cool suggestions, make sure to comment them down below." }, { "code": null, "e": 13024, "s": 12826, "text": "If you have any queries related to the various points stated in this article, then feel free to let me know in the comments below. I will try to get back to you with a response as soon as possible." }, { "code": null, "e": 13090, "s": 13024, "text": "Check out some of my other articles that you might enjoy reading!" }, { "code": null, "e": 13113, "s": 13090, "text": "towardsdatascience.com" }, { "code": null, "e": 13136, "s": 13113, "text": "towardsdatascience.com" }, { "code": null, "e": 13159, "s": 13136, "text": "towardsdatascience.com" }, { "code": null, "e": 13182, "s": 13159, "text": "towardsdatascience.com" }, { "code": null, "e": 13205, "s": 13182, "text": "towardsdatascience.com" } ]
Construct Tree from Inorder & Preorder | Practice | GeeksforGeeks
Given 2 Arrays of Inorder and preorder traversal. Construct a tree and print the Postorder traversal. Example 1: Input: N = 4 inorder[] = {1 6 8 7} preorder[] = {1 6 7 8} Output: 8 7 6 1 Example 2: Input: N = 6 inorder[] = {3 1 4 0 5 2} preorder[] = {0 1 3 4 2 5} Output: 3 4 1 5 2 0 Explanation: The tree will look like 0 / \ 1 2 / \ / 3 4 5 Your Task: Your task is to complete the function buildTree() which takes 3 arguments(inorder traversal array, preorder traversal array, and size of tree n) and returns the root node to the tree constructed. You are not required to print anything and a new line is added automatically (The post order of the returned tree is printed by the driver's code.) Expected Time Complexity: O(N*N). Expected Auxiliary Space: O(N). Constraints: 1<=Number of Nodes<=1000 0 ruchitchudasama1236 hours ago class Solution{ public: Node* makeBT(int in[],int pre[],int li,int hi,int lp,int hp,map<int,int> &mpp){ if(lp<0 || lp>hp)return NULL; int rootData=pre[lp]; Node* root=new Node(rootData); int index = mpp[rootData]; int numLeft=lp+index-li; root->left=makeBT(in,pre,li,index-1,lp+1,numLeft,mpp); root->right=makeBT(in,pre,index+1,hi,numLeft+1,hp,mpp); return root; } Node* buildTree(int in[],int pre[], int n) { map<int,int> mpp; for(int i=0;i<n;i++){ mpp[in[i]]=i; } return makeBT(in,pre,0,n-1,0,n-1,mpp); } }; 0 utkarshagarwal1011 day ago class Solution{ public: Node* helper(int prestart, int preend, int instart, int inend, int preorder[], int inorder[],int n){ if(prestart>preend||instart>inend){ return NULL; } Node* curr = new Node(preorder[prestart]); int idx=instart; int leftTreeSize =0; while(idx<n&&inorder[idx]!=preorder[prestart]){ idx++; leftTreeSize++; } Node* leftTree = helper(prestart+1,prestart+leftTreeSize,instart,idx-1,preorder,inorder,n); Node* rightTree = helper(prestart+leftTreeSize+1,preend,idx+1,inend,preorder,inorder,n); curr->left = leftTree; curr->right = rightTree; return curr; } Node* buildTree(int in[],int pre[], int n) { // Code here return helper(0,n-1,0,n-1,pre,in,n); } }; 0 mirsayib1 day ago class Solution{ public: unordered_map<int, int> ump; Node* helper(int* inorder, int* preorder, int st, int en, int pr_st){ if(st > en) return NULL; int root_val = preorder[pr_st]; int root_idx = ump[root_val]; //index of root in inorder arr int l_size = root_idx-st; Node* root = new Node(root_val); root->left = helper(inorder, preorder, st, root_idx-1, pr_st+1); root->right = helper(inorder, preorder, root_idx+1, en, pr_st+l_size+1); return root; } Node* buildTree(int inorder[],int preorder[], int n) { // Code here for(int i = 0; i<n; i++) ump[inorder[i]] = i; return helper(inorder, preorder, 0, n-1, 0); } }; 0 akashdogra1712 days ago Node* helper(int in[], int pre[], int inS, int inE, int preS, int preE){ if(inS > inE){ return NULL; } int rootData = pre[preS]; int rootIndex = -1; for(int i =inS;i<=inE;i++){ if(in[i] == rootData){ rootIndex = i; break; } } int leftInS = inS; int leftInE = rootIndex - 1; int leftPreS = preS + 1; int leftPreE = leftPreS + leftInE - leftInS; int rightInS = rootIndex + 1; int rightInE = inE; int rightPreS = leftPreE + 1; int rightPreE = preE; Node* root = new Node(rootData); root->left = helper(in,pre, leftInS, leftInE, leftPreS, leftPreE); root->right = helper(in, pre, rightInS, rightInE, rightPreS, rightPreE); } Node* buildTree(int in[],int pre[], int n) { helper(in, pre , 0, n-1 , 0 , n-1); } +1 parasdhanwal263 days ago <<Java Solution>> class Solution { public static Node buildTree(int inorder[], int preorder[], int n) { HashMap<Integer,Integer> map=new HashMap<>(); for(int i=0;i<inorder.length;i++) { map.put(inorder[i],i); } Node ans=construct(preorder,0,n-1,inorder,0,n-1,map); return ans; // code here } static Node construct(int preorder[], int prestart, int preend, int inorder[], int instart, int inend, HashMap<Integer, Integer> map) { if(prestart>preend||instart>inend) { return null; } Node newNode=new Node(preorder[prestart]); int rootlocationinorder=map.get(preorder[prestart]); int no_of_children=rootlocationinorder-instart; newNode.left=construct(preorder,prestart+1,prestart+1+no_of_children,inorder,instart,rootlocationinorder-1,map); newNode.right=construct(preorder,prestart+1+no_of_children,preend,inorder,rootlocationinorder+1,inend,map); return newNode; } } 0 ialtafshaikh1 week ago Easy and optimised solution in Python------------------------------------- def buildtree(self, inorder, preorder, n): inorderMap = { inorder[index] : index for index in range(len(inorder))} return self.treeConstruction(preorder, inorderMap, 0, n-1) def treeConstruction(self, preorder, inorderMap, start, end): if(start > end or not len(preorder)): return None root = Node(preorder.pop(0)) root.left = self.treeConstruction(preorder,inorderMap, start, inorderMap[root.data] - 1) root.right = self.treeConstruction(preorder,inorderMap, inorderMap[root.data] + 1, end) return root 0 mayankkannojia291 week ago So nodes data are distinct nos? +2 6288262 weeks ago Nice and concise. The while-loop might be a little noisy, but the code is decent. if (n == 0) return NULL; Node *node = new Node(pre[0]); int i = 0; while (in[i] != pre[0]) ++ i; node->left = buildTree(in, pre + 1, i ++); node->right = buildTree(in + i, pre + i, n - i); return node; 0 koulikmaity3 weeks ago int findPosition(int in[], int element, int n) { for(int i=0; i<n; i++) { if(in[i] == element) return i; } return -1; } Node* solve(int in[], int pre[], int &index, int inorderStart, int inorderEnd, int n) { // base case if(index >= n || inorderStart>inorderEnd) return NULL; int element = pre[index++]; int position = findPosition(in, element, n); Node* root = new Node(element); // recursive call for left root->left = solve(in, pre, index, inorderStart, position-1, n); root->right = solve(in, pre, index, position+1, inorderEnd, n); return root; } Node* buildTree(int in[],int pre[], int n) { int preOrderIndex = 0; Node* ans = solve(in, pre, preOrderIndex, 0, n-1, n ); return ans; } +1 smdakhtar0073 weeks ago class Solution{ public: int search(int arr[] , int st , int en , int data) { for(int i = st ; i<=en ; i++){ if((arr[i])==data){ return i; } } } int preindex = 0 ; Node*traversal(int in[] , int pre[] , int st , int end){ if(st>end){ return NULL; } Node*ans = new Node(pre[preindex++]); if(st==end){ return ans; } int inindex = search(in ,st , end , ans->data); ans->left=traversal(in,pre,st,inindex-1); ans->right=traversal(in ,pre, inindex+1,end); return ans; } Node* buildTree(int in[],int pre[], int n) { return traversal(in , pre , 0 , n-1); } }; 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": 341, "s": 238, "text": "Given 2 Arrays of Inorder and preorder traversal. Construct a tree and print the Postorder traversal. " }, { "code": null, "e": 352, "s": 341, "text": "Example 1:" }, { "code": null, "e": 427, "s": 352, "text": "Input:\nN = 4\ninorder[] = {1 6 8 7}\npreorder[] = {1 6 7 8}\nOutput: 8 7 6 1\n" }, { "code": null, "e": 438, "s": 427, "text": "Example 2:" }, { "code": null, "e": 618, "s": 438, "text": "Input:\nN = 6\ninorder[] = {3 1 4 0 5 2}\npreorder[] = {0 1 3 4 2 5}\nOutput: 3 4 1 5 2 0\nExplanation: The tree will look like\n 0\n / \\\n 1 2\n / \\ /\n3 4 5" }, { "code": null, "e": 973, "s": 618, "text": "Your Task:\nYour task is to complete the function buildTree() which takes 3 arguments(inorder traversal array, preorder traversal array, and size of tree n) and returns the root node to the tree constructed. You are not required to print anything and a new line is added automatically (The post order of the returned tree is printed by the driver's code.)" }, { "code": null, "e": 1039, "s": 973, "text": "Expected Time Complexity: O(N*N).\nExpected Auxiliary Space: O(N)." }, { "code": null, "e": 1077, "s": 1039, "text": "Constraints:\n1<=Number of Nodes<=1000" }, { "code": null, "e": 1079, "s": 1077, "text": "0" }, { "code": null, "e": 1109, "s": 1079, "text": "ruchitchudasama1236 hours ago" }, { "code": null, "e": 1761, "s": 1109, "text": "class Solution{\n public:\n Node* makeBT(int in[],int pre[],int li,int hi,int lp,int hp,map<int,int> &mpp){\n if(lp<0 || lp>hp)return NULL;\n \n int rootData=pre[lp];\n Node* root=new Node(rootData);\n int index = mpp[rootData];\n int numLeft=lp+index-li;\n root->left=makeBT(in,pre,li,index-1,lp+1,numLeft,mpp);\n root->right=makeBT(in,pre,index+1,hi,numLeft+1,hp,mpp);\n return root;\n \n }\n Node* buildTree(int in[],int pre[], int n)\n {\n map<int,int> mpp;\n for(int i=0;i<n;i++){\n mpp[in[i]]=i;\n }\n return makeBT(in,pre,0,n-1,0,n-1,mpp);\n }\n};" }, { "code": null, "e": 1763, "s": 1761, "text": "0" }, { "code": null, "e": 1790, "s": 1763, "text": "utkarshagarwal1011 day ago" }, { "code": null, "e": 2666, "s": 1790, "text": "class Solution{\n public:\n \n Node* helper(int prestart, int preend, int instart, int inend, int preorder[], int inorder[],int n){\n if(prestart>preend||instart>inend){\n return NULL;\n }\n Node* curr = new Node(preorder[prestart]);\n \n int idx=instart;\n int leftTreeSize =0;\n while(idx<n&&inorder[idx]!=preorder[prestart]){\n idx++;\n leftTreeSize++;\n }\n Node* leftTree = helper(prestart+1,prestart+leftTreeSize,instart,idx-1,preorder,inorder,n);\n Node* rightTree = helper(prestart+leftTreeSize+1,preend,idx+1,inend,preorder,inorder,n);\n curr->left = leftTree;\n curr->right = rightTree;\n return curr;\n \n }\n Node* buildTree(int in[],int pre[], int n)\n {\n // Code here\n return helper(0,n-1,0,n-1,pre,in,n);\n }\n};" }, { "code": null, "e": 2668, "s": 2666, "text": "0" }, { "code": null, "e": 2686, "s": 2668, "text": "mirsayib1 day ago" }, { "code": null, "e": 3527, "s": 2686, "text": "class Solution{\n public:\n unordered_map<int, int> ump;\n Node* helper(int* inorder, int* preorder, int st, int en, int pr_st){\n \n if(st > en) return NULL;\n \n int root_val = preorder[pr_st];\n int root_idx = ump[root_val]; //index of root in inorder arr\n \n int l_size = root_idx-st;\n \n Node* root = new Node(root_val);\n \n \n root->left = helper(inorder, preorder, st, root_idx-1, pr_st+1);\n root->right = helper(inorder, preorder, root_idx+1, en, pr_st+l_size+1);\n \n return root;\n \n \n }\n Node* buildTree(int inorder[],int preorder[], int n)\n {\n // Code here\n for(int i = 0; i<n; i++) ump[inorder[i]] = i;\n \n return helper(inorder, preorder, 0, n-1, 0);\n \n \n }\n};" }, { "code": null, "e": 3529, "s": 3527, "text": "0" }, { "code": null, "e": 3553, "s": 3529, "text": "akashdogra1712 days ago" }, { "code": null, "e": 4478, "s": 3553, "text": "Node* helper(int in[], int pre[], int inS, int inE, int preS, int preE){ if(inS > inE){ return NULL; } int rootData = pre[preS]; int rootIndex = -1; for(int i =inS;i<=inE;i++){ if(in[i] == rootData){ rootIndex = i; break; } } int leftInS = inS; int leftInE = rootIndex - 1; int leftPreS = preS + 1; int leftPreE = leftPreS + leftInE - leftInS; int rightInS = rootIndex + 1; int rightInE = inE; int rightPreS = leftPreE + 1; int rightPreE = preE; Node* root = new Node(rootData); root->left = helper(in,pre, leftInS, leftInE, leftPreS, leftPreE); root->right = helper(in, pre, rightInS, rightInE, rightPreS, rightPreE); } Node* buildTree(int in[],int pre[], int n) { helper(in, pre , 0, n-1 , 0 , n-1); }" }, { "code": null, "e": 4483, "s": 4480, "text": "+1" }, { "code": null, "e": 4508, "s": 4483, "text": "parasdhanwal263 days ago" }, { "code": null, "e": 4526, "s": 4508, "text": "<<Java Solution>>" }, { "code": null, "e": 5615, "s": 4528, "text": "class Solution\n{\n public static Node buildTree(int inorder[], int preorder[], int n)\n {\n HashMap<Integer,Integer> map=new HashMap<>();\n \n for(int i=0;i<inorder.length;i++)\n {\n map.put(inorder[i],i);\n }\n \n Node ans=construct(preorder,0,n-1,inorder,0,n-1,map);\n return ans;\n // code here \n }\n \n static Node construct(int preorder[], int prestart, int preend, int inorder[], int instart, int inend,\n HashMap<Integer, Integer> map) {\n if(prestart>preend||instart>inend)\n {\n return null;\n \n }\n \n Node newNode=new Node(preorder[prestart]);\n int rootlocationinorder=map.get(preorder[prestart]);\n int no_of_children=rootlocationinorder-instart;\n newNode.left=construct(preorder,prestart+1,prestart+1+no_of_children,inorder,instart,rootlocationinorder-1,map);\n newNode.right=construct(preorder,prestart+1+no_of_children,preend,inorder,rootlocationinorder+1,inend,map);\n \n return newNode;\n }\n}\n" }, { "code": null, "e": 5617, "s": 5615, "text": "0" }, { "code": null, "e": 5640, "s": 5617, "text": "ialtafshaikh1 week ago" }, { "code": null, "e": 5715, "s": 5640, "text": "Easy and optimised solution in Python-------------------------------------" }, { "code": null, "e": 6306, "s": 5715, "text": "def buildtree(self, inorder, preorder, n):\n inorderMap = { inorder[index] : index for index in range(len(inorder))}\n return self.treeConstruction(preorder, inorderMap, 0, n-1)\n \n def treeConstruction(self, preorder, inorderMap, start, end):\n if(start > end or not len(preorder)): return None\n root = Node(preorder.pop(0))\n \n root.left = self.treeConstruction(preorder,inorderMap, start, inorderMap[root.data] - 1)\n root.right = self.treeConstruction(preorder,inorderMap, inorderMap[root.data] + 1, end)\n \n return root" }, { "code": null, "e": 6308, "s": 6306, "text": "0" }, { "code": null, "e": 6335, "s": 6308, "text": "mayankkannojia291 week ago" }, { "code": null, "e": 6367, "s": 6335, "text": "So nodes data are distinct nos?" }, { "code": null, "e": 6370, "s": 6367, "text": "+2" }, { "code": null, "e": 6388, "s": 6370, "text": "6288262 weeks ago" }, { "code": null, "e": 6406, "s": 6388, "text": "Nice and concise." }, { "code": null, "e": 6470, "s": 6406, "text": "The while-loop might be a little noisy, but the code is decent." }, { "code": null, "e": 6680, "s": 6470, "text": "if (n == 0)\n\treturn NULL;\n\t\nNode *node = new Node(pre[0]);\nint i = 0;\n\nwhile (in[i] != pre[0])\n\t++ i;\n\t\nnode->left = buildTree(in, pre + 1, i ++);\nnode->right = buildTree(in + i, pre + i, n - i);\n\nreturn node;" }, { "code": null, "e": 6682, "s": 6680, "text": "0" }, { "code": null, "e": 6705, "s": 6682, "text": "koulikmaity3 weeks ago" }, { "code": null, "e": 7588, "s": 6705, "text": "int findPosition(int in[], int element, int n) { for(int i=0; i<n; i++) { if(in[i] == element) return i; } return -1; } Node* solve(int in[], int pre[], int &index, int inorderStart, int inorderEnd, int n) { // base case if(index >= n || inorderStart>inorderEnd) return NULL; int element = pre[index++]; int position = findPosition(in, element, n); Node* root = new Node(element); // recursive call for left root->left = solve(in, pre, index, inorderStart, position-1, n); root->right = solve(in, pre, index, position+1, inorderEnd, n); return root; } Node* buildTree(int in[],int pre[], int n) { int preOrderIndex = 0; Node* ans = solve(in, pre, preOrderIndex, 0, n-1, n ); return ans; }" }, { "code": null, "e": 7591, "s": 7588, "text": "+1" }, { "code": null, "e": 7615, "s": 7591, "text": "smdakhtar0073 weeks ago" }, { "code": null, "e": 8395, "s": 7615, "text": "class Solution{\n public:\n int search(int arr[] , int st , int en , int data)\n {\n for(int i = st ; i<=en ; i++){\n if((arr[i])==data){\n return i;\n }\n }\n }\n int preindex = 0 ;\n Node*traversal(int in[] , int pre[] , int st , int end){\n \n if(st>end){\n return NULL;\n }\n Node*ans = new Node(pre[preindex++]);\n if(st==end){\n return ans;\n }\n int inindex = search(in ,st , end , ans->data);\n ans->left=traversal(in,pre,st,inindex-1);\n ans->right=traversal(in ,pre, inindex+1,end);\n return ans;\n \n }\n Node* buildTree(int in[],int pre[], int n)\n {\n return traversal(in , pre , 0 , n-1);\n }\n \n \n};" }, { "code": null, "e": 8541, "s": 8395, "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": 8577, "s": 8541, "text": " Login to access your submissions. " }, { "code": null, "e": 8587, "s": 8577, "text": "\nProblem\n" }, { "code": null, "e": 8597, "s": 8587, "text": "\nContest\n" }, { "code": null, "e": 8660, "s": 8597, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8808, "s": 8660, "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": 9016, "s": 8808, "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": 9122, "s": 9016, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to set background image of a webpage?
To set the background image of a webpage, use the CSS style. Under the CSS <style> tag, add the property background-image. The property sets a graphic such as jpg, png, svg, gif, etc. HTML5 do not support the <body> background attribute, so CSS is used to change set background image. You can try the following code to set the background image of a web page in HTML Live Demo <!DOCTYPE html> <html> <head> <style> body { background-image: url("/videotutorials/images/tutor_connect_home.jpg"); } </style> </head> <body> <h1>Connect with Tutors</h1> </body> </html>
[ { "code": null, "e": 1347, "s": 1062, "text": "To set the background image of a webpage, use the CSS style. Under the CSS <style> tag, add the property background-image. The property sets a graphic such as jpg, png, svg, gif, etc. HTML5 do not support the <body> background attribute, so CSS is used to change set background image." }, { "code": null, "e": 1428, "s": 1347, "text": "You can try the following code to set the background image of a web page in HTML" }, { "code": null, "e": 1438, "s": 1428, "text": "Live Demo" }, { "code": null, "e": 1687, "s": 1438, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n body {\n background-image: url(\"/videotutorials/images/tutor_connect_home.jpg\");\n }\n </style>\n </head>\n\n <body>\n <h1>Connect with Tutors</h1>\n </body>\n</html>" } ]
C library function - sprintf()
The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str. Following is the declaration for sprintf() function. int sprintf(char *str, const char *format, ...) str − This is the pointer to an array of char elements where the resulting C string is stored. str − This is the pointer to an array of char elements where the resulting C string is stored. format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype: %[flags][width][.precision][length]specifier, as explained below − format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype: %[flags][width][.precision][length]specifier, as explained below − c Character d or i Signed decimal integer e Scientific notation (mantissa/exponent) using e character E Scientific notation (mantissa/exponent) using E character f Decimal floating point g Uses the shorter of %e or %f. G Uses the shorter of %E or %f o Signed octal s String of characters u Unsigned decimal integer x Unsigned hexadecimal integer X Unsigned hexadecimal integer (capital letters) p Pointer address n Nothing printed % Character - Left-justify within the given field width; Right justification is the default (see width sub-specifier). + Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign. (space) If no sign is going to be written, a blank space is inserted before the value. # Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed. 0 Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier). (number) Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger. * The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. .number For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers − this is the number of digits to be printed after the decimal point. For g and G specifiers − This is the maximum number of significant digits to be printed. For s − this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type − it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed. .* The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted. h The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X). l The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s. L The argument is interpreted as a long double (only applies to floating point specifiers − e, E, f, g and G). additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter (if any). There should be the same number of these arguments as the number of %-tags that expect a value. additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter (if any). There should be the same number of these arguments as the number of %-tags that expect a value. If successful, the total number of characters written is returned excluding the null-character appended at the end of the string, otherwise a negative number is returned in case of failure. The following example shows the usage of sprintf() function. #include <stdio.h> #include <math.h> int main () { char str[80]; sprintf(str, "Value of Pi = %f", M_PI); puts(str); return(0); } Let us compile and run the above program, this will produce the following result − Value of Pi = 3.141593 12 Lectures 2 hours Nishant Malik 12 Lectures 2.5 hours Nishant Malik 48 Lectures 6.5 hours Asif Hussain 12 Lectures 2 hours Richa Maheshwari 20 Lectures 3.5 hours Vandana Annavaram 44 Lectures 1 hours Amit Diwan Print Add Notes Bookmark this page
[ { "code": null, "e": 2133, "s": 2007, "text": "The C library function int sprintf(char *str, const char *format, ...) sends formatted output to a string pointed to, by str." }, { "code": null, "e": 2186, "s": 2133, "text": "Following is the declaration for sprintf() function." }, { "code": null, "e": 2234, "s": 2186, "text": "int sprintf(char *str, const char *format, ...)" }, { "code": null, "e": 2329, "s": 2234, "text": "str − This is the pointer to an array of char elements where the resulting C string is stored." }, { "code": null, "e": 2424, "s": 2329, "text": "str − This is the pointer to an array of char elements where the resulting C string is stored." }, { "code": null, "e": 2742, "s": 2424, "text": "format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype: %[flags][width][.precision][length]specifier, as explained below −" }, { "code": null, "e": 3060, "s": 2742, "text": "format − This is the String that contains the text to be written to buffer. It can optionally contain embedded format tags that are replaced by the values specified in subsequent additional arguments and formatted as requested. Format tags prototype: %[flags][width][.precision][length]specifier, as explained below −" }, { "code": null, "e": 3062, "s": 3060, "text": "c" }, { "code": null, "e": 3072, "s": 3062, "text": "Character" }, { "code": null, "e": 3079, "s": 3072, "text": "d or i" }, { "code": null, "e": 3102, "s": 3079, "text": "Signed decimal integer" }, { "code": null, "e": 3104, "s": 3102, "text": "e" }, { "code": null, "e": 3162, "s": 3104, "text": "Scientific notation (mantissa/exponent) using e character" }, { "code": null, "e": 3164, "s": 3162, "text": "E" }, { "code": null, "e": 3222, "s": 3164, "text": "Scientific notation (mantissa/exponent) using E character" }, { "code": null, "e": 3224, "s": 3222, "text": "f" }, { "code": null, "e": 3247, "s": 3224, "text": "Decimal floating point" }, { "code": null, "e": 3249, "s": 3247, "text": "g" }, { "code": null, "e": 3279, "s": 3249, "text": "Uses the shorter of %e or %f." }, { "code": null, "e": 3281, "s": 3279, "text": "G" }, { "code": null, "e": 3310, "s": 3281, "text": "Uses the shorter of %E or %f" }, { "code": null, "e": 3312, "s": 3310, "text": "o" }, { "code": null, "e": 3325, "s": 3312, "text": "Signed octal" }, { "code": null, "e": 3327, "s": 3325, "text": "s" }, { "code": null, "e": 3348, "s": 3327, "text": "String of characters" }, { "code": null, "e": 3350, "s": 3348, "text": "u" }, { "code": null, "e": 3375, "s": 3350, "text": "Unsigned decimal integer" }, { "code": null, "e": 3377, "s": 3375, "text": "x" }, { "code": null, "e": 3406, "s": 3377, "text": "Unsigned hexadecimal integer" }, { "code": null, "e": 3408, "s": 3406, "text": "X" }, { "code": null, "e": 3455, "s": 3408, "text": "Unsigned hexadecimal integer (capital letters)" }, { "code": null, "e": 3457, "s": 3455, "text": "p" }, { "code": null, "e": 3473, "s": 3457, "text": "Pointer address" }, { "code": null, "e": 3475, "s": 3473, "text": "n" }, { "code": null, "e": 3491, "s": 3475, "text": "Nothing printed" }, { "code": null, "e": 3493, "s": 3491, "text": "%" }, { "code": null, "e": 3503, "s": 3493, "text": "Character" }, { "code": null, "e": 3505, "s": 3503, "text": "-" }, { "code": null, "e": 3610, "s": 3505, "text": "Left-justify within the given field width; Right justification is the default (see width sub-specifier)." }, { "code": null, "e": 3612, "s": 3610, "text": "+" }, { "code": null, "e": 3767, "s": 3612, "text": "Forces to precede the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a -ve sign." }, { "code": null, "e": 3775, "s": 3767, "text": "(space)" }, { "code": null, "e": 3854, "s": 3775, "text": "If no sign is going to be written, a blank space is inserted before the value." }, { "code": null, "e": 3856, "s": 3854, "text": "#" }, { "code": null, "e": 4234, "s": 3856, "text": "Used with o, x or X specifiers the value is preceded with 0, 0x or 0X respectively for values different than zero. Used with e, E and f, it forces the written output to contain a decimal point even if no digits would follow. By default, if no digits follow, no decimal point is written. Used with g or G the result is the same as with e or E but trailing zeros are not removed." }, { "code": null, "e": 4236, "s": 4234, "text": "0" }, { "code": null, "e": 4346, "s": 4236, "text": "Left-pads the number with zeroes (0) instead of spaces, where padding is specified (see width sub-specifier)." }, { "code": null, "e": 4355, "s": 4346, "text": "(number)" }, { "code": null, "e": 4552, "s": 4355, "text": "Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger." }, { "code": null, "e": 4554, "s": 4552, "text": "*" }, { "code": null, "e": 4696, "s": 4554, "text": "The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted." }, { "code": null, "e": 4704, "s": 4696, "text": ".number" }, { "code": null, "e": 5533, "s": 4704, "text": "For integer specifiers (d, i, o, u, x, X) − precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For e, E and f specifiers − this is the number of digits to be printed after the decimal point. For g and G specifiers − This is the maximum number of significant digits to be printed. For s − this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. For c type − it has no effect. When no precision is specified, the default is 1. If the period is specified without an explicit value for precision, 0 is assumed." }, { "code": null, "e": 5536, "s": 5533, "text": ".*" }, { "code": null, "e": 5682, "s": 5536, "text": "The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted." }, { "code": null, "e": 5684, "s": 5682, "text": "h" }, { "code": null, "e": 5808, "s": 5684, "text": "The argument is interpreted as a short int or unsigned short int (only applies to integer specifiers: i, d, o, u, x and X)." }, { "code": null, "e": 5810, "s": 5808, "text": "l" }, { "code": null, "e": 5992, "s": 5810, "text": "The argument is interpreted as a long int or unsigned long int for integer specifiers (i, d, o, u, x and X), and as a wide character or wide character string for specifiers c and s." }, { "code": null, "e": 5994, "s": 5992, "text": "L" }, { "code": null, "e": 6103, "s": 5994, "text": "The argument is interpreted as a long double (only applies to floating point specifiers − e, E, f, g and G)." }, { "code": null, "e": 6421, "s": 6103, "text": "additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter (if any). There should be the same number of these arguments as the number of %-tags that expect a value." }, { "code": null, "e": 6739, "s": 6421, "text": "additional arguments − Depending on the format string, the function may expect a sequence of additional arguments, each containing one value to be inserted instead of each %-tag specified in the format parameter (if any). There should be the same number of these arguments as the number of %-tags that expect a value." }, { "code": null, "e": 6929, "s": 6739, "text": "If successful, the total number of characters written is returned excluding the null-character appended at the end of the string, otherwise a negative number is returned in case of failure." }, { "code": null, "e": 6990, "s": 6929, "text": "The following example shows the usage of sprintf() function." }, { "code": null, "e": 7137, "s": 6990, "text": "#include <stdio.h>\n#include <math.h>\n\nint main () {\n char str[80];\n\n sprintf(str, \"Value of Pi = %f\", M_PI);\n puts(str);\n \n return(0);\n}" }, { "code": null, "e": 7220, "s": 7137, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 7244, "s": 7220, "text": "Value of Pi = 3.141593\n" }, { "code": null, "e": 7277, "s": 7244, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 7292, "s": 7277, "text": " Nishant Malik" }, { "code": null, "e": 7327, "s": 7292, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 7342, "s": 7327, "text": " Nishant Malik" }, { "code": null, "e": 7377, "s": 7342, "text": "\n 48 Lectures \n 6.5 hours \n" }, { "code": null, "e": 7391, "s": 7377, "text": " Asif Hussain" }, { "code": null, "e": 7424, "s": 7391, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 7442, "s": 7424, "text": " Richa Maheshwari" }, { "code": null, "e": 7477, "s": 7442, "text": "\n 20 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7496, "s": 7477, "text": " Vandana Annavaram" }, { "code": null, "e": 7529, "s": 7496, "text": "\n 44 Lectures \n 1 hours \n" }, { "code": null, "e": 7541, "s": 7529, "text": " Amit Diwan" }, { "code": null, "e": 7548, "s": 7541, "text": " Print" }, { "code": null, "e": 7559, "s": 7548, "text": " Add Notes" } ]
OpenShift - Administration
In this chapter, we will cover topics such as how to manage a node, configure a service account, etc. In OpenShift, we need to use the start command along with OC to boot up a new server. While launching a new master, we need to use the master along with the start command, whereas while starting the new node we need to use the node along with the start command. In order to do this, we need to create configuration files for the master as well as for the nodes. We can create a basic configuration file for the master and the node using the following command. $ openshift start master --write-config = /openshift.local.config/master $ oadm create-node-config --node-dir = /openshift.local.config/node-<node_hostname> --node = <node_hostname> --hostnames = <hostname>,<ip_address> Once we run the following commands, we will get the base configuration files that can be used as the starting point for configuration. Later, we can have the same file to boot the new servers. apiLevels: - v1beta3 - v1 apiVersion: v1 assetConfig: logoutURL: "" masterPublicURL: https://172.10.12.1:7449 publicURL: https://172.10.2.2:7449/console/ servingInfo: bindAddress: 0.0.0.0:7449 certFile: master.server.crt clientCA: "" keyFile: master.server.key maxRequestsInFlight: 0 requestTimeoutSeconds: 0 controllers: '*' corsAllowedOrigins: - 172.10.2.2:7449 - 127.0.0.1 - localhost dnsConfig: bindAddress: 0.0.0.0:53 etcdClientInfo: ca: ca.crt certFile: master.etcd-client.crt keyFile: master.etcd-client.key urls: - https://10.0.2.15:4001 etcdConfig: address: 10.0.2.15:4001 peerAddress: 10.0.2.15:7001 peerServingInfo: bindAddress: 0.0.0.0:7001 certFile: etcd.server.crt clientCA: ca.crt keyFile: etcd.server.key servingInfo: bindAddress: 0.0.0.0:4001 certFile: etcd.server.crt clientCA: ca.crt keyFile: etcd.server.key storageDirectory: /root/openshift.local.etcd etcdStorageConfig: kubernetesStoragePrefix: kubernetes.io kubernetesStorageVersion: v1 openShiftStoragePrefix: openshift.io openShiftStorageVersion: v1 imageConfig: format: openshift/origin-${component}:${version} latest: false kind: MasterConfig kubeletClientInfo: ca: ca.crt certFile: master.kubelet-client.crt keyFile: master.kubelet-client.key port: 10250 kubernetesMasterConfig: apiLevels: - v1beta3 - v1 apiServerArguments: null controllerArguments: null masterCount: 1 masterIP: 10.0.2.15 podEvictionTimeout: 5m schedulerConfigFile: "" servicesNodePortRange: 30000-32767 servicesSubnet: 172.30.0.0/16 staticNodeNames: [] masterClients: externalKubernetesKubeConfig: "" openshiftLoopbackKubeConfig: openshift-master.kubeconfig masterPublicURL: https://172.10.2.2:7449 networkConfig: clusterNetworkCIDR: 10.1.0.0/16 hostSubnetLength: 8 networkPluginName: "" serviceNetworkCIDR: 172.30.0.0/16 oauthConfig: assetPublicURL: https://172.10.2.2:7449/console/ grantConfig: method: auto identityProviders: - challenge: true login: true name: anypassword provider: apiVersion: v1 kind: AllowAllPasswordIdentityProvider masterPublicURL: https://172.10.2.2:7449/ masterURL: https://172.10.2.2:7449/ sessionConfig: sessionMaxAgeSeconds: 300 sessionName: ssn sessionSecretsFile: "" tokenConfig: accessTokenMaxAgeSeconds: 86400 authorizeTokenMaxAgeSeconds: 300 policyConfig: bootstrapPolicyFile: policy.json openshiftInfrastructureNamespace: openshift-infra openshiftSharedResourcesNamespace: openshift projectConfig: defaultNodeSelector: "" projectRequestMessage: "" projectRequestTemplate: "" securityAllocator: mcsAllocatorRange: s0:/2 mcsLabelsPerProject: 5 uidAllocatorRange: 1000000000-1999999999/10000 routingConfig: subdomain: router.default.svc.cluster.local serviceAccountConfig: managedNames: - default - builder - deployer masterCA: ca.crt privateKeyFile: serviceaccounts.private.key privateKeyFile: serviceaccounts.private.key publicKeyFiles: - serviceaccounts.public.key servingInfo: bindAddress: 0.0.0.0:8443 certFile: master.server.crt clientCA: ca.crt keyFile: master.server.key maxRequestsInFlight: 0 requestTimeoutSeconds: 3600 allowDisabledDocker: true apiVersion: v1 dnsDomain: cluster.local dnsIP: 172.10.2.2 dockerConfig: execHandlerName: native imageConfig: format: openshift/origin-${component}:${version} latest: false kind: NodeConfig masterKubeConfig: node.kubeconfig networkConfig: mtu: 1450 networkPluginName: "" nodeIP: "" nodeName: node1.example.com podManifestConfig: path: "/path/to/pod-manifest-file" fileCheckIntervalSeconds: 30 servingInfo: bindAddress: 0.0.0.0:10250 certFile: server.crt clientCA: node-client-ca.crt keyFile: server.key volumeDirectory: /root/openshift.local.volumes This is how the node configuration files look like. Once we have these configuration files in place, we can run the following command to create master and node server. $ openshift start --master-config = /openshift.local.config/master/master- config.yaml --node-config = /openshift.local.config/node-<node_hostname>/node- config.yaml In OpenShift, we have OC command line utility which is mostly used for carrying out all the operations in OpenShift. We can use the following commands to manage the nodes. $ oc get nodes NAME LABELS node1.example.com kubernetes.io/hostname = vklnld1446.int.example.com node2.example.com kubernetes.io/hostname = vklnld1447.int.example.com $ oc describe node <node name> $ oc delete node <node name> $ oadm manage-node <node1> <node2> --list-pods [--pod-selector=<pod_selector>] [-o json|yaml] $ oadm manage-node <node1> <node2> --evacuate --dry-run [--pod-selector=<pod_selector>] In OpenShift master, there is a built-in OAuth server, which can be used for managing authentication. All OpenShift users get the token from this server, which helps them communicate to OpenShift API. There are different kinds of authentication level in OpenShift, which can be configured along with the main configuration file. Allow all Deny all HTPasswd LDAP Basic authentication Request header While defining the master configuration, we can define the identification policy where we can define the type of policy that we wish to use. Allow All oauthConfig: ... identityProviders: - name: Allow_Authontication challenge: true login: true provider: apiVersion: v1 kind: AllowAllPasswordIdentityProvider This will deny access to all usernames and passwords. oauthConfig: ... identityProviders: - name: deny_Authontication challenge: true login: true provider: apiVersion: v1 kind: DenyAllPasswordIdentityProvider HTPasswd is used to validate the username and password against an encrypted file password. For generating an encrypted file, following is the command. $ htpasswd </path/to/users.htpasswd> <user_name> Using the encrypted file. oauthConfig: ... identityProviders: - name: htpasswd_authontication challenge: true login: true provider: apiVersion: v1 kind: HTPasswdPasswordIdentityProvider file: /path/to/users.htpasswd This is used for LDAP authentication wherein LDAP server plays a key role in authentication. oauthConfig: ... identityProviders: - name: "ldap_authontication" challenge: true login: true provider: apiVersion: v1 kind: LDAPPasswordIdentityProvider attributes: id: - dn email: - mail name: - cn preferredUsername: - uid bindDN: "" bindPassword: "" ca: my-ldap-ca-bundle.crt insecure: false url: "ldap://ldap.example.com/ou=users,dc=acme,dc=com?uid" This is used when the validation of username and password is done against a server-to-server authentication. The authentication is protected in the base URL and is presented in JSON format. oauthConfig: ... identityProviders: - name: my_remote_basic_auth_provider challenge: true login: true provider: apiVersion: v1 kind: BasicAuthPasswordIdentityProvider url: https://www.vklnld908.int.example.com/remote-idp ca: /path/to/ca.file certFile: /path/to/client.crt keyFile: /path/to/client.key Service accounts provide a flexible way of accessing OpenShift API exposing the username and password for authentication. Service account uses a key pair of public and private key for authentication. Authentication to API is done using a private key and validating it against a public key. ServiceAccountConfig: ... masterCA: ca.crt privateKeyFile: serviceaccounts.private.key publicKeyFiles: - serviceaccounts.public.key - ... Use the following command to create a service account $ Openshift cli create service account <name of server account> In most of the production environment, direct access to Internet is restricted. They are either not exposed to Internet or they are exposed via a HTTP or HTTPS proxy. In an OpenShift environment, this proxy machine definition is set as an environment variable. This can be done by adding a proxy definition on the master and node files located under /etc/sysconfig. This is similar as we do for any other application. /etc/sysconfig/openshift-master HTTP_PROXY=http://USERNAME:[email protected]:8080/ HTTPS_PROXY=https://USERNAME:[email protected]:8080/ NO_PROXY=master.vklnld908.int.example.com /etc/sysconfig/openshift-node HTTP_PROXY=http://USERNAME:[email protected]:8080/ HTTPS_PROXY=https://USERNAME:[email protected]:8080/ NO_PROXY=master.vklnld908.int.example.com Once done, we need to restart the master and node machines. /etc/sysconfig/docker HTTP_PROXY = http://USERNAME:[email protected]:8080/ HTTPS_PROXY = https://USERNAME:[email protected]:8080/ NO_PROXY = master.vklnld1446.int.example.com In order to make a pod run in a proxy environment, it can be done using − containers: - env: - name: "HTTP_PROXY" value: "http://USER:PASSWORD@:10.0.1.1:8080" OC environment command can be used to update the existing env. In OpenShift, the concept of persistent volume and persistent volume claims forms persistent storage. This is one of the key concepts in which first persistent volume is created and later that same volume is claimed. For this, we need to have enough capacity and disk space on the underlying hardware. apiVersion: v1 kind: PersistentVolume metadata: name: storage-unit1 spec: capacity: storage: 10Gi accessModes: - ReadWriteOnce nfs: path: /opt server: 10.12.2.2 persistentVolumeReclaimPolicy: Recycle Next, using OC create command create Persistent Volume. $ oc create -f storage-unit1.yaml persistentvolume " storage-unit1 " created Claiming the created volume. apiVersion: v1 kind: PersistentVolumeClaim metadata: name: Storage-clame1 spec: accessModes: - ReadWriteOnce resources: requests: storage: 5Gi Create the claim. $ oc create -f Storage-claim1.yaml persistentvolume " Storage-clame1 " created User and role administration is used to manage users, their access and controls on different projects. Predefined templates can be used to create new users in OpenShift. kind: "Template" apiVersion: "v1" parameters: - name: vipin required: true objects: - kind: "User" apiVersion: "v1" metadata: name: "${email}" - kind: "Identity" apiVersion: "v1" metadata: name: "vipin:${email}" providerName: "SAML" providerUserName: "${email}" - kind: "UserIdentityMapping" apiVersion: "v1" identity: name: "vipin:${email}" user: name: "${email}" Use oc create –f <file name> to create users. $ oc create –f vipin.yaml Use the following command to delete a user in OpenShift. $ oc delete user <user name> ResourceQuotas and LimitRanges are used for limiting user access levels. They are used for limiting the pods and containers on the cluster. apiVersion: v1 kind: ResourceQuota metadata: name: resources-utilization spec: hard: pods: "10" $ oc create -f resource-quota.yaml –n –Openshift-sample $ oc describe quota resource-quota -n Openshift-sample Name: resource-quota Namespace: Openshift-sample Resource Used Hard -------- ---- ---- pods 3 10 Defining the container limits can be used for limiting the resources which are going to be used by deployed containers. They are used to define the maximum and minimum limitations of certain objects. This is basically used for the number of projects a user can have at any point of time. They are basically done by defining the user levels in categories of bronze, silver, and gold. We need to first define an object which holds the value of how many projects a bronze, silver, and gold category can have. These need to be done in the master-confif.yaml file. admissionConfig: pluginConfig: ProjectRequestLimit: configuration: apiVersion: v1 kind: ProjectRequestLimitConfig limits: - selector: level: platinum - selector: level: gold maxProjects: 15 - selector: level: silver maxProjects: 10 - selector: level: bronze maxProjects: 5 Restart the master server. Assigning a user to a particular level. $ oc label user vipin level = gold Moving the user out of the label, if required. $ oc label user <user_name> level- Adding roles to a user. $ oadm policy add-role-to-user <user_name> Removing the role from a user. $ oadm policy remove-role-from-user <user_name> Adding a cluster role to a user. $ oadm policy add-cluster-role-to-user <user_name> Removing a cluster role from a user. $ oadm policy remove-cluster-role-from-user <user_name> Adding a role to a group. $ oadm policy add-role-to-user <user_name> Removing a role from a group. $ oadm policy remove-cluster-role-from-user <user_name> Adding a cluster role to a group. $ oadm policy add-cluster-role-to-group <groupname> Removing a cluster role from a group. $ oadm policy remove-cluster-role-from-group <role> <groupname> This is one of the most powerful roles where the user has the capability to manage a complete cluster starting from creation till deletion of a cluster. $ oadm policy add-role-to-user admin <user_name> -n <project_name> $ oadm policy add-cluster-role-to-user cluster-admin <user_name> 70 Lectures 4 hours Cloud Passion 19 Lectures 1 hours Pranjal Srivastava 26 Lectures 1.5 hours Pranjal Srivastava Print Add Notes Bookmark this page
[ { "code": null, "e": 2050, "s": 1948, "text": "In this chapter, we will cover topics such as how to manage a node, configure a service account, etc." }, { "code": null, "e": 2510, "s": 2050, "text": "In OpenShift, we need to use the start command along with OC to boot up a new server. While launching a new master, we need to use the master along with the start command, whereas while starting the new node we need to use the node along with the start command. In order to do this, we need to create configuration files for the master as well as for the nodes. We can create a basic configuration file for the master and the node using the following command." }, { "code": null, "e": 2584, "s": 2510, "text": "$ openshift start master --write-config = /openshift.local.config/master\n" }, { "code": null, "e": 2732, "s": 2584, "text": "$ oadm create-node-config --node-dir = /openshift.local.config/node-<node_hostname> --node = <node_hostname> --hostnames = <hostname>,<ip_address>\n" }, { "code": null, "e": 2925, "s": 2732, "text": "Once we run the following commands, we will get the base configuration files that can be used as the starting point for configuration. Later, we can have the same file to boot the new servers." }, { "code": null, "e": 6320, "s": 2925, "text": "apiLevels:\n- v1beta3\n- v1\napiVersion: v1\nassetConfig:\n logoutURL: \"\"\n masterPublicURL: https://172.10.12.1:7449\n publicURL: https://172.10.2.2:7449/console/\n servingInfo:\n bindAddress: 0.0.0.0:7449\n certFile: master.server.crt\n clientCA: \"\"\nkeyFile: master.server.key\n maxRequestsInFlight: 0\n requestTimeoutSeconds: 0\ncontrollers: '*'\ncorsAllowedOrigins:\n- 172.10.2.2:7449\n- 127.0.0.1\n- localhost\ndnsConfig:\n bindAddress: 0.0.0.0:53\netcdClientInfo:\n ca: ca.crt\n certFile: master.etcd-client.crt\n keyFile: master.etcd-client.key\n urls:\n - https://10.0.2.15:4001\netcdConfig:\n address: 10.0.2.15:4001\n peerAddress: 10.0.2.15:7001\n peerServingInfo:\n bindAddress: 0.0.0.0:7001\n certFile: etcd.server.crt\n clientCA: ca.crt\n keyFile: etcd.server.key\n servingInfo:\n bindAddress: 0.0.0.0:4001\n certFile: etcd.server.crt\n clientCA: ca.crt\n keyFile: etcd.server.key\n storageDirectory: /root/openshift.local.etcd\netcdStorageConfig:\n kubernetesStoragePrefix: kubernetes.io\n kubernetesStorageVersion: v1\n openShiftStoragePrefix: openshift.io\n openShiftStorageVersion: v1\nimageConfig:\n format: openshift/origin-${component}:${version}\n latest: false\nkind: MasterConfig\nkubeletClientInfo:\n ca: ca.crt\n certFile: master.kubelet-client.crt\n keyFile: master.kubelet-client.key\n port: 10250\nkubernetesMasterConfig:\n apiLevels:\n - v1beta3\n - v1\n apiServerArguments: null\n controllerArguments: null\n masterCount: 1\n masterIP: 10.0.2.15\n podEvictionTimeout: 5m\n schedulerConfigFile: \"\"\n servicesNodePortRange: 30000-32767\n servicesSubnet: 172.30.0.0/16\n staticNodeNames: []\nmasterClients:\n externalKubernetesKubeConfig: \"\"\n openshiftLoopbackKubeConfig: openshift-master.kubeconfig\nmasterPublicURL: https://172.10.2.2:7449\nnetworkConfig:\n clusterNetworkCIDR: 10.1.0.0/16\n hostSubnetLength: 8\n networkPluginName: \"\"\n serviceNetworkCIDR: 172.30.0.0/16\noauthConfig:\n assetPublicURL: https://172.10.2.2:7449/console/\n grantConfig:\n method: auto\n identityProviders:\n - challenge: true\n login: true\n name: anypassword\n provider:\n apiVersion: v1\n kind: AllowAllPasswordIdentityProvider\n masterPublicURL: https://172.10.2.2:7449/\n masterURL: https://172.10.2.2:7449/\n sessionConfig:\n sessionMaxAgeSeconds: 300\n sessionName: ssn\n sessionSecretsFile: \"\"\n tokenConfig:\n accessTokenMaxAgeSeconds: 86400\n authorizeTokenMaxAgeSeconds: 300\npolicyConfig:\n bootstrapPolicyFile: policy.json\n openshiftInfrastructureNamespace: openshift-infra\n openshiftSharedResourcesNamespace: openshift\nprojectConfig:\n defaultNodeSelector: \"\"\n projectRequestMessage: \"\"\n projectRequestTemplate: \"\"\n securityAllocator:\n mcsAllocatorRange: s0:/2\n mcsLabelsPerProject: 5\n uidAllocatorRange: 1000000000-1999999999/10000\nroutingConfig:\n subdomain: router.default.svc.cluster.local\nserviceAccountConfig:\n managedNames:\n - default\n - builder\n - deployer\n \nmasterCA: ca.crt\n privateKeyFile: serviceaccounts.private.key\n privateKeyFile: serviceaccounts.private.key\n publicKeyFiles:\n - serviceaccounts.public.key\nservingInfo:\n bindAddress: 0.0.0.0:8443\n certFile: master.server.crt\n clientCA: ca.crt\n keyFile: master.server.key\n maxRequestsInFlight: 0\n requestTimeoutSeconds: 3600\n" }, { "code": null, "e": 6930, "s": 6320, "text": "allowDisabledDocker: true\napiVersion: v1\ndnsDomain: cluster.local\ndnsIP: 172.10.2.2\ndockerConfig:\n execHandlerName: native\nimageConfig:\n format: openshift/origin-${component}:${version}\n latest: false\nkind: NodeConfig\nmasterKubeConfig: node.kubeconfig\nnetworkConfig:\n mtu: 1450\n networkPluginName: \"\"\nnodeIP: \"\"\nnodeName: node1.example.com\n\npodManifestConfig:\n path: \"/path/to/pod-manifest-file\"\n fileCheckIntervalSeconds: 30\nservingInfo:\n bindAddress: 0.0.0.0:10250\n certFile: server.crt\n clientCA: node-client-ca.crt\n keyFile: server.key\nvolumeDirectory: /root/openshift.local.volumes\n" }, { "code": null, "e": 7098, "s": 6930, "text": "This is how the node configuration files look like. Once we have these configuration files in place, we can run the following command to create master and node server." }, { "code": null, "e": 7265, "s": 7098, "text": "$ openshift start --master-config = /openshift.local.config/master/master-\nconfig.yaml --node-config = /openshift.local.config/node-<node_hostname>/node-\nconfig.yaml\n" }, { "code": null, "e": 7437, "s": 7265, "text": "In OpenShift, we have OC command line utility which is mostly used for carrying out all the operations in OpenShift. We can use the following commands to manage the nodes." }, { "code": null, "e": 7641, "s": 7437, "text": "$ oc get nodes\nNAME LABELS\nnode1.example.com kubernetes.io/hostname = vklnld1446.int.example.com\nnode2.example.com kubernetes.io/hostname = vklnld1447.int.example.com\n" }, { "code": null, "e": 7673, "s": 7641, "text": "$ oc describe node <node name>\n" }, { "code": null, "e": 7703, "s": 7673, "text": "$ oc delete node <node name>\n" }, { "code": null, "e": 7798, "s": 7703, "text": "$ oadm manage-node <node1> <node2> --list-pods [--pod-selector=<pod_selector>] [-o json|yaml]\n" }, { "code": null, "e": 7887, "s": 7798, "text": "$ oadm manage-node <node1> <node2> --evacuate --dry-run [--pod-selector=<pod_selector>]\n" }, { "code": null, "e": 8088, "s": 7887, "text": "In OpenShift master, there is a built-in OAuth server, which can be used for managing authentication. All OpenShift users get the token from this server, which helps them communicate to OpenShift API." }, { "code": null, "e": 8216, "s": 8088, "text": "There are different kinds of authentication level in OpenShift, which can be configured along with the main configuration file." }, { "code": null, "e": 8226, "s": 8216, "text": "Allow all" }, { "code": null, "e": 8235, "s": 8226, "text": "Deny all" }, { "code": null, "e": 8244, "s": 8235, "text": "HTPasswd" }, { "code": null, "e": 8249, "s": 8244, "text": "LDAP" }, { "code": null, "e": 8270, "s": 8249, "text": "Basic authentication" }, { "code": null, "e": 8285, "s": 8270, "text": "Request header" }, { "code": null, "e": 8426, "s": 8285, "text": "While defining the master configuration, we can define the identification policy where we can define the type of policy that we wish to use." }, { "code": null, "e": 8436, "s": 8426, "text": "Allow All" }, { "code": null, "e": 8639, "s": 8436, "text": "oauthConfig:\n ...\n identityProviders:\n - name: Allow_Authontication\n challenge: true\n login: true\n provider:\n apiVersion: v1\n kind: AllowAllPasswordIdentityProvider\n" }, { "code": null, "e": 8693, "s": 8639, "text": "This will deny access to all usernames and passwords." }, { "code": null, "e": 8894, "s": 8693, "text": "oauthConfig:\n ...\n identityProviders:\n - name: deny_Authontication\n challenge: true\n login: true\n provider:\n apiVersion: v1\n kind: DenyAllPasswordIdentityProvider\n" }, { "code": null, "e": 8985, "s": 8894, "text": "HTPasswd is used to validate the username and password against an encrypted file password." }, { "code": null, "e": 9045, "s": 8985, "text": "For generating an encrypted file, following is the command." }, { "code": null, "e": 9095, "s": 9045, "text": "$ htpasswd </path/to/users.htpasswd> <user_name>\n" }, { "code": null, "e": 9121, "s": 9095, "text": "Using the encrypted file." }, { "code": null, "e": 9366, "s": 9121, "text": "oauthConfig:\n ...\n identityProviders:\n - name: htpasswd_authontication\n challenge: true\n login: true\n provider:\n apiVersion: v1\n kind: HTPasswdPasswordIdentityProvider\n file: /path/to/users.htpasswd\n" }, { "code": null, "e": 9459, "s": 9366, "text": "This is used for LDAP authentication wherein LDAP server plays a key role in authentication." }, { "code": null, "e": 10009, "s": 9459, "text": "oauthConfig:\n ...\n identityProviders:\n - name: \"ldap_authontication\"\n challenge: true\n login: true\n provider:\n apiVersion: v1\n kind: LDAPPasswordIdentityProvider\n attributes:\n id:\n - dn\n email:\n - mail\n name:\n - cn\n preferredUsername:\n - uid\n bindDN: \"\"\n bindPassword: \"\"\n ca: my-ldap-ca-bundle.crt\n insecure: false\n url: \"ldap://ldap.example.com/ou=users,dc=acme,dc=com?uid\"\n" }, { "code": null, "e": 10199, "s": 10009, "text": "This is used when the validation of username and password is done against a server-to-server authentication. The authentication is protected in the base URL and is presented in JSON format." }, { "code": null, "e": 10582, "s": 10199, "text": "oauthConfig:\n ...\n identityProviders:\n - name: my_remote_basic_auth_provider\n challenge: true\n login: true\n provider:\n apiVersion: v1\n kind: BasicAuthPasswordIdentityProvider\n url: https://www.vklnld908.int.example.com/remote-idp\n ca: /path/to/ca.file\n certFile: /path/to/client.crt\n keyFile: /path/to/client.key\n" }, { "code": null, "e": 10704, "s": 10582, "text": "Service accounts provide a flexible way of accessing OpenShift API exposing the username and password for authentication." }, { "code": null, "e": 10872, "s": 10704, "text": "Service account uses a key pair of public and private key for authentication. Authentication to API is done using a private key and validating it against a public key." }, { "code": null, "e": 11029, "s": 10872, "text": "ServiceAccountConfig:\n ...\n masterCA: ca.crt\n privateKeyFile: serviceaccounts.private.key\n publicKeyFiles:\n - serviceaccounts.public.key\n - ...\n" }, { "code": null, "e": 11083, "s": 11029, "text": "Use the following command to create a service account" }, { "code": null, "e": 11148, "s": 11083, "text": "$ Openshift cli create service account <name of server account>\n" }, { "code": null, "e": 11409, "s": 11148, "text": "In most of the production environment, direct access to Internet is restricted. They are either not exposed to Internet or they are exposed via a HTTP or HTTPS proxy. In an OpenShift environment, this proxy machine definition is set as an environment variable." }, { "code": null, "e": 11566, "s": 11409, "text": "This can be done by adding a proxy definition on the master and node files located under /etc/sysconfig. This is similar as we do for any other application." }, { "code": null, "e": 11598, "s": 11566, "text": "/etc/sysconfig/openshift-master" }, { "code": null, "e": 11751, "s": 11598, "text": "HTTP_PROXY=http://USERNAME:[email protected]:8080/\nHTTPS_PROXY=https://USERNAME:[email protected]:8080/\nNO_PROXY=master.vklnld908.int.example.com\n" }, { "code": null, "e": 11781, "s": 11751, "text": "/etc/sysconfig/openshift-node" }, { "code": null, "e": 11934, "s": 11781, "text": "HTTP_PROXY=http://USERNAME:[email protected]:8080/\nHTTPS_PROXY=https://USERNAME:[email protected]:8080/\nNO_PROXY=master.vklnld908.int.example.com\n" }, { "code": null, "e": 11994, "s": 11934, "text": "Once done, we need to restart the master and node machines." }, { "code": null, "e": 12016, "s": 11994, "text": "/etc/sysconfig/docker" }, { "code": null, "e": 12176, "s": 12016, "text": "HTTP_PROXY = http://USERNAME:[email protected]:8080/\nHTTPS_PROXY = https://USERNAME:[email protected]:8080/\nNO_PROXY = master.vklnld1446.int.example.com\n" }, { "code": null, "e": 12250, "s": 12176, "text": "In order to make a pod run in a proxy environment, it can be done using −" }, { "code": null, "e": 12345, "s": 12250, "text": "containers:\n- env:\n - name: \"HTTP_PROXY\"\n value: \"http://USER:PASSWORD@:10.0.1.1:8080\"\n" }, { "code": null, "e": 12408, "s": 12345, "text": "OC environment command can be used to update the existing env." }, { "code": null, "e": 12710, "s": 12408, "text": "In OpenShift, the concept of persistent volume and persistent volume claims forms persistent storage. This is one of the key concepts in which first persistent volume is created and later that same volume is claimed. For this, we need to have enough capacity and disk space on the underlying hardware." }, { "code": null, "e": 12947, "s": 12710, "text": "apiVersion: v1\nkind: PersistentVolume\nmetadata:\n name: storage-unit1\nspec:\n capacity:\n storage: 10Gi\n accessModes:\n - ReadWriteOnce\n nfs:\n path: /opt\n server: 10.12.2.2\n persistentVolumeReclaimPolicy: Recycle\n" }, { "code": null, "e": 13003, "s": 12947, "text": "Next, using OC create command create Persistent Volume." }, { "code": null, "e": 13082, "s": 13003, "text": "$ oc create -f storage-unit1.yaml\n\npersistentvolume \" storage-unit1 \" created\n" }, { "code": null, "e": 13111, "s": 13082, "text": "Claiming the created volume." }, { "code": null, "e": 13285, "s": 13111, "text": "apiVersion: v1\nkind: PersistentVolumeClaim\nmetadata:\n name: Storage-clame1\nspec:\n accessModes:\n - ReadWriteOnce\n resources:\n requests:\n storage: 5Gi\n" }, { "code": null, "e": 13303, "s": 13285, "text": "Create the claim." }, { "code": null, "e": 13383, "s": 13303, "text": "$ oc create -f Storage-claim1.yaml\npersistentvolume \" Storage-clame1 \" created\n" }, { "code": null, "e": 13486, "s": 13383, "text": "User and role administration is used to manage users, their access and controls on different projects." }, { "code": null, "e": 13553, "s": 13486, "text": "Predefined templates can be used to create new users in OpenShift." }, { "code": null, "e": 13965, "s": 13553, "text": "kind: \"Template\"\napiVersion: \"v1\"\nparameters:\n - name: vipin\n required: true\nobjects:\n - kind: \"User\"\n apiVersion: \"v1\"\n metadata:\n name: \"${email}\"\n \n- kind: \"Identity\"\n apiVersion: \"v1\"\n metadata:\n name: \"vipin:${email}\"\n providerName: \"SAML\"\n providerUserName: \"${email}\"\n- kind: \"UserIdentityMapping\"\napiVersion: \"v1\"\nidentity:\n name: \"vipin:${email}\"\nuser:\n name: \"${email}\"\n" }, { "code": null, "e": 14011, "s": 13965, "text": "Use oc create –f <file name> to create users." }, { "code": null, "e": 14038, "s": 14011, "text": "$ oc create –f vipin.yaml\n" }, { "code": null, "e": 14095, "s": 14038, "text": "Use the following command to delete a user in OpenShift." }, { "code": null, "e": 14125, "s": 14095, "text": "$ oc delete user <user name>\n" }, { "code": null, "e": 14265, "s": 14125, "text": "ResourceQuotas and LimitRanges are used for limiting user access levels. They are used for limiting the pods and containers on the cluster." }, { "code": null, "e": 14374, "s": 14265, "text": "apiVersion: v1\nkind: ResourceQuota\nmetadata:\n name: resources-utilization\nspec:\n hard:\n pods: \"10\"\n" }, { "code": null, "e": 14431, "s": 14374, "text": "$ oc create -f resource-quota.yaml –n –Openshift-sample\n" }, { "code": null, "e": 14716, "s": 14431, "text": "$ oc describe quota resource-quota -n Openshift-sample\nName: resource-quota\nNamespace: Openshift-sample\nResource Used Hard\n-------- ---- ----\npods 3 10\n" }, { "code": null, "e": 14916, "s": 14716, "text": "Defining the container limits can be used for limiting the resources which are going to be used by deployed containers. They are used to define the maximum and minimum limitations of certain objects." }, { "code": null, "e": 15099, "s": 14916, "text": "This is basically used for the number of projects a user can have at any point of time. They are basically done by defining the user levels in categories of bronze, silver, and gold." }, { "code": null, "e": 15276, "s": 15099, "text": "We need to first define an object which holds the value of how many projects a bronze, silver, and gold category can have. These need to be done in the master-confif.yaml file." }, { "code": null, "e": 15748, "s": 15276, "text": "admissionConfig:\n pluginConfig:\n ProjectRequestLimit:\n configuration:\n apiVersion: v1\n kind: ProjectRequestLimitConfig\n limits:\n - selector:\n level: platinum\n - selector:\n level: gold\n maxProjects: 15\n - selector:\n level: silver\n maxProjects: 10\n - selector:\n level: bronze\n maxProjects: 5\n" }, { "code": null, "e": 15775, "s": 15748, "text": "Restart the master server." }, { "code": null, "e": 15815, "s": 15775, "text": "Assigning a user to a particular level." }, { "code": null, "e": 15851, "s": 15815, "text": "$ oc label user vipin level = gold\n" }, { "code": null, "e": 15898, "s": 15851, "text": "Moving the user out of the label, if required." }, { "code": null, "e": 15934, "s": 15898, "text": "$ oc label user <user_name> level-\n" }, { "code": null, "e": 15958, "s": 15934, "text": "Adding roles to a user." }, { "code": null, "e": 16003, "s": 15958, "text": "$ oadm policy add-role-to-user <user_name>\n" }, { "code": null, "e": 16034, "s": 16003, "text": "Removing the role from a user." }, { "code": null, "e": 16084, "s": 16034, "text": "$ oadm policy remove-role-from-user <user_name>\n" }, { "code": null, "e": 16117, "s": 16084, "text": "Adding a cluster role to a user." }, { "code": null, "e": 16170, "s": 16117, "text": "$ oadm policy add-cluster-role-to-user <user_name>\n" }, { "code": null, "e": 16207, "s": 16170, "text": "Removing a cluster role from a user." }, { "code": null, "e": 16265, "s": 16207, "text": "$ oadm policy remove-cluster-role-from-user <user_name>\n" }, { "code": null, "e": 16291, "s": 16265, "text": "Adding a role to a group." }, { "code": null, "e": 16336, "s": 16291, "text": "$ oadm policy add-role-to-user <user_name>\n" }, { "code": null, "e": 16366, "s": 16336, "text": "Removing a role from a group." }, { "code": null, "e": 16424, "s": 16366, "text": "$ oadm policy remove-cluster-role-from-user <user_name>\n" }, { "code": null, "e": 16458, "s": 16424, "text": "Adding a cluster role to a group." }, { "code": null, "e": 16512, "s": 16458, "text": "$ oadm policy add-cluster-role-to-group <groupname>\n" }, { "code": null, "e": 16550, "s": 16512, "text": "Removing a cluster role from a group." }, { "code": null, "e": 16615, "s": 16550, "text": "$ oadm policy remove-cluster-role-from-group <role> <groupname>\n" }, { "code": null, "e": 16768, "s": 16615, "text": "This is one of the most powerful roles where the user has the capability to manage a complete cluster starting from creation till deletion of a cluster." }, { "code": null, "e": 16836, "s": 16768, "text": "$ oadm policy add-role-to-user admin <user_name> -n <project_name>\n" }, { "code": null, "e": 16902, "s": 16836, "text": "$ oadm policy add-cluster-role-to-user cluster-admin <user_name>\n" }, { "code": null, "e": 16935, "s": 16902, "text": "\n 70 Lectures \n 4 hours \n" }, { "code": null, "e": 16950, "s": 16935, "text": " Cloud Passion" }, { "code": null, "e": 16983, "s": 16950, "text": "\n 19 Lectures \n 1 hours \n" }, { "code": null, "e": 17003, "s": 16983, "text": " Pranjal Srivastava" }, { "code": null, "e": 17038, "s": 17003, "text": "\n 26 Lectures \n 1.5 hours \n" }, { "code": null, "e": 17058, "s": 17038, "text": " Pranjal Srivastava" }, { "code": null, "e": 17065, "s": 17058, "text": " Print" }, { "code": null, "e": 17076, "s": 17065, "text": " Add Notes" } ]
One Hot Encoding, Standardization, PCA: Data preparation for segmentation in python | by Indraneel Dutta Baruah | Towards Data Science
Data driven customer targeting or product bundling are critical for businesses to stay relevant against the intense competition they face. Consumers are now spoilt for choice and prefer personalized product offerings. With the coming of the fourth industrial revolution in the form of the immense growth of artificial intelligence and big data technologies, there is no better time to leverage segmentation models to perform such analysis. But before we do a deep dive into these models, we should be aware of what kind of data is needed for these models. This is the focus of my blog as we will be going through all the steps necessary for transforming our raw dataset to the format we need for training and testing our segmentation algorithms. The Data For this exercise, we will be working with clickstream data from an online store offering clothing for pregnant women. It has data from April 2008 to August 2008 and includes variables like product category, location of the photo on the webpage, country of origin of the IP address and product price in US dollars. The reason I chose this dataset is that clickstream data is becoming a very important source of providing fine-grained information about customer behaviour. It also provides us a dataset with typical challenges like high dimensionality, need for feature engineering, presence of categorical variables and different scales of fields. We will try to prepare the data for product segmentation by performing the following steps: Exploratory Data Analysis (EDA)Feature EngineeringOne Hot EncodingStandardisationPCA Exploratory Data Analysis (EDA) Feature Engineering One Hot Encoding Standardisation PCA Exploratory Data Analysis (EDA) We will first try to read the dataset (using read_csv function) and look at the top 5 rows (using head function): # Read dataset and look at top recordsimport pandas as pddf = pd.read_csv('e-shop clothing 2008.csv', delimiter=";")df.head(5) We have the data at a daily level for multiple clothing models (field name: “page 2 (clothing model)”). Next, let us check the number of rows and columns and their types (using the info function) #Check the number of rows and columns and their typesdf.info() We have 165474 records and 14 fields. One thing to note is that a lot of fields are numeric but should ideally be strings. Let us convert the fields as string using as.type(str) function: # Convert categorical variables to stringcat_vars = ['year', 'month', 'day', 'country', 'session ID', 'page 1 (main category)', 'page 2 (clothing model)', 'colour', 'location', 'model photography', 'price 2', 'page']df[cat_vars] = df[cat_vars].astype(str)df.info() Let us check the properties of the numeric fields next: # Check properties of numeric fieldsdf.describe() As seen in figure 4, the product price (field name: ‘price’) is on a much larger scale than sequence of clicks during one session (field name: ‘order’). This means that we will have to standardize these fields to bring them to the same scale as distance based models like K-means are affected by the scale of the fields. Feature Engineering As previously mentioned, our dataset is at a daily level and we need to aggregate the data at a product level because we want to perform product segmentation. We create the following features while aggregating at the product level: Most frequently occurring product colour, day of browsing, country, photo type (profile, en face), price type (higher or lower than category average), page number within website and location of the product’s photo on the page (using the mode function)Total number of unique session IDs (using the nununique function)Median, minimum and maximum of sequence of clicks during one session and product price (using the median, min and max function) Most frequently occurring product colour, day of browsing, country, photo type (profile, en face), price type (higher or lower than category average), page number within website and location of the product’s photo on the page (using the mode function) Total number of unique session IDs (using the nununique function) Median, minimum and maximum of sequence of clicks during one session and product price (using the median, min and max function) # Feature Engineeringfrom scipy.stats import mode df2 = df.groupby(['country','page 1 (main category)','page 2 (clothing model)']).agg( median_no_of_clicks_per_session=('order', 'median'), min_no_of_clicks_per_session=('order', 'max'), max_no_of_clicks_per_session=('order', 'min'), median_price=('price', 'median'), min_price=('price', 'max'), max_price=('price', 'min'), total_number_of_sessions =('session ID', pd.Series.nunique), most_frequent_day=('day', lambda x: mode(x)[0][0]), most_frequent_colour=('colour', lambda x: mode(x)[0][0]), most_frequent_location=('location', lambda x: mode(x)[0][0]), most_frequent_photo_type=('model photography', lambda x: mode(x)[0][0]), most_frequent_price_type =('price 2', lambda x: mode(x)[0][0]), most_frequent_page_number =('page', lambda x: mode(x)[0][0]) )df2 One Hot Encoding One hot encoding creates dummy variables which is a duplicate variable which represents one level of a categorical variable. Presence of a level is represented by 1 and absence is represented by 0. If the categorical variable is ordinal (i.e. categories of the variable have an order) then we can translate the variable to a numeric variable using the OrdinalEncoder function. In our case, the categorical variables don’t have any ordinality and hence, we use the get_dummies function to create the dummy variables. # One hot encoding - to convert categorical data to continuouscat_vars = ['most_frequent_day', 'most_frequent_colour', 'most_frequent_location', 'most_frequent_photo_type', 'most_frequent_price_type', 'most_frequent_page_number']df2[cat_vars] = df2[cat_vars].astype(str)df3 = pd.get_dummies(df2)df3.head(5) We can also use the OneHotEncoder function instead of get_dummies function if our nominal features are integers. Standardization As shown in figure 4, our numeric features have different scales. Scaling helps to compare independent features with different ranges or units after converting them to comparable values. There are two major scaling methods: Normalization is the ideal choice when we know that the distribution of data does not follow a Gaussian distribution or for algorithms that do not assume any data distribution like K-Nearest Neighbors and Neural Networks. On the other hand, standardization can be used when data follows a Gaussian distribution. But these are not strict rules and ideally we can try both and select the option which gives the best cluster validation results. We will be standardizing our numeric fields in this example using the StandardScaler function. # Standardizingfrom sklearn.preprocessing import StandardScalercon_vars = ['median_no_of_clicks_per_session', 'min_no_of_clicks_per_session', 'max_no_of_clicks_per_session', 'median_price', 'min_price', 'max_price', 'total_number_of_sessions']scaler = StandardScaler()df3[con_vars]=scaler.fit_transform(df3[con_vars])df3.head(5) Principal Component Analysis (PCA) Principal component analysis combines our current features in a specific way to create new features and then we can drop the “least important” while still retaining the most valuable parts of all of the original variables. This is a useful method when we have a lot of features to handle. It calculates the covariance matrix of all the features and then generates the eigenvectors and eigenvalues from the matrix. Then, the covariance matrix is multiplied by the eigenvectors to create principal components. These principal components are the new features based on our original features and their importance in terms of explaining the variability in the dataset is given by eigenvalues. We can keep the top ranked principal components which explain a minimum level of variance in our original dataset. We can implement PCA analysis using the pca function from sklearn.decomposition module. I have set up a loop function to identify number of principal components that explain at least 85% of the variance in the dataset. # PCAfrom sklearn.decomposition import PCA# Loop Function to identify number of principal components that explain at least 85% of the variancefor comp in range(3, df3.shape[1]): pca = PCA(n_components= comp, random_state=42) pca.fit(df3) comp_check = pca.explained_variance_ratio_ final_comp = comp if comp_check.sum() > 0.85: break Final_PCA = PCA(n_components= final_comp,random_state=42)Final_PCA.fit(df3)cluster_df=Final_PCA.transform(df3)num_comps = comp_check.shape[0]print("Using {} components, we can explain {}% of the variability in the original data.".format(final_comp,comp_check.sum())) As seen in figure 8, 15 components are able to explain 85% of the variance in our dataset. We can now use these features in our unsupervised models like K means, DBSCAN, hierarchical clustering etc to segment our products. Conclusion In this post, we learnt about the steps needed to prepare data for segmentation analysis. Specifically, we learned: How we should perform exploratory data analysis by looking at the data, the field types and the properties of numeric fields. Examples of what kind of features we can create from the raw categorical and continuous fields. How to implement one hot encoding in python as well as ordinal encoding Various types of scaling techniques and how to choose between them What is PCA and how to use it in python for feature reduction Do you have any questions or suggestions about this blog? Please feel free to drop in a note. Finally, I encourage you to check out the article below for an in-depth explanation of different methods for selecting optimal number of clusters for segmentation: Cheat sheet to implementing 7 methods for selecting optimal number of clusters in Python If you are, like me, passionate about AI, Data Science, or Economics, please feel free to add me on LinkedIn.
[ { "code": null, "e": 918, "s": 172, "text": "Data driven customer targeting or product bundling are critical for businesses to stay relevant against the intense competition they face. Consumers are now spoilt for choice and prefer personalized product offerings. With the coming of the fourth industrial revolution in the form of the immense growth of artificial intelligence and big data technologies, there is no better time to leverage segmentation models to perform such analysis. But before we do a deep dive into these models, we should be aware of what kind of data is needed for these models. This is the focus of my blog as we will be going through all the steps necessary for transforming our raw dataset to the format we need for training and testing our segmentation algorithms." }, { "code": null, "e": 927, "s": 918, "text": "The Data" }, { "code": null, "e": 1575, "s": 927, "text": "For this exercise, we will be working with clickstream data from an online store offering clothing for pregnant women. It has data from April 2008 to August 2008 and includes variables like product category, location of the photo on the webpage, country of origin of the IP address and product price in US dollars. The reason I chose this dataset is that clickstream data is becoming a very important source of providing fine-grained information about customer behaviour. It also provides us a dataset with typical challenges like high dimensionality, need for feature engineering, presence of categorical variables and different scales of fields." }, { "code": null, "e": 1667, "s": 1575, "text": "We will try to prepare the data for product segmentation by performing the following steps:" }, { "code": null, "e": 1752, "s": 1667, "text": "Exploratory Data Analysis (EDA)Feature EngineeringOne Hot EncodingStandardisationPCA" }, { "code": null, "e": 1784, "s": 1752, "text": "Exploratory Data Analysis (EDA)" }, { "code": null, "e": 1804, "s": 1784, "text": "Feature Engineering" }, { "code": null, "e": 1821, "s": 1804, "text": "One Hot Encoding" }, { "code": null, "e": 1837, "s": 1821, "text": "Standardisation" }, { "code": null, "e": 1841, "s": 1837, "text": "PCA" }, { "code": null, "e": 1873, "s": 1841, "text": "Exploratory Data Analysis (EDA)" }, { "code": null, "e": 1987, "s": 1873, "text": "We will first try to read the dataset (using read_csv function) and look at the top 5 rows (using head function):" }, { "code": null, "e": 2114, "s": 1987, "text": "# Read dataset and look at top recordsimport pandas as pddf = pd.read_csv('e-shop clothing 2008.csv', delimiter=\";\")df.head(5)" }, { "code": null, "e": 2310, "s": 2114, "text": "We have the data at a daily level for multiple clothing models (field name: “page 2 (clothing model)”). Next, let us check the number of rows and columns and their types (using the info function)" }, { "code": null, "e": 2373, "s": 2310, "text": "#Check the number of rows and columns and their typesdf.info()" }, { "code": null, "e": 2561, "s": 2373, "text": "We have 165474 records and 14 fields. One thing to note is that a lot of fields are numeric but should ideally be strings. Let us convert the fields as string using as.type(str) function:" }, { "code": null, "e": 2856, "s": 2561, "text": "# Convert categorical variables to stringcat_vars = ['year', 'month', 'day', 'country', 'session ID', 'page 1 (main category)', 'page 2 (clothing model)', 'colour', 'location', 'model photography', 'price 2', 'page']df[cat_vars] = df[cat_vars].astype(str)df.info()" }, { "code": null, "e": 2912, "s": 2856, "text": "Let us check the properties of the numeric fields next:" }, { "code": null, "e": 2962, "s": 2912, "text": "# Check properties of numeric fieldsdf.describe()" }, { "code": null, "e": 3283, "s": 2962, "text": "As seen in figure 4, the product price (field name: ‘price’) is on a much larger scale than sequence of clicks during one session (field name: ‘order’). This means that we will have to standardize these fields to bring them to the same scale as distance based models like K-means are affected by the scale of the fields." }, { "code": null, "e": 3303, "s": 3283, "text": "Feature Engineering" }, { "code": null, "e": 3535, "s": 3303, "text": "As previously mentioned, our dataset is at a daily level and we need to aggregate the data at a product level because we want to perform product segmentation. We create the following features while aggregating at the product level:" }, { "code": null, "e": 3979, "s": 3535, "text": "Most frequently occurring product colour, day of browsing, country, photo type (profile, en face), price type (higher or lower than category average), page number within website and location of the product’s photo on the page (using the mode function)Total number of unique session IDs (using the nununique function)Median, minimum and maximum of sequence of clicks during one session and product price (using the median, min and max function)" }, { "code": null, "e": 4231, "s": 3979, "text": "Most frequently occurring product colour, day of browsing, country, photo type (profile, en face), price type (higher or lower than category average), page number within website and location of the product’s photo on the page (using the mode function)" }, { "code": null, "e": 4297, "s": 4231, "text": "Total number of unique session IDs (using the nununique function)" }, { "code": null, "e": 4425, "s": 4297, "text": "Median, minimum and maximum of sequence of clicks during one session and product price (using the median, min and max function)" }, { "code": null, "e": 6297, "s": 4425, "text": "# Feature Engineeringfrom scipy.stats import mode df2 = df.groupby(['country','page 1 (main category)','page 2 (clothing model)']).agg( median_no_of_clicks_per_session=('order', 'median'), min_no_of_clicks_per_session=('order', 'max'), max_no_of_clicks_per_session=('order', 'min'), median_price=('price', 'median'), min_price=('price', 'max'), max_price=('price', 'min'), total_number_of_sessions =('session ID', pd.Series.nunique), most_frequent_day=('day', lambda x: mode(x)[0][0]), most_frequent_colour=('colour', lambda x: mode(x)[0][0]), most_frequent_location=('location', lambda x: mode(x)[0][0]), most_frequent_photo_type=('model photography', lambda x: mode(x)[0][0]), most_frequent_price_type =('price 2', lambda x: mode(x)[0][0]), most_frequent_page_number =('page', lambda x: mode(x)[0][0]) )df2" }, { "code": null, "e": 6314, "s": 6297, "text": "One Hot Encoding" }, { "code": null, "e": 6830, "s": 6314, "text": "One hot encoding creates dummy variables which is a duplicate variable which represents one level of a categorical variable. Presence of a level is represented by 1 and absence is represented by 0. If the categorical variable is ordinal (i.e. categories of the variable have an order) then we can translate the variable to a numeric variable using the OrdinalEncoder function. In our case, the categorical variables don’t have any ordinality and hence, we use the get_dummies function to create the dummy variables." }, { "code": null, "e": 7167, "s": 6830, "text": "# One hot encoding - to convert categorical data to continuouscat_vars = ['most_frequent_day', 'most_frequent_colour', 'most_frequent_location', 'most_frequent_photo_type', 'most_frequent_price_type', 'most_frequent_page_number']df2[cat_vars] = df2[cat_vars].astype(str)df3 = pd.get_dummies(df2)df3.head(5)" }, { "code": null, "e": 7280, "s": 7167, "text": "We can also use the OneHotEncoder function instead of get_dummies function if our nominal features are integers." }, { "code": null, "e": 7296, "s": 7280, "text": "Standardization" }, { "code": null, "e": 7520, "s": 7296, "text": "As shown in figure 4, our numeric features have different scales. Scaling helps to compare independent features with different ranges or units after converting them to comparable values. There are two major scaling methods:" }, { "code": null, "e": 8057, "s": 7520, "text": "Normalization is the ideal choice when we know that the distribution of data does not follow a Gaussian distribution or for algorithms that do not assume any data distribution like K-Nearest Neighbors and Neural Networks. On the other hand, standardization can be used when data follows a Gaussian distribution. But these are not strict rules and ideally we can try both and select the option which gives the best cluster validation results. We will be standardizing our numeric fields in this example using the StandardScaler function." }, { "code": null, "e": 8406, "s": 8057, "text": "# Standardizingfrom sklearn.preprocessing import StandardScalercon_vars = ['median_no_of_clicks_per_session', 'min_no_of_clicks_per_session', 'max_no_of_clicks_per_session', 'median_price', 'min_price', 'max_price', 'total_number_of_sessions']scaler = StandardScaler()df3[con_vars]=scaler.fit_transform(df3[con_vars])df3.head(5)" }, { "code": null, "e": 8441, "s": 8406, "text": "Principal Component Analysis (PCA)" }, { "code": null, "e": 9243, "s": 8441, "text": "Principal component analysis combines our current features in a specific way to create new features and then we can drop the “least important” while still retaining the most valuable parts of all of the original variables. This is a useful method when we have a lot of features to handle. It calculates the covariance matrix of all the features and then generates the eigenvectors and eigenvalues from the matrix. Then, the covariance matrix is multiplied by the eigenvectors to create principal components. These principal components are the new features based on our original features and their importance in terms of explaining the variability in the dataset is given by eigenvalues. We can keep the top ranked principal components which explain a minimum level of variance in our original dataset." }, { "code": null, "e": 9462, "s": 9243, "text": "We can implement PCA analysis using the pca function from sklearn.decomposition module. I have set up a loop function to identify number of principal components that explain at least 85% of the variance in the dataset." }, { "code": null, "e": 10091, "s": 9462, "text": "# PCAfrom sklearn.decomposition import PCA# Loop Function to identify number of principal components that explain at least 85% of the variancefor comp in range(3, df3.shape[1]): pca = PCA(n_components= comp, random_state=42) pca.fit(df3) comp_check = pca.explained_variance_ratio_ final_comp = comp if comp_check.sum() > 0.85: break Final_PCA = PCA(n_components= final_comp,random_state=42)Final_PCA.fit(df3)cluster_df=Final_PCA.transform(df3)num_comps = comp_check.shape[0]print(\"Using {} components, we can explain {}% of the variability in the original data.\".format(final_comp,comp_check.sum()))" }, { "code": null, "e": 10314, "s": 10091, "text": "As seen in figure 8, 15 components are able to explain 85% of the variance in our dataset. We can now use these features in our unsupervised models like K means, DBSCAN, hierarchical clustering etc to segment our products." }, { "code": null, "e": 10325, "s": 10314, "text": "Conclusion" }, { "code": null, "e": 10415, "s": 10325, "text": "In this post, we learnt about the steps needed to prepare data for segmentation analysis." }, { "code": null, "e": 10441, "s": 10415, "text": "Specifically, we learned:" }, { "code": null, "e": 10567, "s": 10441, "text": "How we should perform exploratory data analysis by looking at the data, the field types and the properties of numeric fields." }, { "code": null, "e": 10663, "s": 10567, "text": "Examples of what kind of features we can create from the raw categorical and continuous fields." }, { "code": null, "e": 10735, "s": 10663, "text": "How to implement one hot encoding in python as well as ordinal encoding" }, { "code": null, "e": 10802, "s": 10735, "text": "Various types of scaling techniques and how to choose between them" }, { "code": null, "e": 10864, "s": 10802, "text": "What is PCA and how to use it in python for feature reduction" }, { "code": null, "e": 10958, "s": 10864, "text": "Do you have any questions or suggestions about this blog? Please feel free to drop in a note." }, { "code": null, "e": 11122, "s": 10958, "text": "Finally, I encourage you to check out the article below for an in-depth explanation of different methods for selecting optimal number of clusters for segmentation:" }, { "code": null, "e": 11211, "s": 11122, "text": "Cheat sheet to implementing 7 methods for selecting optimal number of clusters in Python" } ]
How to create a graph in R using ggplot2 with all the four quadrants?
The default graph created by using ggplot2 package shows the axes labels depending on the starting and ending values of the column of the data frame or vector but we might want to visualize it just like we do in paper form of graphs that shows all of the four quadrants. This can be done by using xlim, ylim, geom_hline, and geom_vline functions with ggplot function of ggplot2 package. Consider the below data frame − Live Demo x<-1:5 y<-5:1 df<-data.frame(x,y) df x y 1 1 5 2 2 4 3 3 3 4 4 2 5 5 1 Loading ggplot2 package and creating point chart between x and y− library(ggplot2) ggplot(df,aes(x,y))+geom_point() Creating point chart between x and y by showing all four quadrants − ggplot(df,aes(x,y))+geom_point()+xlim(-6,6)+ylim(-6,6)+geom_hline(yintercept=0)+geom_vline(xintercept=0)
[ { "code": null, "e": 1449, "s": 1062, "text": "The default graph created by using ggplot2 package shows the axes labels depending on the starting and ending values of the column of the data frame or vector but we might want to visualize it just like we do in paper form of graphs that shows all of the four quadrants. This can be done by using xlim, ylim, geom_hline, and geom_vline functions with ggplot function of ggplot2 package." }, { "code": null, "e": 1481, "s": 1449, "text": "Consider the below data frame −" }, { "code": null, "e": 1492, "s": 1481, "text": " Live Demo" }, { "code": null, "e": 1529, "s": 1492, "text": "x<-1:5\ny<-5:1\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1565, "s": 1529, "text": " x y\n1 1 5\n2 2 4\n3 3 3\n4 4 2\n5 5 1" }, { "code": null, "e": 1631, "s": 1565, "text": "Loading ggplot2 package and creating point chart between x and y−" }, { "code": null, "e": 1681, "s": 1631, "text": "library(ggplot2) ggplot(df,aes(x,y))+geom_point()" }, { "code": null, "e": 1750, "s": 1681, "text": "Creating point chart between x and y by showing all four quadrants −" }, { "code": null, "e": 1855, "s": 1750, "text": "ggplot(df,aes(x,y))+geom_point()+xlim(-6,6)+ylim(-6,6)+geom_hline(yintercept=0)+geom_vline(xintercept=0)" } ]
Improve data quality by using the pandas library and Python | by Anthony Figueroa | Towards Data Science
Data quality is a broad concept with multiple dimensions. I detail that information in another introductory article. This tutorial explores a real-life example. We identify what we want to improve, create the code to achieve our goals, and wrap up with some comments about things that can happen in real-life situations. To follow along, you need a basic understanding of Python. Python Data Analysis Library (pandas) is an open-source, BSD-licensed library that provides high-performance, easy-to-use data structures and data analysis tools for the Python programming language. You can install pandas by entering this code in a command line: python3 -m pip install — upgrade pandas. There are two primary classes of data structures in pandas: Series. A single column that can contain any type of data. DataFrame. A relational data table, with rows and named columns. A DataFrame contains one or more Series and a name for each Series. DataFrames are commonly used abstractions, or complexity managers, for data manipulation. A Series is like a cross between a dictionary and a list. Items are stored in order, and they’re labeled so you can retrieve them. The first item in a Series list is the special index, which is a lot like a dictionary key. The second item is your actual data. It’s important to note that each data column has its own index label. You can retrieve them by using the .name attribute. This part of the structure is different than a dictionary, and it’s useful for merging multiple columns of data. This quick example shows you what a Series looks like: import pandas as pdcarbs = [‘pizza’, ‘hamburger‘, ‘rice’]pd.Series(carbs)0 ‘pizza’1 ‘hamburger’2 ‘rice’dType: object We can also create a Series with label attributes: foods = pd.Series( [‘pizza’, ‘hamburger’, ‘rice’], index=[‘Italy’, ‘USA’, ‘Japan’]Italy ‘pizza’USA ‘hamburger’Japan ‘rice’dType: object You can query a Series by the index position or by the index label. If you don’t give the Series an index, the position and label have the same value. To query by numeric location, use the iloc attribute. foods.iloc[2]‘rice’ To query by the index label, use the loc attribute. foods.loc[‘USA’]‘hamburger’ Keep in mind that one key can return multiple results. This example shows the basics. There are many other Series topics like vectorization, memory management, and more. But we won’t go that deep in this article. A DataFrame is the main structure of the pandas library. It’s the primary object that you work within data analysis and cleaning tasks. Conceptually, a DataFrame is a two-dimensional Series object. It has an index and multiple columns of content, and each column is labeled. But the distinction between a column and a row is only conceptual. Think of a DataFrame as a two-axis labeled array. You can create the DataFrame table that follows by using Series: purchase_1 = pd.Series({ ‘Name’: ‘John’, ‘Ordered’:’Pizza’, ‘Cost’: 11 })purchase_2 = pd.Series({ ‘Name’: ‘Mary’, ‘Ordered’:’Brioche’, ‘Cost’: 21.20 })purchase_3 = pd.Series({ ‘Name’: ‘Timothy’, ‘Ordered’:’Steak’, ‘Cost’: 30.00 })df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=[‘Restaurant 1’, ‘Restaurant 1’, ‘Restaurant 2’])+--------------+-------+---------+---------+| | Cost | Ordered | Name |+--------------+-------+---------+---------+| Restaurant 1 | 11 | Pizza | John || Restaurant 1 | 21.20 | Brioche | Mary || Restaurant 2 | 30.00 | Steak | Timothy |+--------------+-------+---------+---------+ Like with Series, we can extract data by using the iloc and loc attributes. DataFrames are two-dimensional. So when we pass a single value to the loc, the indexing operator returns a Series if there’s only one row to return. Let’s query this DataFrame. df.loc[‘Restaurant 2’]Cost 30.00Ordered ‘Steak’Name ‘Timothy’ This function returns an object of the type Series. One powerful feature of the pandas DataFrame is that you can quickly select data based on multiple axes. Because iloc and loc are used for row selection, pandas developers reserved the indexing operator directly on the DataFrame for column selection. In a DataFrame, columns always have a name. So this selection is always label based. As an example, we can rewrite the query for all Restaurant 1 costs with this code: df.loc[‘Restaurant 1’][‘Cost’]Restaurant 1 11Restaurant 1 21.20Name: Cost, dType: float64 Now we tackle a simple but common problem with data: missing values. In Data Demystified — Data Quality, I explain why completeness is one of the dimensions to consider when you assess data quality. Missing data can also be related to two more dimensions: lack of accuracy or consistency. There’s a lot more to learn, but I want to jump straight to an example and introduce new concepts as we go. We can read large datasets from any source. Some examples are relational databases, files, and NoSQL databases. This library example shows a set of methods that interact with a relational database: import pandas.io.sql as psql Note that connect and read_sql are key methods. For the sake of simplicity, we’ll work with a CSV file. Let’s say we have a log file that’s stored in logs.csv. This log stores the position of the mouse pointer every 100ms. If the mouse doesn’t change, the algorithm stores an empty value, but it adds a new entry to the row. Why? Because it’s not efficient to send this information across the network if it hasn’t changed. Our goal is to have all the rows in the CSV file stored with the right coordinates. As shown in the table that follows, we can store the rows with this code: df = pd.read_csv(‘logs.csv’)df+----+-----------+---------+---------+-----+-----+| | timestamp | page | user | x | y |+----+-----------+---------+---------+-----+-----+| 0 | 169971476 | landing | admin | 744 | 220 || 1 | 169971576 | landing | admin | NaN | NaN || 2 | 169971591 | profile | maryb | 321 | 774 || 3 | 169971691 | profile | maryb | NaN | NaN || 4 | 169972003 | landing | joshf | 432 | 553 || 5 | 169971776 | landing | admin | 722 | 459 || 6 | 169971876 | landing | admin | NaN | NaN || 7 | 169971891 | profile | maryb | 221 | 333 || 8 | 169971976 | landing | admin | NaN | NaN || 9 | 169971991 | profile | maryb | NaN | NaN || 10 | 169972003 | landing | johnive | 312 | 3 || 11 | 169971791 | profile | maryb | NaN | NaN || 12 | 169971676 | landing | admin | NaN | NaN |+----+-----------+---------+---------+-----+-----+ When we check the data, we see multiple problems. There are lots of empty values, and the file isn’t ordered by a timestamp. This issue is common in systems with a high degree of parallelism. One function that can handle the empty data is fillna. For more information, enter df.fillna? in your command line. There are many options for working with this method: One option is to pass in a single scalar value that changes all the missing data to one value. But that change isn’t what we want. Another option is to pass a method parameter. The two common values are ffill and bfill. ffill fills cells going forward. It updates a NaN value in a cell with the value from the previous row. For this update to make sense, your data needs to be sorted in order. But traditional database management systems don’t usually guarantee any order to the data you extract from them. So, let’s sort the data first. We can sort either by index or by values. In this example, timestamp is the index, and we sort the index field: df = df.set_index(‘timestamp’)df = df.sort_index() We create the following table: +-----------+---------+---------+-----+-----+| | page | user | x | y |+-----------+---------+---------+-----+-----+| time | | | | || 169971476 | landing | admin | 744 | 220 || 169971576 | landing | admin | NaN | NaN || 169971591 | profile | maryb | 321 | 774 || 169971676 | landing | admin | NaN | NaN || 169971691 | profile | maryb | NaN | NaN || 169971776 | landing | admin | 722 | 459 || 169971791 | profile | maryb | NaN | NaN || 169971876 | landing | admin | NaN | NaN || 169971891 | profile | maryb | 221 | 333 || 169971976 | landing | admin | NaN | NaN || 169971991 | profile | maryb | NaN | NaN || 169972003 | landing | johnive | 312 | 3 || 169972003 | landing | joshf | 432 | 553 |+-----------+---------+---------+-----+-----+ As you can see, there’s still a problem. Our timestamp isn’t unique. Two users might interact with the platform at the same time. Let’s reset the index and create a compound index by using both timestamp and the username: df = df.reset_index()df = df.set_index([‘timestamp’, ‘user’])df We create the following table: +-----------+---------+---------+-----+-----+| | | page | x | y |+-----------+---------+---------+-----+-----+| time | user | | | || 169971476 | admin | landing | 744 | 220 || 169971576 | admin | landing | NaN | NaN || 169971676 | admin | landing | NaN | NaN || 169971776 | admin | landing | 722 | 459 || 169971876 | admin | landing | NaN | NaN || 169971976 | admin | landing | NaN | NaN || 169971591 | maryb | profile | 321 | 774 || 169971691 | maryb | profile | NaN | NaN || 169971791 | maryb | profile | NaN | NaN || 169971891 | maryb | profile | 221 | 333 || 169971991 | maryb | profile | NaN | NaN || 169972003 | johnive | landing | 312 | 3 || | joshf | landing | 432 | 553 |+-----------+---------+---------+-----+-----+ Now we can fill in the missing data with ffill: df = df.fillna(method='ffill') This table shows the result: +-----------+---------+---------+-----+-----+| | | page | x | y |+-----------+---------+---------+-----+-----+| time | user | | | || 169971476 | admin | landing | 744 | 220 || 169971576 | admin | landing | 744 | 220 || 169971676 | admin | landing | 744 | 220 || 169971776 | admin | landing | 722 | 459 || 169971876 | admin | landing | 722 | 459 || 169971976 | admin | landing | 722 | 459 || 169971591 | maryb | profile | 321 | 774 || 169971691 | maryb | profile | 321 | 774 || 169971791 | maryb | profile | 321 | 774 || 169971891 | maryb | profile | 221 | 333 || 169971991 | maryb | profile | 221 | 333 || 169972003 | johnive | landing | 312 | 3 || | joshf | landing | 432 | 553 |+-----------+---------+---------+-----+-----+ pandas outperforms PostgreSQL. It runs 5 to 10 times faster for large datasets. The only time PostgreSQL performs better is with small datasets, usually less than a thousand rows. Selecting columns is efficient in pandas, with an O(1) time. That’s because the DataFrame is stored in memory. For that same reason, pandas has limitations, and there’s still a need for SQL. pandas data is stored in memory. So it’s hard to load a CSV file that’s bigger than half the system’s memory. Datasets often contain hundreds of columns, which creates file sizes of around 10 GB for datasets with more than a million rows. PostgreSQL and pandas are two different tools with overlapping functionality. PostgreSQL and other SQL-based languages were created to manage databases. They make it easy for users to access and retrieve data, especially across multiple tables. A server that runs PostgreSQL has all the datasets stored as tables across the system. It’s not practical for users to transfer the required tables to their systems and then use pandas to perform tasks like join and group on the client side. pandas’ specialty is data manipulation and complex data analysis operations. The two tools don’t compete in the tech market. But rather, they add to the range of tools available in the data science computational stack. The pandas team recently introduced a way to fill in missing values with a series that’s the same length as your DataFrame. With this new method, it’s easy to derive values that are missing if you need to do that. Fox, D. (2018), Manipulating Data with pandas and PostgreSQL: Which is better?, The Data Incubator. pandas (2019), Python Data Analysis Library.
[ { "code": null, "e": 552, "s": 172, "text": "Data quality is a broad concept with multiple dimensions. I detail that information in another introductory article. This tutorial explores a real-life example. We identify what we want to improve, create the code to achieve our goals, and wrap up with some comments about things that can happen in real-life situations. To follow along, you need a basic understanding of Python." }, { "code": null, "e": 751, "s": 552, "text": "Python Data Analysis Library (pandas) is an open-source, BSD-licensed library that provides high-performance, easy-to-use data structures and data analysis tools for the Python programming language." }, { "code": null, "e": 856, "s": 751, "text": "You can install pandas by entering this code in a command line: python3 -m pip install — upgrade pandas." }, { "code": null, "e": 916, "s": 856, "text": "There are two primary classes of data structures in pandas:" }, { "code": null, "e": 975, "s": 916, "text": "Series. A single column that can contain any type of data." }, { "code": null, "e": 1040, "s": 975, "text": "DataFrame. A relational data table, with rows and named columns." }, { "code": null, "e": 1198, "s": 1040, "text": "A DataFrame contains one or more Series and a name for each Series. DataFrames are commonly used abstractions, or complexity managers, for data manipulation." }, { "code": null, "e": 1693, "s": 1198, "text": "A Series is like a cross between a dictionary and a list. Items are stored in order, and they’re labeled so you can retrieve them. The first item in a Series list is the special index, which is a lot like a dictionary key. The second item is your actual data. It’s important to note that each data column has its own index label. You can retrieve them by using the .name attribute. This part of the structure is different than a dictionary, and it’s useful for merging multiple columns of data." }, { "code": null, "e": 1748, "s": 1693, "text": "This quick example shows you what a Series looks like:" }, { "code": null, "e": 1877, "s": 1748, "text": "import pandas as pdcarbs = [‘pizza’, ‘hamburger‘, ‘rice’]pd.Series(carbs)0 ‘pizza’1 ‘hamburger’2 ‘rice’dType: object" }, { "code": null, "e": 1928, "s": 1877, "text": "We can also create a Series with label attributes:" }, { "code": null, "e": 2078, "s": 1928, "text": "foods = pd.Series( [‘pizza’, ‘hamburger’, ‘rice’], index=[‘Italy’, ‘USA’, ‘Japan’]Italy ‘pizza’USA ‘hamburger’Japan ‘rice’dType: object" }, { "code": null, "e": 2283, "s": 2078, "text": "You can query a Series by the index position or by the index label. If you don’t give the Series an index, the position and label have the same value. To query by numeric location, use the iloc attribute." }, { "code": null, "e": 2303, "s": 2283, "text": "foods.iloc[2]‘rice’" }, { "code": null, "e": 2355, "s": 2303, "text": "To query by the index label, use the loc attribute." }, { "code": null, "e": 2383, "s": 2355, "text": "foods.loc[‘USA’]‘hamburger’" }, { "code": null, "e": 2596, "s": 2383, "text": "Keep in mind that one key can return multiple results. This example shows the basics. There are many other Series topics like vectorization, memory management, and more. But we won’t go that deep in this article." }, { "code": null, "e": 2732, "s": 2596, "text": "A DataFrame is the main structure of the pandas library. It’s the primary object that you work within data analysis and cleaning tasks." }, { "code": null, "e": 2988, "s": 2732, "text": "Conceptually, a DataFrame is a two-dimensional Series object. It has an index and multiple columns of content, and each column is labeled. But the distinction between a column and a row is only conceptual. Think of a DataFrame as a two-axis labeled array." }, { "code": null, "e": 3053, "s": 2988, "text": "You can create the DataFrame table that follows by using Series:" }, { "code": null, "e": 3706, "s": 3053, "text": "purchase_1 = pd.Series({ ‘Name’: ‘John’, ‘Ordered’:’Pizza’, ‘Cost’: 11 })purchase_2 = pd.Series({ ‘Name’: ‘Mary’, ‘Ordered’:’Brioche’, ‘Cost’: 21.20 })purchase_3 = pd.Series({ ‘Name’: ‘Timothy’, ‘Ordered’:’Steak’, ‘Cost’: 30.00 })df = pd.DataFrame([purchase_1, purchase_2, purchase_3], index=[‘Restaurant 1’, ‘Restaurant 1’, ‘Restaurant 2’])+--------------+-------+---------+---------+| | Cost | Ordered | Name |+--------------+-------+---------+---------+| Restaurant 1 | 11 | Pizza | John || Restaurant 1 | 21.20 | Brioche | Mary || Restaurant 2 | 30.00 | Steak | Timothy |+--------------+-------+---------+---------+" }, { "code": null, "e": 3931, "s": 3706, "text": "Like with Series, we can extract data by using the iloc and loc attributes. DataFrames are two-dimensional. So when we pass a single value to the loc, the indexing operator returns a Series if there’s only one row to return." }, { "code": null, "e": 3959, "s": 3931, "text": "Let’s query this DataFrame." }, { "code": null, "e": 4037, "s": 3959, "text": "df.loc[‘Restaurant 2’]Cost 30.00Ordered ‘Steak’Name ‘Timothy’" }, { "code": null, "e": 4089, "s": 4037, "text": "This function returns an object of the type Series." }, { "code": null, "e": 4425, "s": 4089, "text": "One powerful feature of the pandas DataFrame is that you can quickly select data based on multiple axes. Because iloc and loc are used for row selection, pandas developers reserved the indexing operator directly on the DataFrame for column selection. In a DataFrame, columns always have a name. So this selection is always label based." }, { "code": null, "e": 4508, "s": 4425, "text": "As an example, we can rewrite the query for all Restaurant 1 costs with this code:" }, { "code": null, "e": 4604, "s": 4508, "text": "df.loc[‘Restaurant 1’][‘Cost’]Restaurant 1 11Restaurant 1 21.20Name: Cost, dType: float64" }, { "code": null, "e": 5001, "s": 4604, "text": "Now we tackle a simple but common problem with data: missing values. In Data Demystified — Data Quality, I explain why completeness is one of the dimensions to consider when you assess data quality. Missing data can also be related to two more dimensions: lack of accuracy or consistency. There’s a lot more to learn, but I want to jump straight to an example and introduce new concepts as we go." }, { "code": null, "e": 5199, "s": 5001, "text": "We can read large datasets from any source. Some examples are relational databases, files, and NoSQL databases. This library example shows a set of methods that interact with a relational database:" }, { "code": null, "e": 5228, "s": 5199, "text": "import pandas.io.sql as psql" }, { "code": null, "e": 5276, "s": 5228, "text": "Note that connect and read_sql are key methods." }, { "code": null, "e": 5651, "s": 5276, "text": "For the sake of simplicity, we’ll work with a CSV file. Let’s say we have a log file that’s stored in logs.csv. This log stores the position of the mouse pointer every 100ms. If the mouse doesn’t change, the algorithm stores an empty value, but it adds a new entry to the row. Why? Because it’s not efficient to send this information across the network if it hasn’t changed." }, { "code": null, "e": 5809, "s": 5651, "text": "Our goal is to have all the rows in the CSV file stored with the right coordinates. As shown in the table that follows, we can store the rows with this code:" }, { "code": null, "e": 6690, "s": 5809, "text": "df = pd.read_csv(‘logs.csv’)df+----+-----------+---------+---------+-----+-----+| | timestamp | page | user | x | y |+----+-----------+---------+---------+-----+-----+| 0 | 169971476 | landing | admin | 744 | 220 || 1 | 169971576 | landing | admin | NaN | NaN || 2 | 169971591 | profile | maryb | 321 | 774 || 3 | 169971691 | profile | maryb | NaN | NaN || 4 | 169972003 | landing | joshf | 432 | 553 || 5 | 169971776 | landing | admin | 722 | 459 || 6 | 169971876 | landing | admin | NaN | NaN || 7 | 169971891 | profile | maryb | 221 | 333 || 8 | 169971976 | landing | admin | NaN | NaN || 9 | 169971991 | profile | maryb | NaN | NaN || 10 | 169972003 | landing | johnive | 312 | 3 || 11 | 169971791 | profile | maryb | NaN | NaN || 12 | 169971676 | landing | admin | NaN | NaN |+----+-----------+---------+---------+-----+-----+" }, { "code": null, "e": 6882, "s": 6690, "text": "When we check the data, we see multiple problems. There are lots of empty values, and the file isn’t ordered by a timestamp. This issue is common in systems with a high degree of parallelism." }, { "code": null, "e": 7051, "s": 6882, "text": "One function that can handle the empty data is fillna. For more information, enter df.fillna? in your command line. There are many options for working with this method:" }, { "code": null, "e": 7182, "s": 7051, "text": "One option is to pass in a single scalar value that changes all the missing data to one value. But that change isn’t what we want." }, { "code": null, "e": 7558, "s": 7182, "text": "Another option is to pass a method parameter. The two common values are ffill and bfill. ffill fills cells going forward. It updates a NaN value in a cell with the value from the previous row. For this update to make sense, your data needs to be sorted in order. But traditional database management systems don’t usually guarantee any order to the data you extract from them." }, { "code": null, "e": 7701, "s": 7558, "text": "So, let’s sort the data first. We can sort either by index or by values. In this example, timestamp is the index, and we sort the index field:" }, { "code": null, "e": 7752, "s": 7701, "text": "df = df.set_index(‘timestamp’)df = df.sort_index()" }, { "code": null, "e": 7783, "s": 7752, "text": "We create the following table:" }, { "code": null, "e": 8594, "s": 7783, "text": "+-----------+---------+---------+-----+-----+| | page | user | x | y |+-----------+---------+---------+-----+-----+| time | | | | || 169971476 | landing | admin | 744 | 220 || 169971576 | landing | admin | NaN | NaN || 169971591 | profile | maryb | 321 | 774 || 169971676 | landing | admin | NaN | NaN || 169971691 | profile | maryb | NaN | NaN || 169971776 | landing | admin | 722 | 459 || 169971791 | profile | maryb | NaN | NaN || 169971876 | landing | admin | NaN | NaN || 169971891 | profile | maryb | 221 | 333 || 169971976 | landing | admin | NaN | NaN || 169971991 | profile | maryb | NaN | NaN || 169972003 | landing | johnive | 312 | 3 || 169972003 | landing | joshf | 432 | 553 |+-----------+---------+---------+-----+-----+" }, { "code": null, "e": 8724, "s": 8594, "text": "As you can see, there’s still a problem. Our timestamp isn’t unique. Two users might interact with the platform at the same time." }, { "code": null, "e": 8816, "s": 8724, "text": "Let’s reset the index and create a compound index by using both timestamp and the username:" }, { "code": null, "e": 8880, "s": 8816, "text": "df = df.reset_index()df = df.set_index([‘timestamp’, ‘user’])df" }, { "code": null, "e": 8911, "s": 8880, "text": "We create the following table:" }, { "code": null, "e": 9722, "s": 8911, "text": "+-----------+---------+---------+-----+-----+| | | page | x | y |+-----------+---------+---------+-----+-----+| time | user | | | || 169971476 | admin | landing | 744 | 220 || 169971576 | admin | landing | NaN | NaN || 169971676 | admin | landing | NaN | NaN || 169971776 | admin | landing | 722 | 459 || 169971876 | admin | landing | NaN | NaN || 169971976 | admin | landing | NaN | NaN || 169971591 | maryb | profile | 321 | 774 || 169971691 | maryb | profile | NaN | NaN || 169971791 | maryb | profile | NaN | NaN || 169971891 | maryb | profile | 221 | 333 || 169971991 | maryb | profile | NaN | NaN || 169972003 | johnive | landing | 312 | 3 || | joshf | landing | 432 | 553 |+-----------+---------+---------+-----+-----+" }, { "code": null, "e": 9770, "s": 9722, "text": "Now we can fill in the missing data with ffill:" }, { "code": null, "e": 9801, "s": 9770, "text": "df = df.fillna(method='ffill')" }, { "code": null, "e": 9830, "s": 9801, "text": "This table shows the result:" }, { "code": null, "e": 10641, "s": 9830, "text": "+-----------+---------+---------+-----+-----+| | | page | x | y |+-----------+---------+---------+-----+-----+| time | user | | | || 169971476 | admin | landing | 744 | 220 || 169971576 | admin | landing | 744 | 220 || 169971676 | admin | landing | 744 | 220 || 169971776 | admin | landing | 722 | 459 || 169971876 | admin | landing | 722 | 459 || 169971976 | admin | landing | 722 | 459 || 169971591 | maryb | profile | 321 | 774 || 169971691 | maryb | profile | 321 | 774 || 169971791 | maryb | profile | 321 | 774 || 169971891 | maryb | profile | 221 | 333 || 169971991 | maryb | profile | 221 | 333 || 169972003 | johnive | landing | 312 | 3 || | joshf | landing | 432 | 553 |+-----------+---------+---------+-----+-----+" }, { "code": null, "e": 10932, "s": 10641, "text": "pandas outperforms PostgreSQL. It runs 5 to 10 times faster for large datasets. The only time PostgreSQL performs better is with small datasets, usually less than a thousand rows. Selecting columns is efficient in pandas, with an O(1) time. That’s because the DataFrame is stored in memory." }, { "code": null, "e": 11251, "s": 10932, "text": "For that same reason, pandas has limitations, and there’s still a need for SQL. pandas data is stored in memory. So it’s hard to load a CSV file that’s bigger than half the system’s memory. Datasets often contain hundreds of columns, which creates file sizes of around 10 GB for datasets with more than a million rows." }, { "code": null, "e": 11496, "s": 11251, "text": "PostgreSQL and pandas are two different tools with overlapping functionality. PostgreSQL and other SQL-based languages were created to manage databases. They make it easy for users to access and retrieve data, especially across multiple tables." }, { "code": null, "e": 11738, "s": 11496, "text": "A server that runs PostgreSQL has all the datasets stored as tables across the system. It’s not practical for users to transfer the required tables to their systems and then use pandas to perform tasks like join and group on the client side." }, { "code": null, "e": 11815, "s": 11738, "text": "pandas’ specialty is data manipulation and complex data analysis operations." }, { "code": null, "e": 11957, "s": 11815, "text": "The two tools don’t compete in the tech market. But rather, they add to the range of tools available in the data science computational stack." }, { "code": null, "e": 12171, "s": 11957, "text": "The pandas team recently introduced a way to fill in missing values with a series that’s the same length as your DataFrame. With this new method, it’s easy to derive values that are missing if you need to do that." }, { "code": null, "e": 12271, "s": 12171, "text": "Fox, D. (2018), Manipulating Data with pandas and PostgreSQL: Which is better?, The Data Incubator." } ]
Poisson Distribution Explained — Intuition, Examples, and Derivation | Towards Data Science
Before setting the parameter λ and plugging it into the formula, let’s pause a second and ask a question. Why did Poisson have to invent the Poisson Distribution? Why does this distribution exist (= why did he invent this)? When should Poisson be used for modeling? To predict the # of events occurring in the future! More formally, to predict the probability of a given number of events occurring in a fixed interval of time. If you’ve ever sold something, this “event” can be defined, for example, as a customer purchasing something from you (the moment of truth, not just browsing). It can be how many visitors you get on your website a day, how many clicks your ads get for the next month, how many phone calls you get during your shift, or even how many people will die from a fatal disease next year, etc. Below is an example of how I’d use Poisson in real life. Every week, on average, 17 people clap for my blog post. I’d like to predict the # of ppl who would clap next week because I get paid weekly by those numbers.What is the probability that exactly 20 people (or 10, 30, 50, etc.) will clap for the blog post next week? One way to solve this would be to start with the number of reads. Each person who reads the blog has some probability that they will really like it and clap. This is a classic job for the binomial distribution, since we are calculating the probability of the number of successful events (claps). A binomial random variable is the number of successes x in n repeated trials. And we assume the probability of success p is constant over each trial. However, here we are given only one piece of information — 17 ppl/week, which is a “rate” (the average # of successes per week, or the expected value of x). We don’t know anything about the clapping probability p, nor the number of blog visitors n. Therefore, we need a little more information to tackle this problem. What more do we need to frame this probability as a binomial problem? We need two things: the probability of success (claps) p & the number of trials (visitors) n. Let’s get them from the past data. These are stats for 1 year. A total of 59k people read my blog. Out of 59k people, 888 of them clapped. Therefore, the # of people who read my blog per week (n) is 59k/52 = 1134. The # of people who clapped per week (x) is 888/52 =17. # of people who read per week (n) = 59k/52 = 1134# of people who clap per week (x) = 888/52 = 17Success probability (p) : 888/59k = 0.015 = 1.5% <Binomial Probability for different x’s>╔══════╦════════════════╗║ x ║ Binomial P(X=x)║╠══════╬════════════════╣║ 10 ║ 0.02250 ║║ 17 ║ 0.09701 ║ 🡒 The average rate has the highest P!║ 20 ║ 0.06962 ║ 🡒 Nice. 20 is also quite Likely!║ 30 ║ 0.00121 ║║ 40 ║ < 0.000001 ║ 🡒 Well, I guess I won’t get 40 claps..╚══════╩════════════════╝ We just solved the problem with a binomial distribution. Then, what is Poisson for? What are the things that only Poisson can do, but Binomial can’t? a) A binomial random variable is “BI-nary” — 0 or 1. In the above example, we have 17 ppl/wk who clapped. This means 17/7 = 2.4 people clapped per day, and 17/(7*24) = 0.1 people clapping per hour. If we model the success probability by hour (0.1 people/hr) using the binomial random variable, this means most of the hours get zero claps but some hours will get exactly 1 clap. However, it is also very possible that certain hours will get more than 1 clap (2, 3, 5 claps, etc.) The problem with binomial is that it CANNOT contain more than 1 event in the unit of time (in this case, 1 hr is the unit time). The unit of time can only have 0 or 1 event. Then, how about dividing 1 hour into 60 minutes, and make unit time smaller, for example, a minute? Then 1 hour can contain multiple events. (Still, one minute will contain exactly one or zero events.) Is our problem solved now? Kind of. But what if, during that one minute, we get multiple claps? (i.e. someone shared your blog post on Twitter and the traffic spiked at that minute.) Then what? We can divide a minute into seconds. Then our time unit becomes a second and again a minute can contain multiple events. But this binary container problem will always exist for ever-smaller time units. The idea is, we can make the Binomial random variable handle multiple events by dividing a unit time into smaller units. By using smaller divisions, we can make the original unit time contain more than one event. Mathematically, this means n → ∞. Since we assume the rate is fixed, we must have p → 0. Because otherwise, n*p, which is the number of events, will blow up. Using the limit, the unit times are now infinitesimal. We no longer have to worry about more than one event occurring within the same unit time. And this is how we derive Poisson distribution. b) In the Binomial distribution, the # of trials (n) should be known beforehand. If you use Binomial, you cannot calculate the success probability only with the rate (i.e. 17 ppl/week). You need “more info” (n & p) in order to use the binomial PMF.The Poisson Distribution, on the other hand, doesn’t require you to know n or p. We are assuming n is infinitely large and p is infinitesimal. The only parameter of the Poisson distribution is the rate λ (the expected value of x). In real life, only knowing the rate (i.e., during 2pm~4pm, I received 3 phone calls) is much more common than knowing both n & p. Now you know where each component λ^k , k! and e^-λ come from! Finally, we only need to show that the multiplication of the first two terms n!/((n-k)!*n^k) is 1 when n approaches infinity. It is 1. We got the Poisson Formula! Now the Wikipedia explanation starts making sense. Plug your own data into the formula and see if P(x) makes sense to you! Below is mine. < Comparison between Binomial & Poisson >╔══════╦═══════════════════╦═══════════════════════╗║ k ║ Binomial P(X=k) ║ Poisson P(X=k;λ=17) ║╠══════╬═══════════════════╬═══════════════════════╣║ 10 ║ 0.02250 ║ 0.02300 ║║ 17 ║ 0.09701 ║ 0.09628 ║║ 20 ║ 0.06962 ║ 0.07595 ║║ 30 ║ 0.00121 ║ 0.00340 ║║ 40 ║ < 0.000001 ║ < 0.000001 ║╚══════╩═══════════════════╩═══════════════════════╝* You can calculate both easily here:Binomial: https://stattrek.com/online-calculator/binomial.aspxPoisson : https://stattrek.com/online-calculator/poisson.aspx A few things to note: Even though the Poisson distribution models rare events, the rate λ can be any number. It doesn’t always have to be small.The Poisson Distribution is asymmetric — it is always skewed toward the right. Because it is inhibited by the zero occurrence barrier (there is no such thing as “minus one” clap) on the left and it is unlimited on the other side.As λ becomes bigger, the graph looks more like a normal distribution. Even though the Poisson distribution models rare events, the rate λ can be any number. It doesn’t always have to be small. The Poisson Distribution is asymmetric — it is always skewed toward the right. Because it is inhibited by the zero occurrence barrier (there is no such thing as “minus one” clap) on the left and it is unlimited on the other side. As λ becomes bigger, the graph looks more like a normal distribution. 4. The Poisson Model Assumptions a. The average rate of events per unit time is constant. This means the number of people who visit your blog per hour might not follow a Poisson Distribution, because the hourly rate is not constant (higher rate during the daytime, lower rate during the nighttime). Using monthly rate for consumer/biological data would be just an approximation as well, since the seasonality effect is non-trivial in that domain. b. Events are independent.The arrivals of your blog visitors might not always be independent. For example, sometimes a large number of visitors come in a group because someone popular mentioned your blog, or your blog got featured on Medium’s first page, etc. The number of earthquakes per year in a country also might not follow a Poisson Distribution if one large earthquake increases the probability of aftershocks. 5. Relationship between a Poisson and an Exponential distribution If the number of events per unit time follows a Poisson distribution, then the amount of time between events follows the exponential distribution. The Poisson distribution is discrete and the exponential distribution is continuous, yet the two distributions are closely related. Let’s go deeper: Exponential Distribution Intuition If you like my post, could you please clap? It gives me motivation to write more. :)
[ { "code": null, "e": 277, "s": 171, "text": "Before setting the parameter λ and plugging it into the formula, let’s pause a second and ask a question." }, { "code": null, "e": 334, "s": 277, "text": "Why did Poisson have to invent the Poisson Distribution?" }, { "code": null, "e": 395, "s": 334, "text": "Why does this distribution exist (= why did he invent this)?" }, { "code": null, "e": 437, "s": 395, "text": "When should Poisson be used for modeling?" }, { "code": null, "e": 489, "s": 437, "text": "To predict the # of events occurring in the future!" }, { "code": null, "e": 598, "s": 489, "text": "More formally, to predict the probability of a given number of events occurring in a fixed interval of time." }, { "code": null, "e": 983, "s": 598, "text": "If you’ve ever sold something, this “event” can be defined, for example, as a customer purchasing something from you (the moment of truth, not just browsing). It can be how many visitors you get on your website a day, how many clicks your ads get for the next month, how many phone calls you get during your shift, or even how many people will die from a fatal disease next year, etc." }, { "code": null, "e": 1040, "s": 983, "text": "Below is an example of how I’d use Poisson in real life." }, { "code": null, "e": 1306, "s": 1040, "text": "Every week, on average, 17 people clap for my blog post. I’d like to predict the # of ppl who would clap next week because I get paid weekly by those numbers.What is the probability that exactly 20 people (or 10, 30, 50, etc.) will clap for the blog post next week?" }, { "code": null, "e": 1464, "s": 1306, "text": "One way to solve this would be to start with the number of reads. Each person who reads the blog has some probability that they will really like it and clap." }, { "code": null, "e": 1602, "s": 1464, "text": "This is a classic job for the binomial distribution, since we are calculating the probability of the number of successful events (claps)." }, { "code": null, "e": 1752, "s": 1602, "text": "A binomial random variable is the number of successes x in n repeated trials. And we assume the probability of success p is constant over each trial." }, { "code": null, "e": 2001, "s": 1752, "text": "However, here we are given only one piece of information — 17 ppl/week, which is a “rate” (the average # of successes per week, or the expected value of x). We don’t know anything about the clapping probability p, nor the number of blog visitors n." }, { "code": null, "e": 2234, "s": 2001, "text": "Therefore, we need a little more information to tackle this problem. What more do we need to frame this probability as a binomial problem? We need two things: the probability of success (claps) p & the number of trials (visitors) n." }, { "code": null, "e": 2269, "s": 2234, "text": "Let’s get them from the past data." }, { "code": null, "e": 2373, "s": 2269, "text": "These are stats for 1 year. A total of 59k people read my blog. Out of 59k people, 888 of them clapped." }, { "code": null, "e": 2504, "s": 2373, "text": "Therefore, the # of people who read my blog per week (n) is 59k/52 = 1134. The # of people who clapped per week (x) is 888/52 =17." }, { "code": null, "e": 2649, "s": 2504, "text": "# of people who read per week (n) = 59k/52 = 1134# of people who clap per week (x) = 888/52 = 17Success probability (p) : 888/59k = 0.015 = 1.5%" }, { "code": null, "e": 3028, "s": 2649, "text": "<Binomial Probability for different x’s>╔══════╦════════════════╗║ x ║ Binomial P(X=x)║╠══════╬════════════════╣║ 10 ║ 0.02250 ║║ 17 ║ 0.09701 ║ 🡒 The average rate has the highest P!║ 20 ║ 0.06962 ║ 🡒 Nice. 20 is also quite Likely!║ 30 ║ 0.00121 ║║ 40 ║ < 0.000001 ║ 🡒 Well, I guess I won’t get 40 claps..╚══════╩════════════════╝" }, { "code": null, "e": 3085, "s": 3028, "text": "We just solved the problem with a binomial distribution." }, { "code": null, "e": 3178, "s": 3085, "text": "Then, what is Poisson for? What are the things that only Poisson can do, but Binomial can’t?" }, { "code": null, "e": 3231, "s": 3178, "text": "a) A binomial random variable is “BI-nary” — 0 or 1." }, { "code": null, "e": 3376, "s": 3231, "text": "In the above example, we have 17 ppl/wk who clapped. This means 17/7 = 2.4 people clapped per day, and 17/(7*24) = 0.1 people clapping per hour." }, { "code": null, "e": 3657, "s": 3376, "text": "If we model the success probability by hour (0.1 people/hr) using the binomial random variable, this means most of the hours get zero claps but some hours will get exactly 1 clap. However, it is also very possible that certain hours will get more than 1 clap (2, 3, 5 claps, etc.)" }, { "code": null, "e": 3831, "s": 3657, "text": "The problem with binomial is that it CANNOT contain more than 1 event in the unit of time (in this case, 1 hr is the unit time). The unit of time can only have 0 or 1 event." }, { "code": null, "e": 4033, "s": 3831, "text": "Then, how about dividing 1 hour into 60 minutes, and make unit time smaller, for example, a minute? Then 1 hour can contain multiple events. (Still, one minute will contain exactly one or zero events.)" }, { "code": null, "e": 4060, "s": 4033, "text": "Is our problem solved now?" }, { "code": null, "e": 4429, "s": 4060, "text": "Kind of. But what if, during that one minute, we get multiple claps? (i.e. someone shared your blog post on Twitter and the traffic spiked at that minute.) Then what? We can divide a minute into seconds. Then our time unit becomes a second and again a minute can contain multiple events. But this binary container problem will always exist for ever-smaller time units." }, { "code": null, "e": 4642, "s": 4429, "text": "The idea is, we can make the Binomial random variable handle multiple events by dividing a unit time into smaller units. By using smaller divisions, we can make the original unit time contain more than one event." }, { "code": null, "e": 4800, "s": 4642, "text": "Mathematically, this means n → ∞. Since we assume the rate is fixed, we must have p → 0. Because otherwise, n*p, which is the number of events, will blow up." }, { "code": null, "e": 4993, "s": 4800, "text": "Using the limit, the unit times are now infinitesimal. We no longer have to worry about more than one event occurring within the same unit time. And this is how we derive Poisson distribution." }, { "code": null, "e": 5074, "s": 4993, "text": "b) In the Binomial distribution, the # of trials (n) should be known beforehand." }, { "code": null, "e": 5602, "s": 5074, "text": "If you use Binomial, you cannot calculate the success probability only with the rate (i.e. 17 ppl/week). You need “more info” (n & p) in order to use the binomial PMF.The Poisson Distribution, on the other hand, doesn’t require you to know n or p. We are assuming n is infinitely large and p is infinitesimal. The only parameter of the Poisson distribution is the rate λ (the expected value of x). In real life, only knowing the rate (i.e., during 2pm~4pm, I received 3 phone calls) is much more common than knowing both n & p." }, { "code": null, "e": 5665, "s": 5602, "text": "Now you know where each component λ^k , k! and e^-λ come from!" }, { "code": null, "e": 5791, "s": 5665, "text": "Finally, we only need to show that the multiplication of the first two terms n!/((n-k)!*n^k) is 1 when n approaches infinity." }, { "code": null, "e": 5800, "s": 5791, "text": "It is 1." }, { "code": null, "e": 5828, "s": 5800, "text": "We got the Poisson Formula!" }, { "code": null, "e": 5879, "s": 5828, "text": "Now the Wikipedia explanation starts making sense." }, { "code": null, "e": 5951, "s": 5879, "text": "Plug your own data into the formula and see if P(x) makes sense to you!" }, { "code": null, "e": 5966, "s": 5951, "text": "Below is mine." }, { "code": null, "e": 6638, "s": 5966, "text": "< Comparison between Binomial & Poisson >╔══════╦═══════════════════╦═══════════════════════╗║ k ║ Binomial P(X=k) ║ Poisson P(X=k;λ=17) ║╠══════╬═══════════════════╬═══════════════════════╣║ 10 ║ 0.02250 ║ 0.02300 ║║ 17 ║ 0.09701 ║ 0.09628 ║║ 20 ║ 0.06962 ║ 0.07595 ║║ 30 ║ 0.00121 ║ 0.00340 ║║ 40 ║ < 0.000001 ║ < 0.000001 ║╚══════╩═══════════════════╩═══════════════════════╝* You can calculate both easily here:Binomial: https://stattrek.com/online-calculator/binomial.aspxPoisson : https://stattrek.com/online-calculator/poisson.aspx" }, { "code": null, "e": 6660, "s": 6638, "text": "A few things to note:" }, { "code": null, "e": 7081, "s": 6660, "text": "Even though the Poisson distribution models rare events, the rate λ can be any number. It doesn’t always have to be small.The Poisson Distribution is asymmetric — it is always skewed toward the right. Because it is inhibited by the zero occurrence barrier (there is no such thing as “minus one” clap) on the left and it is unlimited on the other side.As λ becomes bigger, the graph looks more like a normal distribution." }, { "code": null, "e": 7204, "s": 7081, "text": "Even though the Poisson distribution models rare events, the rate λ can be any number. It doesn’t always have to be small." }, { "code": null, "e": 7434, "s": 7204, "text": "The Poisson Distribution is asymmetric — it is always skewed toward the right. Because it is inhibited by the zero occurrence barrier (there is no such thing as “minus one” clap) on the left and it is unlimited on the other side." }, { "code": null, "e": 7504, "s": 7434, "text": "As λ becomes bigger, the graph looks more like a normal distribution." }, { "code": null, "e": 7537, "s": 7504, "text": "4. The Poisson Model Assumptions" }, { "code": null, "e": 7951, "s": 7537, "text": "a. The average rate of events per unit time is constant. This means the number of people who visit your blog per hour might not follow a Poisson Distribution, because the hourly rate is not constant (higher rate during the daytime, lower rate during the nighttime). Using monthly rate for consumer/biological data would be just an approximation as well, since the seasonality effect is non-trivial in that domain." }, { "code": null, "e": 8370, "s": 7951, "text": "b. Events are independent.The arrivals of your blog visitors might not always be independent. For example, sometimes a large number of visitors come in a group because someone popular mentioned your blog, or your blog got featured on Medium’s first page, etc. The number of earthquakes per year in a country also might not follow a Poisson Distribution if one large earthquake increases the probability of aftershocks." }, { "code": null, "e": 8436, "s": 8370, "text": "5. Relationship between a Poisson and an Exponential distribution" }, { "code": null, "e": 8715, "s": 8436, "text": "If the number of events per unit time follows a Poisson distribution, then the amount of time between events follows the exponential distribution. The Poisson distribution is discrete and the exponential distribution is continuous, yet the two distributions are closely related." }, { "code": null, "e": 8767, "s": 8715, "text": "Let’s go deeper: Exponential Distribution Intuition" } ]
Tailwind CSS Background Opacity - GeeksforGeeks
23 Mar, 2022 This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. The bg-opacity is the class of an element that describes the transparency of the element. It is the alternative to the CSS Opacity / Transparency. Background Opacity class: background-opacity-0: Control the opacity of an element’s background using the background-opacity-{amount} utilities. Note: The number of the opacity can be changeable from 0 to 100 with the span of 5. Syntax: <element class="bg-{opacity}">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center mx-4 space-y-2"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Background Opacity Class</b> <div class="mx-14 bg-green-200 grid grid-rows-4 grid-flow-col text-justify p-4"> <p class="bg-green-800 bg-opacity-100 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-green-800 bg-opacity-75 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-green-800 bg-opacity-50 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-green-800 bg-opacity-25 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-yellow-800 bg-opacity-100 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-yellow-800 bg-opacity-75 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-yellow-800 bg-opacity-50 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-yellow-800 bg-opacity-25 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-pink-800 bg-opacity-100 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-pink-800 bg-opacity-75 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-pink-800 bg-opacity-50 p-2"> A Computer Science Portal for Geeks </p> <p class="bg-pink-800 bg-opacity-25 p-2"> A Computer Science Portal for Geeks </p> </div></body> </html> Output: Background opacity class Tailwind CSS Tailwind-Background CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? 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": 37385, "s": 37357, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37636, "s": 37385, "text": "This class accepts lots of value in tailwind CSS in which all the properties are covered in class form. The bg-opacity is the class of an element that describes the transparency of the element. It is the alternative to the CSS Opacity / Transparency." }, { "code": null, "e": 37662, "s": 37636, "text": "Background Opacity class:" }, { "code": null, "e": 37780, "s": 37662, "text": "background-opacity-0: Control the opacity of an element’s background using the background-opacity-{amount} utilities." }, { "code": null, "e": 37864, "s": 37780, "text": "Note: The number of the opacity can be changeable from 0 to 100 with the span of 5." }, { "code": null, "e": 37872, "s": 37864, "text": "Syntax:" }, { "code": null, "e": 37916, "s": 37872, "text": "<element class=\"bg-{opacity}\">...</element>" }, { "code": null, "e": 37925, "s": 37916, "text": "Example:" }, { "code": null, "e": 37930, "s": 37925, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center mx-4 space-y-2\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Background Opacity Class</b> <div class=\"mx-14 bg-green-200 grid grid-rows-4 grid-flow-col text-justify p-4\"> <p class=\"bg-green-800 bg-opacity-100 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-green-800 bg-opacity-75 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-green-800 bg-opacity-50 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-green-800 bg-opacity-25 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-yellow-800 bg-opacity-100 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-yellow-800 bg-opacity-75 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-yellow-800 bg-opacity-50 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-yellow-800 bg-opacity-25 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-pink-800 bg-opacity-100 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-pink-800 bg-opacity-75 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-pink-800 bg-opacity-50 p-2\"> A Computer Science Portal for Geeks </p> <p class=\"bg-pink-800 bg-opacity-25 p-2\"> A Computer Science Portal for Geeks </p> </div></body> </html> ", "e": 39832, "s": 37930, "text": null }, { "code": null, "e": 39840, "s": 39832, "text": "Output:" }, { "code": null, "e": 39865, "s": 39840, "text": "Background opacity class" }, { "code": null, "e": 39878, "s": 39865, "text": "Tailwind CSS" }, { "code": null, "e": 39898, "s": 39878, "text": "Tailwind-Background" }, { "code": null, "e": 39902, "s": 39898, "text": "CSS" }, { "code": null, "e": 39919, "s": 39902, "text": "Web Technologies" }, { "code": null, "e": 40017, "s": 39919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40067, "s": 40017, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 40129, "s": 40067, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 40177, "s": 40129, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 40235, "s": 40177, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 40290, "s": 40235, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 40330, "s": 40290, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40363, "s": 40330, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40408, "s": 40363, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40451, "s": 40408, "text": "How to fetch data from an API in ReactJS ?" } ]
tf.transpose() function in TensorFlow - GeeksforGeeks
01 Jun, 2020 tf.transpose() is a function provided in TensorFlow. This function is used to transpose the input tensor. Syntax: tf.transpose(input_tensor, perm, conjugate) Parameters:input_tensor: as the name suggests it is the tensor which is to be transposed.Type: Tensor perm: This parameters specifies the permutation according to which the input_tensor is to be transposed.Type: Vector conjugate: This parameters is set to True if the input_tensor is of type complex.Type: Boolean Example 1: import tensorflow as geek x = geek.constant([[1, 2, 3, 4], [5, 6, 7, 8]])transposed_tensor = geek.transpose(x) Output : array([[1, 5], [2, 6], [3, 7], [4, 8]]) Example 2: With using perm parameter: When this parameter is passes the tensor is transposed along the given axis. In simple words it defines the output shape of the transposed tensor. import tensorflow as geek x = geek.constant([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [ 10, 11, 12]], [[ 13, 14, 15], [ 16, 17, 18]], [[ 19, 20, 21], [ 22, 23, 24]]])transposed_tensor = geek.transpose(x, perm = [0, 2, 1]) Output: array([[[ 1, 4], [ 2, 5], [ 3, 6]], [[ 7, 10], [ 8, 11], [ 9, 12]], [[13, 16], [14, 17], [15, 18]], [[19, 22], [20, 23], [21, 24]]]) shape (4, 3, 2) The shape is (4, 3, 2) because our perm was [0, 2, 1]. The following is the mapping from perm to input tensor shape. 0 => 4 2 => 3 1 => 2 Example 3: Now we will study the conjugate parameterIt is set to True when we have complex variables in our tensor. import tensorflow as geek x = geek.constant([[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j, 6 + 6j]])transposed_tensor = geek.transpose(x) Output: array([[1 + 1j, 4 + 4j], [2 + 2j, 5 + 5j], [3 + 3j, 6 + 6j]]) Tensorflow Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25991, "s": 25963, "text": "\n01 Jun, 2020" }, { "code": null, "e": 26097, "s": 25991, "text": "tf.transpose() is a function provided in TensorFlow. This function is used to transpose the input tensor." }, { "code": null, "e": 26149, "s": 26097, "text": "Syntax: tf.transpose(input_tensor, perm, conjugate)" }, { "code": null, "e": 26251, "s": 26149, "text": "Parameters:input_tensor: as the name suggests it is the tensor which is to be transposed.Type: Tensor" }, { "code": null, "e": 26368, "s": 26251, "text": "perm: This parameters specifies the permutation according to which the input_tensor is to be transposed.Type: Vector" }, { "code": null, "e": 26463, "s": 26368, "text": "conjugate: This parameters is set to True if the input_tensor is of type complex.Type: Boolean" }, { "code": null, "e": 26474, "s": 26463, "text": "Example 1:" }, { "code": "import tensorflow as geek x = geek.constant([[1, 2, 3, 4], [5, 6, 7, 8]])transposed_tensor = geek.transpose(x)", "e": 26606, "s": 26474, "text": null }, { "code": null, "e": 26615, "s": 26606, "text": "Output :" }, { "code": null, "e": 26677, "s": 26615, "text": "array([[1, 5],\n [2, 6],\n [3, 7],\n [4, 8]])\n" }, { "code": null, "e": 26715, "s": 26677, "text": "Example 2: With using perm parameter:" }, { "code": null, "e": 26862, "s": 26715, "text": "When this parameter is passes the tensor is transposed along the given axis. In simple words it defines the output shape of the transposed tensor." }, { "code": "import tensorflow as geek x = geek.constant([[[ 1, 2, 3], [ 4, 5, 6]], [[ 7, 8, 9], [ 10, 11, 12]], [[ 13, 14, 15], [ 16, 17, 18]], [[ 19, 20, 21], [ 22, 23, 24]]])transposed_tensor = geek.transpose(x, perm = [0, 2, 1])", "e": 27215, "s": 26862, "text": null }, { "code": null, "e": 27223, "s": 27215, "text": "Output:" }, { "code": null, "e": 27464, "s": 27223, "text": "array([[[ 1, 4],\n [ 2, 5],\n [ 3, 6]],\n\n [[ 7, 10],\n [ 8, 11],\n [ 9, 12]],\n\n [[13, 16],\n [14, 17],\n [15, 18]],\n\n [[19, 22],\n [20, 23],\n [21, 24]]])\nshape (4, 3, 2)\n" }, { "code": null, "e": 27581, "s": 27464, "text": "The shape is (4, 3, 2) because our perm was [0, 2, 1]. The following is the mapping from perm to input tensor shape." }, { "code": null, "e": 27602, "s": 27581, "text": "0 => 4\n2 => 3\n1 => 2" }, { "code": null, "e": 27718, "s": 27602, "text": "Example 3: Now we will study the conjugate parameterIt is set to True when we have complex variables in our tensor." }, { "code": "import tensorflow as geek x = geek.constant([[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j, 6 + 6j]])transposed_tensor = geek.transpose(x)", "e": 27874, "s": 27718, "text": null }, { "code": null, "e": 27882, "s": 27874, "text": "Output:" }, { "code": null, "e": 27959, "s": 27882, "text": "array([[1 + 1j, 4 + 4j],\n [2 + 2j, 5 + 5j],\n [3 + 3j, 6 + 6j]])\n" }, { "code": null, "e": 27970, "s": 27959, "text": "Tensorflow" }, { "code": null, "e": 27977, "s": 27970, "text": "Python" }, { "code": null, "e": 28075, "s": 27977, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28093, "s": 28075, "text": "Python Dictionary" }, { "code": null, "e": 28128, "s": 28093, "text": "Read a file line by line in Python" }, { "code": null, "e": 28160, "s": 28128, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28182, "s": 28160, "text": "Enumerate() in Python" }, { "code": null, "e": 28224, "s": 28182, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28254, "s": 28224, "text": "Iterate over a list in Python" }, { "code": null, "e": 28280, "s": 28254, "text": "Python String | replace()" }, { "code": null, "e": 28309, "s": 28280, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28353, "s": 28309, "text": "Reading and Writing to text files in Python" } ]
Generic Implementation of QuickSort Algorithm in C - GeeksforGeeks
24 Sep, 2018 Write a function to implement quicksort algorithm that will work for all types of data i.e ints, floats, chars etc.It should accept all types of data and show the sorted data as output. Note: This function is similar to C standard library function qsort(). Examples: First Input as a string. Input :abc cad bcd xyz bsd Output :abc bcd bsd cad xyz Second input as integer Input :5 6 4 2 3 Output :2 3 4 5 6 We use void* to implement generic quicksort function in C. void* does not know how much bytes of memory it has to occupy in memory space. It must be casted to any other data type like int*, char* before doing any operation on it.Example: when we declare int var; compiler knows that it has occupy 4 bytes of memory but void does not know how much bytes of memory it has to occupy.We will also use a pointer to function that will point to a function which is dependent to different types of data i.e and this function will be defined by the user according to there need. Below is the image representation of void* in memory before and after casting it to any particular data type for better understanding. Void* pt in Memory : void* pt casted to char* : // C Program to illustrate Generic Quicksort Function#include <stdio.h>#include <stdlib.h>#include <string.h> // function for comparing two strings. This function// is passed as a parameter to _quickSort() when we// want to sort int cmpstr(void* v1, void* v2){ // casting v1 to char** and then assigning it to // pointer to v1 as v1 is array of characters i.e // strings. char *a1 = *(char**)v1; char *a2 = *(char**)v2; return strcmp(a1, a2);} // function for comparing two stringsint cmpnum(void* s1, void* s2){ // casting s1 to int* so it can be // copied in variable a. int *a = (int*)s1; int *b = (int*)s2; if ((*a) > (*b)) return 1; else if ((*a) < (*b)) return -1; else return 0;} /* you can also write compare function for floats, chars, double similarly as integer. */// function for swap two elementsvoid swap(void* v1, void* v2, int size){ // buffer is array of characters which will // store element byte by byte char buffer[size]; // memcpy will copy the contents from starting // address of v1 to length of size in buffer // byte by byte. memcpy(buffer, v1, size); memcpy(v1, v2, size); memcpy(v2, buffer, size);} // v is an array of elements to sort.// size is the number of elements in array// left and right is start and end of array//(*comp)(void*, void*) is a pointer to a function// which accepts two void* as its parametervoid _qsort(void* v, int size, int left, int right, int (*comp)(void*, void*)){ void *vt, *v3; int i, last, mid = (left + right) / 2; if (left >= right) return; // casting void* to char* so that operations // can be done. void* vl = (char*)(v + (left * size)); void* vr = (char*)(v + (mid * size)); swap(vl, vr, size); last = left; for (i = left + 1; i <= right; i++) { // vl and vt will have the starting address // of the elements which will be passed to // comp function. vt = (char*)(v + (i * size)); if ((*comp)(vl, vt) > 0) { ++last; v3 = (char*)(v + (last * size)); swap(vt, v3, size); } } v3 = (char*)(v + (last * size)); swap(vl, v3, size); _qsort(v, size, left, last - 1, comp); _qsort(v, size, last + 1, right, comp);} int main(){ // Your C Code char* a[] = {"bbc", "xcd", "ede", "def", "afg", "hello", "hmmm", "okay", "how" }; int b[] = { 45, 78, 89, 65, 70, 23, 44 }; int* p = b; _qsort(a, sizeof(char*), 0, 8, (int (*)(void*, void*))(cmpstr)); _qsort(p, sizeof(int), 0, 6, (int (*)(void*, void*))(cmpnum)); for (int i = 0; i < 9; i++) printf("%s ", a[i]); printf("\n"); for (int i = 0; i < 7; i++) printf("%d ", b[i]); return 0;} afg bbc def ede hello hmmm how okay xcd 23 44 45 65 70 78 89 C-Functions C-Pointers Quick Sort C Programs Sorting Sorting 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 Exit codes in C/C++ with Examples C program to find the length of a string Handling multiple clients on server with multithreading using Socket Programming in C/C++
[ { "code": null, "e": 26279, "s": 26251, "text": "\n24 Sep, 2018" }, { "code": null, "e": 26465, "s": 26279, "text": "Write a function to implement quicksort algorithm that will work for all types of data i.e ints, floats, chars etc.It should accept all types of data and show the sorted data as output." }, { "code": null, "e": 26536, "s": 26465, "text": "Note: This function is similar to C standard library function qsort()." }, { "code": null, "e": 26546, "s": 26536, "text": "Examples:" }, { "code": null, "e": 26688, "s": 26546, "text": "First Input as a string.\nInput :abc cad bcd xyz bsd \nOutput :abc bcd bsd cad xyz\n\nSecond input as integer\nInput :5 6 4 2 3\nOutput :2 3 4 5 6\n" }, { "code": null, "e": 27258, "s": 26688, "text": "We use void* to implement generic quicksort function in C. void* does not know how much bytes of memory it has to occupy in memory space. It must be casted to any other data type like int*, char* before doing any operation on it.Example: when we declare int var; compiler knows that it has occupy 4 bytes of memory but void does not know how much bytes of memory it has to occupy.We will also use a pointer to function that will point to a function which is dependent to different types of data i.e and this function will be defined by the user according to there need." }, { "code": null, "e": 27393, "s": 27258, "text": "Below is the image representation of void* in memory before and after casting it to any particular data type for better understanding." }, { "code": null, "e": 27414, "s": 27393, "text": "Void* pt in Memory :" }, { "code": null, "e": 27441, "s": 27414, "text": "void* pt casted to char* :" }, { "code": "// C Program to illustrate Generic Quicksort Function#include <stdio.h>#include <stdlib.h>#include <string.h> // function for comparing two strings. This function// is passed as a parameter to _quickSort() when we// want to sort int cmpstr(void* v1, void* v2){ // casting v1 to char** and then assigning it to // pointer to v1 as v1 is array of characters i.e // strings. char *a1 = *(char**)v1; char *a2 = *(char**)v2; return strcmp(a1, a2);} // function for comparing two stringsint cmpnum(void* s1, void* s2){ // casting s1 to int* so it can be // copied in variable a. int *a = (int*)s1; int *b = (int*)s2; if ((*a) > (*b)) return 1; else if ((*a) < (*b)) return -1; else return 0;} /* you can also write compare function for floats, chars, double similarly as integer. */// function for swap two elementsvoid swap(void* v1, void* v2, int size){ // buffer is array of characters which will // store element byte by byte char buffer[size]; // memcpy will copy the contents from starting // address of v1 to length of size in buffer // byte by byte. memcpy(buffer, v1, size); memcpy(v1, v2, size); memcpy(v2, buffer, size);} // v is an array of elements to sort.// size is the number of elements in array// left and right is start and end of array//(*comp)(void*, void*) is a pointer to a function// which accepts two void* as its parametervoid _qsort(void* v, int size, int left, int right, int (*comp)(void*, void*)){ void *vt, *v3; int i, last, mid = (left + right) / 2; if (left >= right) return; // casting void* to char* so that operations // can be done. void* vl = (char*)(v + (left * size)); void* vr = (char*)(v + (mid * size)); swap(vl, vr, size); last = left; for (i = left + 1; i <= right; i++) { // vl and vt will have the starting address // of the elements which will be passed to // comp function. vt = (char*)(v + (i * size)); if ((*comp)(vl, vt) > 0) { ++last; v3 = (char*)(v + (last * size)); swap(vt, v3, size); } } v3 = (char*)(v + (last * size)); swap(vl, v3, size); _qsort(v, size, left, last - 1, comp); _qsort(v, size, last + 1, right, comp);} int main(){ // Your C Code char* a[] = {\"bbc\", \"xcd\", \"ede\", \"def\", \"afg\", \"hello\", \"hmmm\", \"okay\", \"how\" }; int b[] = { 45, 78, 89, 65, 70, 23, 44 }; int* p = b; _qsort(a, sizeof(char*), 0, 8, (int (*)(void*, void*))(cmpstr)); _qsort(p, sizeof(int), 0, 6, (int (*)(void*, void*))(cmpnum)); for (int i = 0; i < 9; i++) printf(\"%s \", a[i]); printf(\"\\n\"); for (int i = 0; i < 7; i++) printf(\"%d \", b[i]); return 0;}", "e": 30242, "s": 27441, "text": null }, { "code": null, "e": 30305, "s": 30242, "text": "afg bbc def ede hello hmmm how okay xcd \n23 44 45 65 70 78 89\n" }, { "code": null, "e": 30317, "s": 30305, "text": "C-Functions" }, { "code": null, "e": 30328, "s": 30317, "text": "C-Pointers" }, { "code": null, "e": 30339, "s": 30328, "text": "Quick Sort" }, { "code": null, "e": 30350, "s": 30339, "text": "C Programs" }, { "code": null, "e": 30358, "s": 30350, "text": "Sorting" }, { "code": null, "e": 30366, "s": 30358, "text": "Sorting" }, { "code": null, "e": 30464, "s": 30366, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30505, "s": 30464, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 30536, "s": 30505, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 30570, "s": 30536, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 30611, "s": 30570, "text": "C program to find the length of a string" } ]
Iterator Interface In Java - GeeksforGeeks
09 Nov, 2020 Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and perform operations on each element. Iterator is a universal iterator as it can be applied to any Collection object. We can traverse only in the forward direction using iterator. Using ListIterator which extends Iterator, can traverse in both directions. Both read and remove operations can be performed by the iterator interface. This is included in Java JDK 1.2. The only Enumeration is the first iterator to be included in JDK 1.0. To use an iterator, we must import java.util package. Limitations of Enumeration Interface: An Iterator interface is used in place of Enumeration in Java Collection. Enumeration is not a universal iterator and is used for legacy classes like Vector, Hashtable only. Iterator allows the caller to remove elements from the given collection during iterating over the elements. Only forward direction iteration is possible in an Enumeration. Declaration of iterator interface public interface Iterator<E> E – the type of elements returned by this iterator EventIterator: public interface EventIterator extends Iterator<Event> EventIterators are unmodifiable. Methods: nextEvent() which returns the next Event in an EventSet. ListIterator<E>: public interface ListIterator<E> extends Iterator<E> An Iterator for lists which allows to traverse the list in either of the forward or backward direction or modify the list during the iteration and to obtain the current position of the iterator. ListIterator has no current element. PrimitiveIterator<T,T_CONS>, PrimitiveIterator.OfInt, PrimitiveIterator.OfLong Implementing Classes: BeanContextSupport.BCSIterator EventReaderDelegate Scanner Example: Implementation of Iterator All classes in the Collection Framework provide iterator() method which returns the instance of Iterator to iterate over the elements in that collection. Java // Java program to show the usage of Iterator()import java.util.Iterator;import java.util.LinkedList;import java.util.List;public class JavaIteratorExample1 { public static void main(String[] args) { // create a list List<String> list = new LinkedList<>(); list.add("Welcome"); list.add("to"); list.add("GFG"); System.out.println("The list is given as : " + list); // get the iterator on the list Iterator<String> itr = list.iterator(); // Returns true if there are more number of // elements. while (itr.hasNext()) { // Returns the next element. System.out.println(itr.next()); } // Removes the last element. itr.remove(); System.out.println( "After the remove() method is called : " + list); }} The list is given as : [Welcome, to, GFG] Welcome to GFG After the remove() method is called : [Welcome, to] ArrayList Iterator Example Java // Java program to iterate over an arraylist// using Iteratorimport java.util.*;class GFG { public static void main(String[] args) { // initializing ArrayList List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80); // Looping ArrayList using Iterator Iterator it = numbers.iterator(); while (it.hasNext()) System.out.print(it.next() + " "); }} 10 20 30 40 50 60 70 80 Develop Custom Class Iterator To provide similar functionality for user-defined /custom class, we should follow the below steps: Define a custom class. Define the collection class to this custom class. The collection class should import java.util package and implement iterable interface. This collection class should now provide implementation to Iterable interface’s method iterator(). Example code of developing custom class: Java // java program to show the creation of// custom class that implements iterable interfaceimport java.util.*;import java.io.*;class Employees implements Iterable { List<String> str = null; public Employees() { str = new ArrayList<String>(); str.add("practice"); str.add("geeks"); str.add("for"); str.add("geeks"); str.add("to"); str.add("learn"); str.add("coding"); } // if we are implementing Iterable interface, the we // need to define the iterator() method of Iterable // interface @Override public Iterator<String> iterator() { return str.iterator(); }} public class EmployeesTester { public static void main(String[] args) { Employees emps = new Employees(); for (String st : emps.str) { System.out.println(st); } }} practice geeks for geeks to learn coding Using remove() method to remove items from a collection It removes the last element of the collection returned by the iterator. If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, an Iterator will throw a ConcurrentModificationException. Java // java program to remove()// elements from a collection import java.util.ArrayList;import java.util.Iterator; public class MyClass { public static void main(String[] args) { // create a list of Integers ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(12); numbers.add(8); numbers.add(2); numbers.add(23); // get the iterator on the list Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { // gives the next element // and iterator moves to next // element Integer i = it.next(); if (i < 10) { // removes the current element it.remove(); } } System.out.println(numbers); }} [12, 23] Iterator forEachRemaining() Example Java // Java program to show the usage of// Iterator forEachRemaining()import java.util.*;class GFG { public static void main(String[] args) { // initializing ArrayList List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80); numbers.iterator().forEachRemaining( System.out::println); }} 10 20 30 40 50 60 70 80 Advantages of Java Iterator: It is not a legacy interface and can traverse overall collections like ArrayList, HashMap, TreeSet, HashSet etc.It can be used for any java collection and therefore known as Universal Cursor for Collection API.Read and Remove operations are supported.Simple and easily usable method names. It is not a legacy interface and can traverse overall collections like ArrayList, HashMap, TreeSet, HashSet etc. It can be used for any java collection and therefore known as Universal Cursor for Collection API. Read and Remove operations are supported. Simple and easily usable method names. Limitations of Java Iterator: It does not support Create and Update operations in CRUD (Create, Read, Update, Delete) operations.It supports only uni-directional traversal i.e in forwarding direction.It does not support a better iteration on a large volume of data in comparison to Spliterator.It supports only sequential iteration i.e it does not support iterating elements parallel. It does not support Create and Update operations in CRUD (Create, Read, Update, Delete) operations. It supports only uni-directional traversal i.e in forwarding direction. It does not support a better iteration on a large volume of data in comparison to Spliterator. It supports only sequential iteration i.e it does not support iterating elements parallel. Difference between Iterator and Enumeration: Iterator Enumeration Methods: Methods If iteration has more elements, then it returns true. If the iterator has gone through all the elements, it returns false It returns the next element of iteration. It throws NoSuchElementException if the iterator has no more elements. It removes the last element of the collection returned by the iterator. If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, iterator will throw an ConcurrentModificationException. It performs the given action for each remaining element until all elements have been processed. If the order is specified, the actions are performed in the order of iteration. It throws NullPointerException if the action is null. Java-Iterator Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25249, "s": 25221, "text": "\n09 Nov, 2020" }, { "code": null, "e": 25967, "s": 25249, "text": "Java Iterator Interface of java collections allows us to access elements of the collection and is used to iterate over the elements in the collection(Map, List or Set). It helps to easily retrieve the elements of a collection and perform operations on each element. Iterator is a universal iterator as it can be applied to any Collection object. We can traverse only in the forward direction using iterator. Using ListIterator which extends Iterator, can traverse in both directions. Both read and remove operations can be performed by the iterator interface. This is included in Java JDK 1.2. The only Enumeration is the first iterator to be included in JDK 1.0. To use an iterator, we must import java.util package." }, { "code": null, "e": 26005, "s": 25967, "text": "Limitations of Enumeration Interface:" }, { "code": null, "e": 26080, "s": 26005, "text": "An Iterator interface is used in place of Enumeration in Java Collection. " }, { "code": null, "e": 26180, "s": 26080, "text": "Enumeration is not a universal iterator and is used for legacy classes like Vector, Hashtable only." }, { "code": null, "e": 26288, "s": 26180, "text": "Iterator allows the caller to remove elements from the given collection during iterating over the elements." }, { "code": null, "e": 26352, "s": 26288, "text": "Only forward direction iteration is possible in an Enumeration." }, { "code": null, "e": 26386, "s": 26352, "text": "Declaration of iterator interface" }, { "code": null, "e": 26416, "s": 26386, "text": "public interface Iterator<E>\n" }, { "code": null, "e": 26467, "s": 26416, "text": "E – the type of elements returned by this iterator" }, { "code": null, "e": 26483, "s": 26467, "text": "EventIterator: " }, { "code": null, "e": 26539, "s": 26483, "text": "public interface EventIterator extends Iterator<Event>\n" }, { "code": null, "e": 26572, "s": 26539, "text": "EventIterators are unmodifiable." }, { "code": null, "e": 26638, "s": 26572, "text": "Methods: nextEvent() which returns the next Event in an EventSet." }, { "code": null, "e": 26655, "s": 26638, "text": "ListIterator<E>:" }, { "code": null, "e": 26709, "s": 26655, "text": "public interface ListIterator<E> extends Iterator<E>\n" }, { "code": null, "e": 26941, "s": 26709, "text": "An Iterator for lists which allows to traverse the list in either of the forward or backward direction or modify the list during the iteration and to obtain the current position of the iterator. ListIterator has no current element." }, { "code": null, "e": 27020, "s": 26941, "text": "PrimitiveIterator<T,T_CONS>, PrimitiveIterator.OfInt, PrimitiveIterator.OfLong" }, { "code": null, "e": 27042, "s": 27020, "text": "Implementing Classes:" }, { "code": null, "e": 27073, "s": 27042, "text": "BeanContextSupport.BCSIterator" }, { "code": null, "e": 27093, "s": 27073, "text": "EventReaderDelegate" }, { "code": null, "e": 27101, "s": 27093, "text": "Scanner" }, { "code": null, "e": 27137, "s": 27101, "text": "Example: Implementation of Iterator" }, { "code": null, "e": 27291, "s": 27137, "text": "All classes in the Collection Framework provide iterator() method which returns the instance of Iterator to iterate over the elements in that collection." }, { "code": null, "e": 27296, "s": 27291, "text": "Java" }, { "code": "// Java program to show the usage of Iterator()import java.util.Iterator;import java.util.LinkedList;import java.util.List;public class JavaIteratorExample1 { public static void main(String[] args) { // create a list List<String> list = new LinkedList<>(); list.add(\"Welcome\"); list.add(\"to\"); list.add(\"GFG\"); System.out.println(\"The list is given as : \" + list); // get the iterator on the list Iterator<String> itr = list.iterator(); // Returns true if there are more number of // elements. while (itr.hasNext()) { // Returns the next element. System.out.println(itr.next()); } // Removes the last element. itr.remove(); System.out.println( \"After the remove() method is called : \" + list); }}", "e": 28199, "s": 27296, "text": null }, { "code": null, "e": 28308, "s": 28199, "text": "The list is given as : [Welcome, to, GFG]\nWelcome\nto\nGFG\nAfter the remove() method is called : [Welcome, to]" }, { "code": null, "e": 28335, "s": 28308, "text": "ArrayList Iterator Example" }, { "code": null, "e": 28340, "s": 28335, "text": "Java" }, { "code": "// Java program to iterate over an arraylist// using Iteratorimport java.util.*;class GFG { public static void main(String[] args) { // initializing ArrayList List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80); // Looping ArrayList using Iterator Iterator it = numbers.iterator(); while (it.hasNext()) System.out.print(it.next() + \" \"); }}", "e": 28767, "s": 28340, "text": null }, { "code": null, "e": 28792, "s": 28767, "text": "10 20 30 40 50 60 70 80 " }, { "code": null, "e": 28822, "s": 28792, "text": "Develop Custom Class Iterator" }, { "code": null, "e": 28921, "s": 28822, "text": "To provide similar functionality for user-defined /custom class, we should follow the below steps:" }, { "code": null, "e": 28944, "s": 28921, "text": "Define a custom class." }, { "code": null, "e": 28994, "s": 28944, "text": "Define the collection class to this custom class." }, { "code": null, "e": 29081, "s": 28994, "text": "The collection class should import java.util package and implement iterable interface." }, { "code": null, "e": 29180, "s": 29081, "text": "This collection class should now provide implementation to Iterable interface’s method iterator()." }, { "code": null, "e": 29221, "s": 29180, "text": "Example code of developing custom class:" }, { "code": null, "e": 29226, "s": 29221, "text": "Java" }, { "code": "// java program to show the creation of// custom class that implements iterable interfaceimport java.util.*;import java.io.*;class Employees implements Iterable { List<String> str = null; public Employees() { str = new ArrayList<String>(); str.add(\"practice\"); str.add(\"geeks\"); str.add(\"for\"); str.add(\"geeks\"); str.add(\"to\"); str.add(\"learn\"); str.add(\"coding\"); } // if we are implementing Iterable interface, the we // need to define the iterator() method of Iterable // interface @Override public Iterator<String> iterator() { return str.iterator(); }} public class EmployeesTester { public static void main(String[] args) { Employees emps = new Employees(); for (String st : emps.str) { System.out.println(st); } }}", "e": 30087, "s": 29226, "text": null }, { "code": null, "e": 30128, "s": 30087, "text": "practice\ngeeks\nfor\ngeeks\nto\nlearn\ncoding" }, { "code": null, "e": 30184, "s": 30128, "text": "Using remove() method to remove items from a collection" }, { "code": null, "e": 30256, "s": 30184, "text": "It removes the last element of the collection returned by the iterator." }, { "code": null, "e": 30427, "s": 30256, "text": "If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, an Iterator will throw a ConcurrentModificationException." }, { "code": null, "e": 30432, "s": 30427, "text": "Java" }, { "code": "// java program to remove()// elements from a collection import java.util.ArrayList;import java.util.Iterator; public class MyClass { public static void main(String[] args) { // create a list of Integers ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(12); numbers.add(8); numbers.add(2); numbers.add(23); // get the iterator on the list Iterator<Integer> it = numbers.iterator(); while (it.hasNext()) { // gives the next element // and iterator moves to next // element Integer i = it.next(); if (i < 10) { // removes the current element it.remove(); } } System.out.println(numbers); }}", "e": 31298, "s": 30432, "text": null }, { "code": null, "e": 31307, "s": 31298, "text": "[12, 23]" }, { "code": null, "e": 31343, "s": 31307, "text": "Iterator forEachRemaining() Example" }, { "code": null, "e": 31348, "s": 31343, "text": "Java" }, { "code": "// Java program to show the usage of// Iterator forEachRemaining()import java.util.*;class GFG { public static void main(String[] args) { // initializing ArrayList List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80); numbers.iterator().forEachRemaining( System.out::println); }}", "e": 31700, "s": 31348, "text": null }, { "code": null, "e": 31725, "s": 31700, "text": "10\n20\n30\n40\n50\n60\n70\n80\n" }, { "code": null, "e": 31754, "s": 31725, "text": "Advantages of Java Iterator:" }, { "code": null, "e": 32044, "s": 31754, "text": "It is not a legacy interface and can traverse overall collections like ArrayList, HashMap, TreeSet, HashSet etc.It can be used for any java collection and therefore known as Universal Cursor for Collection API.Read and Remove operations are supported.Simple and easily usable method names." }, { "code": null, "e": 32157, "s": 32044, "text": "It is not a legacy interface and can traverse overall collections like ArrayList, HashMap, TreeSet, HashSet etc." }, { "code": null, "e": 32256, "s": 32157, "text": "It can be used for any java collection and therefore known as Universal Cursor for Collection API." }, { "code": null, "e": 32298, "s": 32256, "text": "Read and Remove operations are supported." }, { "code": null, "e": 32337, "s": 32298, "text": "Simple and easily usable method names." }, { "code": null, "e": 32367, "s": 32337, "text": "Limitations of Java Iterator:" }, { "code": null, "e": 32722, "s": 32367, "text": "It does not support Create and Update operations in CRUD (Create, Read, Update, Delete) operations.It supports only uni-directional traversal i.e in forwarding direction.It does not support a better iteration on a large volume of data in comparison to Spliterator.It supports only sequential iteration i.e it does not support iterating elements parallel." }, { "code": null, "e": 32822, "s": 32722, "text": "It does not support Create and Update operations in CRUD (Create, Read, Update, Delete) operations." }, { "code": null, "e": 32894, "s": 32822, "text": "It supports only uni-directional traversal i.e in forwarding direction." }, { "code": null, "e": 32989, "s": 32894, "text": "It does not support a better iteration on a large volume of data in comparison to Spliterator." }, { "code": null, "e": 33080, "s": 32989, "text": "It supports only sequential iteration i.e it does not support iterating elements parallel." }, { "code": null, "e": 33125, "s": 33080, "text": "Difference between Iterator and Enumeration:" }, { "code": null, "e": 33134, "s": 33125, "text": "Iterator" }, { "code": null, "e": 33146, "s": 33134, "text": "Enumeration" }, { "code": null, "e": 33155, "s": 33146, "text": "Methods:" }, { "code": null, "e": 33211, "s": 33155, "text": " Methods " }, { "code": null, "e": 33265, "s": 33211, "text": "If iteration has more elements, then it returns true." }, { "code": null, "e": 33333, "s": 33265, "text": "If the iterator has gone through all the elements, it returns false" }, { "code": null, "e": 33375, "s": 33333, "text": "It returns the next element of iteration." }, { "code": null, "e": 33446, "s": 33375, "text": "It throws NoSuchElementException if the iterator has no more elements." }, { "code": null, "e": 33518, "s": 33446, "text": "It removes the last element of the collection returned by the iterator." }, { "code": null, "e": 33687, "s": 33518, "text": "If the iteration is in progress and meanwhile underlying collection is modified then by calling remove() method, iterator will throw an ConcurrentModificationException." }, { "code": null, "e": 33783, "s": 33687, "text": "It performs the given action for each remaining element until all elements have been processed." }, { "code": null, "e": 33863, "s": 33783, "text": "If the order is specified, the actions are performed in the order of iteration." }, { "code": null, "e": 33917, "s": 33863, "text": "It throws NullPointerException if the action is null." }, { "code": null, "e": 33931, "s": 33917, "text": "Java-Iterator" }, { "code": null, "e": 33936, "s": 33931, "text": "Java" }, { "code": null, "e": 33941, "s": 33936, "text": "Java" }, { "code": null, "e": 34039, "s": 33941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34054, "s": 34039, "text": "Stream In Java" }, { "code": null, "e": 34075, "s": 34054, "text": "Constructors in Java" }, { "code": null, "e": 34094, "s": 34075, "text": "Exceptions in Java" }, { "code": null, "e": 34124, "s": 34094, "text": "Functional Interfaces in Java" }, { "code": null, "e": 34170, "s": 34124, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 34187, "s": 34170, "text": "Generics in Java" }, { "code": null, "e": 34208, "s": 34187, "text": "Introduction to Java" }, { "code": null, "e": 34251, "s": 34208, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 34287, "s": 34251, "text": "Internal Working of HashMap in Java" } ]
Draw Spiraling Square using Turtle in Python - GeeksforGeeks
18 Aug, 2020 Prerequisite: Python Turtle Basic Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle, methods defined in the turtle module and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen). To move turtle(pen) there are some functions i.e forward(), backward(), etc. Approach to draw a Spiraling Square of size n: Import turtle and create a turtle instance. Using for loop(i = 0 to i < n * 4) and repeat below stepturtle.forward(i * 10).turtle.right(90). turtle.forward(i * 10). turtle.right(90). Close the turtle instance. Below is the implementation: Python3 # importing turtle moduleimport turtle # size n = 10 # creating instance of turtlepen = turtle.Turtle() # loop to draw a sidefor i in range(n * 4): # drawing side of # length i*10 pen.forward(i * 10) # changing direction of pen # by 90 degree in clockwise pen.right(90) # closing the instanceturtle.done() Output: Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Get unique values from a list Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25581, "s": 25553, "text": "\n18 Aug, 2020" }, { "code": null, "e": 25615, "s": 25581, "text": "Prerequisite: Python Turtle Basic" }, { "code": null, "e": 25918, "s": 25615, "text": "Turtle is an inbuilt module of python. It enables us to draw any drawing by a turtle, methods defined in the turtle module and by using some logical loops. To draw something on the screen(cardboard) just move the turtle(pen). To move turtle(pen) there are some functions i.e forward(), backward(), etc." }, { "code": null, "e": 25967, "s": 25918, "text": "Approach to draw a Spiraling Square of size n: " }, { "code": null, "e": 26011, "s": 25967, "text": "Import turtle and create a turtle instance." }, { "code": null, "e": 26108, "s": 26011, "text": "Using for loop(i = 0 to i < n * 4) and repeat below stepturtle.forward(i * 10).turtle.right(90)." }, { "code": null, "e": 26132, "s": 26108, "text": "turtle.forward(i * 10)." }, { "code": null, "e": 26150, "s": 26132, "text": "turtle.right(90)." }, { "code": null, "e": 26177, "s": 26150, "text": "Close the turtle instance." }, { "code": null, "e": 26206, "s": 26177, "text": "Below is the implementation:" }, { "code": null, "e": 26214, "s": 26206, "text": "Python3" }, { "code": "# importing turtle moduleimport turtle # size n = 10 # creating instance of turtlepen = turtle.Turtle() # loop to draw a sidefor i in range(n * 4): # drawing side of # length i*10 pen.forward(i * 10) # changing direction of pen # by 90 degree in clockwise pen.right(90) # closing the instanceturtle.done()", "e": 26552, "s": 26214, "text": null }, { "code": null, "e": 26560, "s": 26552, "text": "Output:" }, { "code": null, "e": 26574, "s": 26560, "text": "Python-turtle" }, { "code": null, "e": 26581, "s": 26574, "text": "Python" }, { "code": null, "e": 26679, "s": 26581, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26711, "s": 26679, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26753, "s": 26711, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26795, "s": 26753, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26851, "s": 26795, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26878, "s": 26851, "text": "Python Classes and Objects" }, { "code": null, "e": 26909, "s": 26878, "text": "Python | os.path.join() method" }, { "code": null, "e": 26948, "s": 26909, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26977, "s": 26948, "text": "Create a directory in Python" }, { "code": null, "e": 26999, "s": 26977, "text": "Defaultdict in Python" } ]
Logical Not ! operator in C with Examples - GeeksforGeeks
15 Oct, 2019 ! is a type of Logical Operator and is read as “NOT” or “Logical NOT“. This operator is used to perform “logical NOT” operation, i.e. the function similar to Inverter gate in digital electronics. Syntax: !Condition // returns true if the conditions is false // else returns false Below is an example to demonstrate ! operator: Example: // C program to demonstrate working// of logical NOT '!' operators #include <stdio.h> int main(){ // Taking a variable a // and set it to 0 (false) int a = 0; // logical NOT example // Since 0 is considered to be false // !a will yield true if (!a) printf("Condition yielded True\n"); else printf("Condition yielded False\n"); // set a to non-zero value (true) a = 1; // Since a non-zero value is considered to be true // !a will yield false if (!a) printf("Condition yielded True\n"); else printf("Condition yielded False\n"); return 0;} Condition yielded True Condition yielded False C-Operators 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": 25478, "s": 25450, "text": "\n15 Oct, 2019" }, { "code": null, "e": 25674, "s": 25478, "text": "! is a type of Logical Operator and is read as “NOT” or “Logical NOT“. This operator is used to perform “logical NOT” operation, i.e. the function similar to Inverter gate in digital electronics." }, { "code": null, "e": 25682, "s": 25674, "text": "Syntax:" }, { "code": null, "e": 25760, "s": 25682, "text": "!Condition\n\n// returns true if the conditions is false\n// else returns false\n" }, { "code": null, "e": 25807, "s": 25760, "text": "Below is an example to demonstrate ! operator:" }, { "code": null, "e": 25816, "s": 25807, "text": "Example:" }, { "code": "// C program to demonstrate working// of logical NOT '!' operators #include <stdio.h> int main(){ // Taking a variable a // and set it to 0 (false) int a = 0; // logical NOT example // Since 0 is considered to be false // !a will yield true if (!a) printf(\"Condition yielded True\\n\"); else printf(\"Condition yielded False\\n\"); // set a to non-zero value (true) a = 1; // Since a non-zero value is considered to be true // !a will yield false if (!a) printf(\"Condition yielded True\\n\"); else printf(\"Condition yielded False\\n\"); return 0;}", "e": 26442, "s": 25816, "text": null }, { "code": null, "e": 26490, "s": 26442, "text": "Condition yielded True\nCondition yielded False\n" }, { "code": null, "e": 26502, "s": 26490, "text": "C-Operators" }, { "code": null, "e": 26513, "s": 26502, "text": "C Language" }, { "code": null, "e": 26611, "s": 26513, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26649, "s": 26611, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 26675, "s": 26649, "text": "Exception Handling in C++" }, { "code": null, "e": 26695, "s": 26675, "text": "Multithreading in C" }, { "code": null, "e": 26717, "s": 26695, "text": "'this' pointer in C++" }, { "code": null, "e": 26758, "s": 26717, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26787, "s": 26758, "text": "Ways to copy a vector in C++" }, { "code": null, "e": 26829, "s": 26787, "text": "Smart Pointers in C++ and How to Use Them" }, { "code": null, "e": 26857, "s": 26829, "text": "Multiple Inheritance in C++" }, { "code": null, "e": 26893, "s": 26857, "text": "Understanding \"extern\" keyword in C" } ]
Maximum LCM among all pairs (i, j) from the given Array - GeeksforGeeks
15 Jun, 2021 Given an array arr[], the task is to find the maximum LCM when the elements of the array are taken in pairs. Examples: Input: arr[] = {17, 3, 8, 6} Output: 136 Explanation: Respective Pairs with their LCM are: {8, 17} has LCM 136, {3, 17} has LCM 51, {6, 17} has LCM 102, {3, 8} has LCM 24, {3, 6} has LCM 6, and {6, 8} has LCM 24. Maximum LCM among these =136. Input: array[] = {1, 8, 12, 9} Output: 72 Explanation: 72 is the highest LCM among all the pairs of the given array. Naive Approach: Use two loops to generate all possible pairs of elements of the array and calculate LCM of them. Update the LCM whenever we get a higher value. Time Complexity: O(N2) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the maximum// LCM of pairs in an array #include <bits/stdc++.h>using namespace std; // Function comparing all LCM pairsint maxLcmOfPairs(int arr[], int n){ // To store the highest LCM int maxLCM = -1; // To generate all pairs from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM;} // Driver codeint main(){ int arr[] = { 17, 3, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxLcmOfPairs(arr, n); return 0;} // Java implementation to find the maximum// LCM of pairs in an arrayimport java.util.*;class GFG { // Function comparing all LCM pairs static int maxLcmOfPairs(int arr[], int n) { // To store the highest LCM int maxLCM = -1; // To generate all pairs from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void main(String[] args) { int arr[] = { 17, 3, 8, 6 }; int n = arr.length; System.out.print(maxLcmOfPairs(arr, n)); }} // This code is contributed by sapnasingh4991 # Python3 implementation to find the# maximum LCM of pairs in an arrayfrom math import gcd # Function comparing all LCM pairs def maxLcmOfPairs(arr, n): # To store the highest LCM maxLCM = -1 # To generate all pairs from array for i in range(n): for j in range(i + 1, n, 1): # Find LCM of the pair # Update the maxLCM if this is # greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) // gcd(arr[i], arr[j])) # Return the highest value of LCM return maxLCM # Driver codeif __name__ == '__main__': arr = [17, 3, 8, 6] n = len(arr) print(maxLcmOfPairs(arr, n)) # This code is contributed by hupendraSingh // C# implementation to find the maximum// LCM of pairs in an arrayusing System;class GFG { // Function comparing all LCM pairs static int maxLcmOfPairs(int[] arr, int n) { // To store the highest LCM int maxLCM = -1; // To generate all pairs from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.Max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void Main() { int[] arr = { 17, 3, 8, 6 }; int n = arr.Length; Console.Write(maxLcmOfPairs(arr, n)); }} // This code is contributed by Code_Mech <script>// javascript implementation to find the maximum// LCM of pairs in an array // Function comparing all LCM pairs function maxLcmOfPairs(arr , n) { // To store the highest LCM var maxLCM = -1; // To generate all pairs from array for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max(maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code var arr = [ 17, 3, 8, 6 ]; var n = arr.length; document.write(maxLcmOfPairs(arr, n)); // This code is contributed by umadevi9616</script> 136 Another Approach:We can use Greedy Method. For applying the greedy approach we have to sort the given array and then comparing LCM of pairs of elements of the array and finally compute the maximum value of LCM. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the maximum// LCM of pairs in an array #include <bits/stdc++.h>using namespace std; // Function for the highest value of LCM pairsint greedyLCM(int arr[], int n){ // Sort the given array sort(arr, arr + n); // Compute the highest LCM int maxLCM = arr[n - 1]; for (int i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for (int j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // return the maximum lcm return maxLCM;} // Driver codeint main(){ int arr[] = { 17, 3, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << greedyLCM(arr, n); return 0;} // Java implementation to find the// maximum LCM of pairs in an arrayimport java.util.*; class GFG { // Function for the highest value // of LCM pairs static int greedyLCM(int arr[], int n) { // Sort the given array Arrays.sort(arr); // Compute the highest LCM int maxLCM = arr[n - 1]; for (int i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for (int j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the maximum lcm return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void main(String[] args) { int arr[] = { 17, 3, 8, 6 }; int n = arr.length; System.out.print(greedyLCM(arr, n)); }} // This code is contributed by Amit Katiyar # Python3 implementation to# find the maximum LCM of# pairs in an arrayfrom math import gcd # Function for the highest# value of LCM pairs def greedyLCM(arr, n): # Sort the given array arr.sort() # Compute the highest LCM maxLCM = arr[n - 1] for i in range(n - 1, -1, -1): if (arr[i] * arr[i] < maxLCM): break for j in range(i - 1, -1, -1): if (arr[i] * arr[j] < maxLCM): break else: # Find LCM of the pair # Update the maxLCM if this is # greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) // gcd(arr[i], arr[j])) # Return the maximum lcm return maxLCM # Driver codearr = [17, 3, 8, 6]n = len(arr) print(greedyLCM(arr, n)) # This code is contributed by divyeshrabadiya07 // C# implementation to find the// maximum LCM of pairs in an arrayusing System; class GFG { // Function for the highest value // of LCM pairs static int greedyLCM(int[] arr, int n) { // Sort the given array Array.Sort(arr); // Compute the highest LCM int maxLCM = arr[n - 1]; for (int i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for (int j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.Max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the maximum lcm return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void Main(String[] args) { int[] arr = { 17, 3, 8, 6 }; int n = arr.Length; Console.Write(greedyLCM(arr, n)); }} // This code is contributed by Amit Katiyar <script> // Javascript implementation to find the// maximum LCM of pairs in an array // Function for the highest value// of LCM pairsfunction greedyLCM(arr, n){ // Sort the given array arr.sort(function(a, b){return a - b}); // Compute the highest LCM let maxLCM = arr[n - 1]; for(let i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for(let j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max(maxLCM, parseInt((arr[i] * arr[j]) / __gcd(arr[i], arr[j]), 10)); } } // Return the maximum lcm return maxLCM;} function __gcd(a, b){ return b == 0 ? a : __gcd(b, a % b);} // Driver codelet arr = [ 17, 3, 8, 6 ];let n = arr.length; document.write(greedyLCM(arr, n)); // This code is contributed by mukesh07 </script> 136 Time Complexity: O(N2) bgangwar59 sapnasingh4991 Code_Mech amit143katiyar divyeshrabadiya07 cscyuger umadevi9616 mukesh07 Algorithms Arrays Competitive Programming Arrays 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": 25961, "s": 25933, "text": "\n15 Jun, 2021" }, { "code": null, "e": 26070, "s": 25961, "text": "Given an array arr[], the task is to find the maximum LCM when the elements of the array are taken in pairs." }, { "code": null, "e": 26080, "s": 26070, "text": "Examples:" }, { "code": null, "e": 26323, "s": 26080, "text": "Input: arr[] = {17, 3, 8, 6} Output: 136 Explanation: Respective Pairs with their LCM are: {8, 17} has LCM 136, {3, 17} has LCM 51, {6, 17} has LCM 102, {3, 8} has LCM 24, {3, 6} has LCM 6, and {6, 8} has LCM 24. Maximum LCM among these =136." }, { "code": null, "e": 26441, "s": 26323, "text": "Input: array[] = {1, 8, 12, 9} Output: 72 Explanation: 72 is the highest LCM among all the pairs of the given array. " }, { "code": null, "e": 26624, "s": 26441, "text": "Naive Approach: Use two loops to generate all possible pairs of elements of the array and calculate LCM of them. Update the LCM whenever we get a higher value. Time Complexity: O(N2)" }, { "code": null, "e": 26676, "s": 26624, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26680, "s": 26676, "text": "C++" }, { "code": null, "e": 26685, "s": 26680, "text": "Java" }, { "code": null, "e": 26693, "s": 26685, "text": "Python3" }, { "code": null, "e": 26696, "s": 26693, "text": "C#" }, { "code": null, "e": 26707, "s": 26696, "text": "Javascript" }, { "code": "// C++ implementation to find the maximum// LCM of pairs in an array #include <bits/stdc++.h>using namespace std; // Function comparing all LCM pairsint maxLcmOfPairs(int arr[], int n){ // To store the highest LCM int maxLCM = -1; // To generate all pairs from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM;} // Driver codeint main(){ int arr[] = { 17, 3, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << maxLcmOfPairs(arr, n); return 0;}", "e": 27528, "s": 26707, "text": null }, { "code": "// Java implementation to find the maximum// LCM of pairs in an arrayimport java.util.*;class GFG { // Function comparing all LCM pairs static int maxLcmOfPairs(int arr[], int n) { // To store the highest LCM int maxLCM = -1; // To generate all pairs from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void main(String[] args) { int arr[] = { 17, 3, 8, 6 }; int n = arr.length; System.out.print(maxLcmOfPairs(arr, n)); }} // This code is contributed by sapnasingh4991", "e": 28588, "s": 27528, "text": null }, { "code": "# Python3 implementation to find the# maximum LCM of pairs in an arrayfrom math import gcd # Function comparing all LCM pairs def maxLcmOfPairs(arr, n): # To store the highest LCM maxLCM = -1 # To generate all pairs from array for i in range(n): for j in range(i + 1, n, 1): # Find LCM of the pair # Update the maxLCM if this is # greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) // gcd(arr[i], arr[j])) # Return the highest value of LCM return maxLCM # Driver codeif __name__ == '__main__': arr = [17, 3, 8, 6] n = len(arr) print(maxLcmOfPairs(arr, n)) # This code is contributed by hupendraSingh", "e": 29318, "s": 28588, "text": null }, { "code": "// C# implementation to find the maximum// LCM of pairs in an arrayusing System;class GFG { // Function comparing all LCM pairs static int maxLcmOfPairs(int[] arr, int n) { // To store the highest LCM int maxLCM = -1; // To generate all pairs from array for (int i = 0; i < n; i++) { for (int j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.Max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void Main() { int[] arr = { 17, 3, 8, 6 }; int n = arr.Length; Console.Write(maxLcmOfPairs(arr, n)); }} // This code is contributed by Code_Mech", "e": 30349, "s": 29318, "text": null }, { "code": "<script>// javascript implementation to find the maximum// LCM of pairs in an array // Function comparing all LCM pairs function maxLcmOfPairs(arr , n) { // To store the highest LCM var maxLCM = -1; // To generate all pairs from array for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max(maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the highest value of LCM return maxLCM; } function __gcd(a , b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code var arr = [ 17, 3, 8, 6 ]; var n = arr.length; document.write(maxLcmOfPairs(arr, n)); // This code is contributed by umadevi9616</script>", "e": 31282, "s": 30349, "text": null }, { "code": null, "e": 31286, "s": 31282, "text": "136" }, { "code": null, "e": 31497, "s": 31286, "text": "Another Approach:We can use Greedy Method. For applying the greedy approach we have to sort the given array and then comparing LCM of pairs of elements of the array and finally compute the maximum value of LCM." }, { "code": null, "e": 31549, "s": 31497, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 31553, "s": 31549, "text": "C++" }, { "code": null, "e": 31558, "s": 31553, "text": "Java" }, { "code": null, "e": 31566, "s": 31558, "text": "Python3" }, { "code": null, "e": 31569, "s": 31566, "text": "C#" }, { "code": null, "e": 31580, "s": 31569, "text": "Javascript" }, { "code": "// C++ implementation to find the maximum// LCM of pairs in an array #include <bits/stdc++.h>using namespace std; // Function for the highest value of LCM pairsint greedyLCM(int arr[], int n){ // Sort the given array sort(arr, arr + n); // Compute the highest LCM int maxLCM = arr[n - 1]; for (int i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for (int j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // return the maximum lcm return maxLCM;} // Driver codeint main(){ int arr[] = { 17, 3, 8, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << greedyLCM(arr, n); return 0;}", "e": 32585, "s": 31580, "text": null }, { "code": "// Java implementation to find the// maximum LCM of pairs in an arrayimport java.util.*; class GFG { // Function for the highest value // of LCM pairs static int greedyLCM(int arr[], int n) { // Sort the given array Arrays.sort(arr); // Compute the highest LCM int maxLCM = arr[n - 1]; for (int i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for (int j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the maximum lcm return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void main(String[] args) { int arr[] = { 17, 3, 8, 6 }; int n = arr.length; System.out.print(greedyLCM(arr, n)); }} // This code is contributed by Amit Katiyar", "e": 33866, "s": 32585, "text": null }, { "code": "# Python3 implementation to# find the maximum LCM of# pairs in an arrayfrom math import gcd # Function for the highest# value of LCM pairs def greedyLCM(arr, n): # Sort the given array arr.sort() # Compute the highest LCM maxLCM = arr[n - 1] for i in range(n - 1, -1, -1): if (arr[i] * arr[i] < maxLCM): break for j in range(i - 1, -1, -1): if (arr[i] * arr[j] < maxLCM): break else: # Find LCM of the pair # Update the maxLCM if this is # greater than its existing value maxLCM = max(maxLCM, (arr[i] * arr[j]) // gcd(arr[i], arr[j])) # Return the maximum lcm return maxLCM # Driver codearr = [17, 3, 8, 6]n = len(arr) print(greedyLCM(arr, n)) # This code is contributed by divyeshrabadiya07", "e": 34765, "s": 33866, "text": null }, { "code": "// C# implementation to find the// maximum LCM of pairs in an arrayusing System; class GFG { // Function for the highest value // of LCM pairs static int greedyLCM(int[] arr, int n) { // Sort the given array Array.Sort(arr); // Compute the highest LCM int maxLCM = arr[n - 1]; for (int i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for (int j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.Max( maxLCM, (arr[i] * arr[j]) / __gcd(arr[i], arr[j])); } } // Return the maximum lcm return maxLCM; } static int __gcd(int a, int b) { return b == 0 ? a : __gcd(b, a % b); } // Driver code public static void Main(String[] args) { int[] arr = { 17, 3, 8, 6 }; int n = arr.Length; Console.Write(greedyLCM(arr, n)); }} // This code is contributed by Amit Katiyar", "e": 36034, "s": 34765, "text": null }, { "code": "<script> // Javascript implementation to find the// maximum LCM of pairs in an array // Function for the highest value// of LCM pairsfunction greedyLCM(arr, n){ // Sort the given array arr.sort(function(a, b){return a - b}); // Compute the highest LCM let maxLCM = arr[n - 1]; for(let i = n - 1; i >= 0; i--) { if (arr[i] * arr[i] < maxLCM) break; for(let j = i - 1; j >= 0; j--) { if (arr[i] * arr[j] < maxLCM) break; else // Find LCM of the pair // Update the maxLCM if this is // greater than its existing value maxLCM = Math.max(maxLCM, parseInt((arr[i] * arr[j]) / __gcd(arr[i], arr[j]), 10)); } } // Return the maximum lcm return maxLCM;} function __gcd(a, b){ return b == 0 ? a : __gcd(b, a % b);} // Driver codelet arr = [ 17, 3, 8, 6 ];let n = arr.length; document.write(greedyLCM(arr, n)); // This code is contributed by mukesh07 </script>", "e": 37102, "s": 36034, "text": null }, { "code": null, "e": 37106, "s": 37102, "text": "136" }, { "code": null, "e": 37129, "s": 37106, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 37140, "s": 37129, "text": "bgangwar59" }, { "code": null, "e": 37155, "s": 37140, "text": "sapnasingh4991" }, { "code": null, "e": 37165, "s": 37155, "text": "Code_Mech" }, { "code": null, "e": 37180, "s": 37165, "text": "amit143katiyar" }, { "code": null, "e": 37198, "s": 37180, "text": "divyeshrabadiya07" }, { "code": null, "e": 37207, "s": 37198, "text": "cscyuger" }, { "code": null, "e": 37219, "s": 37207, "text": "umadevi9616" }, { "code": null, "e": 37228, "s": 37219, "text": "mukesh07" }, { "code": null, "e": 37239, "s": 37228, "text": "Algorithms" }, { "code": null, "e": 37246, "s": 37239, "text": "Arrays" }, { "code": null, "e": 37270, "s": 37246, "text": "Competitive Programming" }, { "code": null, "e": 37277, "s": 37270, "text": "Arrays" }, { "code": null, "e": 37288, "s": 37277, "text": "Algorithms" }, { "code": null, "e": 37386, "s": 37288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37435, "s": 37386, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 37460, "s": 37435, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 37488, "s": 37460, "text": "How to write a Pseudo Code?" }, { "code": null, "e": 37539, "s": 37488, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 37566, "s": 37539, "text": "Introduction to Algorithms" }, { "code": null, "e": 37581, "s": 37566, "text": "Arrays in Java" }, { "code": null, "e": 37597, "s": 37581, "text": "Arrays in C/C++" }, { "code": null, "e": 37665, "s": 37597, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 37711, "s": 37665, "text": "Write a program to reverse an array or string" } ]
Python - Uniform Distribution in Statistics - GeeksforGeeks
10 Jan, 2020 scipy.stats.uniform() is a Uniform continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution. Parameters : q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’). Results : Uniform continuous random variable Code #1 : Creating Uniform continuous random variable # importing library from scipy.stats import uniform numargs = uniform .numargs a, b = 0.2, 0.8rv = uniform (a, b) print ("RV : \n", rv) Output : RV : scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D9F1E708 Code #2 : Uniform continuous variates and probability distribution import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = uniform .rvs(a, b, size = 10) print ("Random Variates : \n", R) # PDF x = np.linspace(uniform.ppf(0.01, a, b), uniform.ppf(0.99, a, b), 10)R = uniform.pdf(x, 1, 3)print ("\nProbability Distribution : \n", R) Output : Random Variates : [0.30819979 0.95991962 0.70622125 0.60895239 0.72550267 0.73555393 0.3757751 0.88295358 0.50726709 0.57936421] Probability Distribution : [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] Code #3 : Graphical Representation. import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print("Distribution : \n", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) Output : Distribution : [0. 0.02040816 0.04081633 0.06122449 0.08163265 0.10204082 0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898 0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878 0.36734694 0.3877551 0.40816327 0.42857143 0.44897959 0.46938776 0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673 0.6122449 0.63265306 0.65306122 0.67346939 0.69387755 0.71428571 0.73469388 0.75510204 0.7755102 0.79591837 0.81632653 0.83673469 0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367 0.97959184 1. ] Code #4 : Varying Positional Arguments import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = uniform.pdf(x, a, b) y2 = uniform.pdf(x, a, b) plt.plot(x, y1, "*", x, y2, "r--") Output : Python scipy-stats-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Convert integer to string in Python
[ { "code": null, "e": 25553, "s": 25525, "text": "\n10 Jan, 2020" }, { "code": null, "e": 25784, "s": 25553, "text": "scipy.stats.uniform() is a Uniform continuous random variable. It is inherited from the of generic methods as an instance of the rv_continuous class. It completes the methods with details specific for this particular distribution." }, { "code": null, "e": 25797, "s": 25784, "text": "Parameters :" }, { "code": null, "e": 26143, "s": 25797, "text": "q : lower and upper tail probabilityx : quantilesloc : [optional]location parameter. Default = 0scale : [optional]scale parameter. Default = 1size : [tuple of ints, optional] shape or random variates.moments : [optional] composed of letters [‘mvsk’]; ‘m’ = mean, ‘v’ = variance, ‘s’ = Fisher’s skew and ‘k’ = Fisher’s kurtosis. (default = ‘mv’)." }, { "code": null, "e": 26188, "s": 26143, "text": "Results : Uniform continuous random variable" }, { "code": null, "e": 26242, "s": 26188, "text": "Code #1 : Creating Uniform continuous random variable" }, { "code": "# importing library from scipy.stats import uniform numargs = uniform .numargs a, b = 0.2, 0.8rv = uniform (a, b) print (\"RV : \\n\", rv) ", "e": 26389, "s": 26242, "text": null }, { "code": null, "e": 26398, "s": 26389, "text": "Output :" }, { "code": null, "e": 26479, "s": 26398, "text": "RV : \n scipy.stats._distn_infrastructure.rv_frozen object at 0x000002A9D9F1E708\n" }, { "code": null, "e": 26546, "s": 26479, "text": "Code #2 : Uniform continuous variates and probability distribution" }, { "code": "import numpy as np quantile = np.arange (0.01, 1, 0.1) # Random Variates R = uniform .rvs(a, b, size = 10) print (\"Random Variates : \\n\", R) # PDF x = np.linspace(uniform.ppf(0.01, a, b), uniform.ppf(0.99, a, b), 10)R = uniform.pdf(x, 1, 3)print (\"\\nProbability Distribution : \\n\", R) ", "e": 26851, "s": 26546, "text": null }, { "code": null, "e": 26860, "s": 26851, "text": "Output :" }, { "code": null, "e": 27056, "s": 26860, "text": "Random Variates : \n [0.30819979 0.95991962 0.70622125 0.60895239 0.72550267 0.73555393\n 0.3757751 0.88295358 0.50726709 0.57936421]\n\nProbability Distribution : \n [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]\n" }, { "code": null, "e": 27092, "s": 27056, "text": "Code #3 : Graphical Representation." }, { "code": "import numpy as np import matplotlib.pyplot as plt distribution = np.linspace(0, np.minimum(rv.dist.b, 3)) print(\"Distribution : \\n\", distribution) plot = plt.plot(distribution, rv.pdf(distribution)) ", "e": 27303, "s": 27092, "text": null }, { "code": null, "e": 27312, "s": 27303, "text": "Output :" }, { "code": null, "e": 27891, "s": 27312, "text": "Distribution : \n [0. 0.02040816 0.04081633 0.06122449 0.08163265 0.10204082\n 0.12244898 0.14285714 0.16326531 0.18367347 0.20408163 0.2244898\n 0.24489796 0.26530612 0.28571429 0.30612245 0.32653061 0.34693878\n 0.36734694 0.3877551 0.40816327 0.42857143 0.44897959 0.46938776\n 0.48979592 0.51020408 0.53061224 0.55102041 0.57142857 0.59183673\n 0.6122449 0.63265306 0.65306122 0.67346939 0.69387755 0.71428571\n 0.73469388 0.75510204 0.7755102 0.79591837 0.81632653 0.83673469\n 0.85714286 0.87755102 0.89795918 0.91836735 0.93877551 0.95918367\n 0.97959184 1. ]\n " }, { "code": null, "e": 27930, "s": 27891, "text": "Code #4 : Varying Positional Arguments" }, { "code": "import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 5, 100) # Varying positional arguments y1 = uniform.pdf(x, a, b) y2 = uniform.pdf(x, a, b) plt.plot(x, y1, \"*\", x, y2, \"r--\") ", "e": 28134, "s": 27930, "text": null }, { "code": null, "e": 28143, "s": 28134, "text": "Output :" }, { "code": null, "e": 28172, "s": 28143, "text": "Python scipy-stats-functions" }, { "code": null, "e": 28179, "s": 28172, "text": "Python" }, { "code": null, "e": 28277, "s": 28179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28295, "s": 28277, "text": "Python Dictionary" }, { "code": null, "e": 28330, "s": 28295, "text": "Read a file line by line in Python" }, { "code": null, "e": 28362, "s": 28330, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28384, "s": 28362, "text": "Enumerate() in Python" }, { "code": null, "e": 28426, "s": 28384, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28456, "s": 28426, "text": "Iterate over a list in Python" }, { "code": null, "e": 28482, "s": 28456, "text": "Python String | replace()" }, { "code": null, "e": 28526, "s": 28482, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28555, "s": 28526, "text": "*args and **kwargs in Python" } ]
How to modify HTML using BeautifulSoup ? - GeeksforGeeks
15 Mar, 2021 BeautifulSoup in Python helps in scraping the information from web pages made of HTML or XML. Not only it involves scrapping data but also involves searching, modifying, and iterating the parse tree. In this article, we will discuss modifying the content directly on the HTML web page using BeautifulSoup. Syntax: old_text=soup.find(“#Widget”, {“id”:”#Id name of widget in which you want to edit”}) new_text=old_text.find(text=re.compile(‘#Text which you want to edit’)).replace_with(‘#New text which you want to replace with’) Widget: Here, widget stands for the particular widget in which the text you wish to replace from the website is currently stored. Id Name: Here, Id Name stands for the name you have given to the Id of the particular widget in which text is stored. Example: For instance, consider this simple page source. HTML <!DOCTYPE html><html> <head> My First Heading </head><body> <p id="para"> Geeks For Geeks </p> </body></html> Once you have created a driver, you can replace the text ‘Geeks For Geeks‘ with ‘Vinayak Rai‘ using – old_text=soup.find(“p”, {“id”:”para”}) new_text=old_text.find(text=re.compile(‘Geeks For Geeks’)).replace_with(‘Vinayak Rai’) Step 1: First, import the libraries Beautiful Soup, os and re. from bs4 import BeautifulSoup as bs import os import re Step 2: Now, remove the last segment of the path. base=os.path.dirname(os.path.abspath(__file__)) Step 3: Then, open the HTML file in which you wish to make a change. html=open(os.path.join(base, ‘#Name of HTML file in which you want to edit’)) Step 4: Moreover, parse the HTML file in Beautiful Soup. soup=bs(html, ‘html.parser’) Step 5: Further, give the appropriate location of the text which you wish to replace. old_text=soup.find(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”}) Step 6: Next, replace the already stored text with the new text you wish to assign. new_text=old_text.find(text=re.compile(‘#Text which you want to edit’)).replace_with(‘#New Text which you want to replace with’) Step 7: Finally, alter the HTML file to see the changes done in the previous step. with open(“#Name of HTML file in which you want to store the edited text”, “wb”) as f_output: f_output.write(soup.prettify(“utf-8”)) Python # Python program to modify HTML# with the help of Beautiful Soup # Import the libraries from bs4 import BeautifulSoup as bsimport osimport re # Remove the last segment of the pathbase = os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to make changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Give location where text is # stored which you wish to alterold_text = soup.find("p", {"id": "para"}) # Replace the already stored text with # the new text which you wish to assignnew_text = old_text.find(text=re.compile( 'Geeks For Geeks')).replace_with('Vinayak Rai') # Alter HTML file to see the changes donewith open("gfg.html", "wb") as f_output: f_output.write(soup.prettify("utf-8")) Output: Picked Python BeautifulSoup Python bs4-Exercises Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n15 Mar, 2021" }, { "code": null, "e": 25843, "s": 25537, "text": "BeautifulSoup in Python helps in scraping the information from web pages made of HTML or XML. Not only it involves scrapping data but also involves searching, modifying, and iterating the parse tree. In this article, we will discuss modifying the content directly on the HTML web page using BeautifulSoup." }, { "code": null, "e": 25851, "s": 25843, "text": "Syntax:" }, { "code": null, "e": 25936, "s": 25851, "text": "old_text=soup.find(“#Widget”, {“id”:”#Id name of widget in which you want to edit”})" }, { "code": null, "e": 26065, "s": 25936, "text": "new_text=old_text.find(text=re.compile(‘#Text which you want to edit’)).replace_with(‘#New text which you want to replace with’)" }, { "code": null, "e": 26195, "s": 26065, "text": "Widget: Here, widget stands for the particular widget in which the text you wish to replace from the website is currently stored." }, { "code": null, "e": 26313, "s": 26195, "text": "Id Name: Here, Id Name stands for the name you have given to the Id of the particular widget in which text is stored." }, { "code": null, "e": 26322, "s": 26313, "text": "Example:" }, { "code": null, "e": 26370, "s": 26322, "text": "For instance, consider this simple page source." }, { "code": null, "e": 26375, "s": 26370, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> My First Heading </head><body> <p id=\"para\"> Geeks For Geeks </p> </body></html>", "e": 26496, "s": 26375, "text": null }, { "code": null, "e": 26598, "s": 26496, "text": "Once you have created a driver, you can replace the text ‘Geeks For Geeks‘ with ‘Vinayak Rai‘ using –" }, { "code": null, "e": 26637, "s": 26598, "text": "old_text=soup.find(“p”, {“id”:”para”})" }, { "code": null, "e": 26724, "s": 26637, "text": "new_text=old_text.find(text=re.compile(‘Geeks For Geeks’)).replace_with(‘Vinayak Rai’)" }, { "code": null, "e": 26787, "s": 26724, "text": "Step 1: First, import the libraries Beautiful Soup, os and re." }, { "code": null, "e": 26823, "s": 26787, "text": "from bs4 import BeautifulSoup as bs" }, { "code": null, "e": 26833, "s": 26823, "text": "import os" }, { "code": null, "e": 26843, "s": 26833, "text": "import re" }, { "code": null, "e": 26893, "s": 26843, "text": "Step 2: Now, remove the last segment of the path." }, { "code": null, "e": 26941, "s": 26893, "text": "base=os.path.dirname(os.path.abspath(__file__))" }, { "code": null, "e": 27010, "s": 26941, "text": "Step 3: Then, open the HTML file in which you wish to make a change." }, { "code": null, "e": 27088, "s": 27010, "text": "html=open(os.path.join(base, ‘#Name of HTML file in which you want to edit’))" }, { "code": null, "e": 27145, "s": 27088, "text": "Step 4: Moreover, parse the HTML file in Beautiful Soup." }, { "code": null, "e": 27174, "s": 27145, "text": "soup=bs(html, ‘html.parser’)" }, { "code": null, "e": 27261, "s": 27174, "text": "Step 5: Further, give the appropriate location of the text which you wish to replace. " }, { "code": null, "e": 27351, "s": 27261, "text": "old_text=soup.find(“#Widget Name”, {“id”:”#Id name of widget in which you want to edit”})" }, { "code": null, "e": 27435, "s": 27351, "text": "Step 6: Next, replace the already stored text with the new text you wish to assign." }, { "code": null, "e": 27564, "s": 27435, "text": "new_text=old_text.find(text=re.compile(‘#Text which you want to edit’)).replace_with(‘#New Text which you want to replace with’)" }, { "code": null, "e": 27647, "s": 27564, "text": "Step 7: Finally, alter the HTML file to see the changes done in the previous step." }, { "code": null, "e": 27741, "s": 27647, "text": "with open(“#Name of HTML file in which you want to store the edited text”, “wb”) as f_output:" }, { "code": null, "e": 27783, "s": 27741, "text": " f_output.write(soup.prettify(“utf-8”))" }, { "code": null, "e": 27790, "s": 27783, "text": "Python" }, { "code": "# Python program to modify HTML# with the help of Beautiful Soup # Import the libraries from bs4 import BeautifulSoup as bsimport osimport re # Remove the last segment of the pathbase = os.path.dirname(os.path.abspath(__file__)) # Open the HTML in which you want to make changeshtml = open(os.path.join(base, 'gfg.html')) # Parse HTML file in Beautiful Soupsoup = bs(html, 'html.parser') # Give location where text is # stored which you wish to alterold_text = soup.find(\"p\", {\"id\": \"para\"}) # Replace the already stored text with # the new text which you wish to assignnew_text = old_text.find(text=re.compile( 'Geeks For Geeks')).replace_with('Vinayak Rai') # Alter HTML file to see the changes donewith open(\"gfg.html\", \"wb\") as f_output: f_output.write(soup.prettify(\"utf-8\"))", "e": 28584, "s": 27790, "text": null }, { "code": null, "e": 28592, "s": 28584, "text": "Output:" }, { "code": null, "e": 28599, "s": 28592, "text": "Picked" }, { "code": null, "e": 28620, "s": 28599, "text": "Python BeautifulSoup" }, { "code": null, "e": 28641, "s": 28620, "text": "Python bs4-Exercises" }, { "code": null, "e": 28648, "s": 28641, "text": "Python" }, { "code": null, "e": 28746, "s": 28648, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28778, "s": 28746, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28820, "s": 28778, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28862, "s": 28820, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28889, "s": 28862, "text": "Python Classes and Objects" }, { "code": null, "e": 28945, "s": 28889, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28984, "s": 28945, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29006, "s": 28984, "text": "Defaultdict in Python" }, { "code": null, "e": 29037, "s": 29006, "text": "Python | os.path.join() method" }, { "code": null, "e": 29066, "s": 29037, "text": "Create a directory in Python" } ]
Swap Two Variables in One Line - GeeksforGeeks
21 Jan, 2022 We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.2) C/C++: Below is one generally provided classical solution: // Swap using bitwise XOR (Wrong Solution in C/C++) x ^= y ^= x ^= y; The above solution is wrong in C/C++ as it causes undefined behavior (the compiler is free to behave in any way). The reason is, modifying a variable more than once in an expression causes undefined behavior if there is no sequence point between the modifications. However, we can use a comma to introduce sequence points. So the modified solution is // Swap using bitwise XOR (Correct Solution in C/C++) // sequence point introduced using comma. (x ^= y), (y ^= x), (x ^= y); 3) Java: In Java, rules for subexpression evaluations are clearly defined. The left-hand operand is always evaluated before the right-hand operand. In Java, the expression “x ^= y ^= x ^= y;” doesn’t produce the correct result according to Java rules. It makes x = 0. However, we can use “x = x ^ y ^ (y = x);” Note the expressions are evaluated from left to right. If x = 5 and y = 10 initially, the expression is equivalent to “x = 5 ^ 10 ^ (y = 5);”. Note that we can’t use this in C/C++ as in C/C++, it is not defined whether the left operand or right operand is executed by any operator (See this for more details). 4) JavaScript: Using destructing assignment, we can simply achieve swapping using this one line. [x,y]=[y,x] C C++ Java Python3 C# PHP Javascript // C program to swap two variables in single line#include <stdio.h>int main(){ int x = 5, y = 10; (x ^= y), (y ^= x), (x ^= y); printf("After Swapping values of x and y are %d %d", x, y); return 0;} // C++ code to swap using XOR#include <bits/stdc++.h> using namespace std; int main(){ int x = 5, y = 10; // Code to swap 'x' and 'y' // to swap two numbers in one // line x = x ^ y, y = x ^ y, x = x ^ y; // printing the swapped variables cout << "After Swapping: x = " << x << ", y= " << y; return 0;} // Java program to swap two variables in a single lineclass GFG { public static void main(String[] args) { int x = 5, y = 10; x = x ^ y ^ (y = x); System.out.println( "After Swapping values" +" of x and y are " + x + " " + y); }} # Python program to swap two variables in a single linex = 5y = 10x, y = y, xprint("After Swapping values of x and y are", x, y) // C# program to swap two// variables in single lineusing System; class GFG { static public void Main() { int x = 5, y = 10; x = x ^ y ^ (y = x); Console.WriteLine("After Swapping values " + "of x and y are " + x + " " + y); }} // This code is contributed by aj_36 <?php// PHP program to swap two// variables in single line // Driver Code $x = 5; $y = 10; ($x ^= $y); ($y ^= $x); ($x ^= $y); echo "After Swapping values of x and y are " ,$x," ", $y; // This code is contributed by Vishal Tripathi?> <script>// javascript program to swap two variables in single line let x = 5, y = 10; (x ^= y), (y ^= x), (x ^= y); document.write("After Swapping values of x and y are ", x + " ", y); // This code is contributed by Surbhi Tyagi</script> Output After Swapping values of x and y are 10 5 Alternate Solutions: Using swap(): C++ library functionb = (a + b) – (a = b);a += b – (b = a);a = a * b / (b = a)a = a ^ b ^ (b = a) Using swap(): C++ library function b = (a + b) – (a = b); a += b – (b = a); a = a * b / (b = a) a = a ^ b ^ (b = a) This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.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 kongasricharan bunnyram19 surbhityagi15 itshimanshu CoderSaty anshikajain26 amartyaghoshgfg Bitwise-XOR C Language C++ Java Python Java CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Substring in C++ Core Dump (Segmentation fault) in C/C++ Vector in C++ STL Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) C++ Classes and Objects
[ { "code": null, "e": 25401, "s": 25373, "text": "\n21 Jan, 2022" }, { "code": null, "e": 25750, "s": 25401, "text": "We have discussed different approaches to swap two integers without the temporary variable. How to swap into a single line without using the library function?1) Python: In Python, there is a simple and syntactically neat construct to swap variables, we just need to write “x, y = y, x”.2) C/C++: Below is one generally provided classical solution: " }, { "code": null, "e": 25821, "s": 25750, "text": "// Swap using bitwise XOR (Wrong Solution in C/C++)\nx ^= y ^= x ^= y; " }, { "code": null, "e": 26173, "s": 25821, "text": "The above solution is wrong in C/C++ as it causes undefined behavior (the compiler is free to behave in any way). The reason is, modifying a variable more than once in an expression causes undefined behavior if there is no sequence point between the modifications. However, we can use a comma to introduce sequence points. So the modified solution is " }, { "code": null, "e": 26299, "s": 26173, "text": "// Swap using bitwise XOR (Correct Solution in C/C++)\n// sequence point introduced using comma.\n(x ^= y), (y ^= x), (x ^= y);" }, { "code": null, "e": 26920, "s": 26299, "text": "3) Java: In Java, rules for subexpression evaluations are clearly defined. The left-hand operand is always evaluated before the right-hand operand. In Java, the expression “x ^= y ^= x ^= y;” doesn’t produce the correct result according to Java rules. It makes x = 0. However, we can use “x = x ^ y ^ (y = x);” Note the expressions are evaluated from left to right. If x = 5 and y = 10 initially, the expression is equivalent to “x = 5 ^ 10 ^ (y = 5);”. Note that we can’t use this in C/C++ as in C/C++, it is not defined whether the left operand or right operand is executed by any operator (See this for more details)." }, { "code": null, "e": 27018, "s": 26920, "text": "4) JavaScript: Using destructing assignment, we can simply achieve swapping using this one line. " }, { "code": null, "e": 27030, "s": 27018, "text": "[x,y]=[y,x]" }, { "code": null, "e": 27032, "s": 27030, "text": "C" }, { "code": null, "e": 27036, "s": 27032, "text": "C++" }, { "code": null, "e": 27041, "s": 27036, "text": "Java" }, { "code": null, "e": 27049, "s": 27041, "text": "Python3" }, { "code": null, "e": 27052, "s": 27049, "text": "C#" }, { "code": null, "e": 27056, "s": 27052, "text": "PHP" }, { "code": null, "e": 27067, "s": 27056, "text": "Javascript" }, { "code": "// C program to swap two variables in single line#include <stdio.h>int main(){ int x = 5, y = 10; (x ^= y), (y ^= x), (x ^= y); printf(\"After Swapping values of x and y are %d %d\", x, y); return 0;}", "e": 27288, "s": 27067, "text": null }, { "code": "// C++ code to swap using XOR#include <bits/stdc++.h> using namespace std; int main(){ int x = 5, y = 10; // Code to swap 'x' and 'y' // to swap two numbers in one // line x = x ^ y, y = x ^ y, x = x ^ y; // printing the swapped variables cout << \"After Swapping: x = \" << x << \", y= \" << y; return 0;}", "e": 27625, "s": 27288, "text": null }, { "code": "// Java program to swap two variables in a single lineclass GFG { public static void main(String[] args) { int x = 5, y = 10; x = x ^ y ^ (y = x); System.out.println( \"After Swapping values\" +\" of x and y are \" + x + \" \" + y); }}", "e": 27918, "s": 27625, "text": null }, { "code": "# Python program to swap two variables in a single linex = 5y = 10x, y = y, xprint(\"After Swapping values of x and y are\", x, y)", "e": 28047, "s": 27918, "text": null }, { "code": "// C# program to swap two// variables in single lineusing System; class GFG { static public void Main() { int x = 5, y = 10; x = x ^ y ^ (y = x); Console.WriteLine(\"After Swapping values \" + \"of x and y are \" + x + \" \" + y); }} // This code is contributed by aj_36", "e": 28392, "s": 28047, "text": null }, { "code": "<?php// PHP program to swap two// variables in single line // Driver Code $x = 5; $y = 10; ($x ^= $y); ($y ^= $x); ($x ^= $y); echo \"After Swapping values of x and y are \" ,$x,\" \", $y; // This code is contributed by Vishal Tripathi?>", "e": 28681, "s": 28392, "text": null }, { "code": "<script>// javascript program to swap two variables in single line let x = 5, y = 10; (x ^= y), (y ^= x), (x ^= y); document.write(\"After Swapping values of x and y are \", x + \" \", y); // This code is contributed by Surbhi Tyagi</script>", "e": 28940, "s": 28681, "text": null }, { "code": null, "e": 28947, "s": 28940, "text": "Output" }, { "code": null, "e": 28989, "s": 28947, "text": "After Swapping values of x and y are 10 5" }, { "code": null, "e": 29011, "s": 28989, "text": "Alternate Solutions: " }, { "code": null, "e": 29123, "s": 29011, "text": "Using swap(): C++ library functionb = (a + b) – (a = b);a += b – (b = a);a = a * b / (b = a)a = a ^ b ^ (b = a)" }, { "code": null, "e": 29158, "s": 29123, "text": "Using swap(): C++ library function" }, { "code": null, "e": 29181, "s": 29158, "text": "b = (a + b) – (a = b);" }, { "code": null, "e": 29199, "s": 29181, "text": "a += b – (b = a);" }, { "code": null, "e": 29219, "s": 29199, "text": "a = a * b / (b = a)" }, { "code": null, "e": 29239, "s": 29219, "text": "a = a ^ b ^ (b = a)" }, { "code": null, "e": 29603, "s": 29239, "text": "This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.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": 29609, "s": 29603, "text": "jit_t" }, { "code": null, "e": 29624, "s": 29609, "text": "kongasricharan" }, { "code": null, "e": 29635, "s": 29624, "text": "bunnyram19" }, { "code": null, "e": 29649, "s": 29635, "text": "surbhityagi15" }, { "code": null, "e": 29661, "s": 29649, "text": "itshimanshu" }, { "code": null, "e": 29671, "s": 29661, "text": "CoderSaty" }, { "code": null, "e": 29685, "s": 29671, "text": "anshikajain26" }, { "code": null, "e": 29701, "s": 29685, "text": "amartyaghoshgfg" }, { "code": null, "e": 29713, "s": 29701, "text": "Bitwise-XOR" }, { "code": null, "e": 29724, "s": 29713, "text": "C Language" }, { "code": null, "e": 29728, "s": 29724, "text": "C++" }, { "code": null, "e": 29733, "s": 29728, "text": "Java" }, { "code": null, "e": 29740, "s": 29733, "text": "Python" }, { "code": null, "e": 29745, "s": 29740, "text": "Java" }, { "code": null, "e": 29749, "s": 29745, "text": "CPP" }, { "code": null, "e": 29847, "s": 29749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29882, "s": 29847, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 29928, "s": 29882, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 29950, "s": 29928, "text": "Function Pointer in C" }, { "code": null, "e": 29967, "s": 29950, "text": "Substring in C++" }, { "code": null, "e": 30007, "s": 29967, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 30025, "s": 30007, "text": "Vector in C++ STL" }, { "code": null, "e": 30044, "s": 30025, "text": "Inheritance in C++" }, { "code": null, "e": 30090, "s": 30044, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 30133, "s": 30090, "text": "Map in C++ Standard Template Library (STL)" } ]
How can you delete a record from a table using MySQL in Python?
We may at times need to delete certain rows from a table. Suppose, we have a table of details of students in the class. It is possible that one of the students left the class and hence, we do not require the details of that particular student. Hence, we need to delete that particular row or record from the table. The “DELETE FROM” statement in MySQL is used to delete a row or record from the table, The “WHERE” clause is used to specify the row to be deleted. If WHERE clause is not used, then all the records will be deleted. Delete all the rows − DELETE FROM table_name Delete a specific row − DELETE FROM table_name WHERE condition import MySQL connector import MySQL connector establish connection with the connector using connect() establish connection with the connector using connect() create the cursor object using cursor() method create the cursor object using cursor() method create a query using the appropriate mysql statements create a query using the appropriate mysql statements execute the SQL query using execute() method execute the SQL query using execute() method commit the changes made using the commit() method commit the changes made using the commit() method close the connection close the connection Suppose we have a table named “Student” as follows − +----------+---------+-----------+------------+ | Name | Class | City | Marks | +----------+---------+-----------+------------+ | Karan | 4 | Amritsar | 95 | | Sahil | 6 | Amritsar | 93 | | Kriti | 3 | Batala | 88 | | Khushi | 9 | Delhi | 90 | | Kirat | 5 | Delhi | 85 | +----------+---------+-----------+------------+ Suppose, we have the above table of students and we want to delete the record of Kriti from the above table. import mysql.connector db=mysql.connector.connect(host="your host", user="your username", password="your password",database="database_name") cursor=db.cursor() query="DELETE FROM Students WHERE Name='Kriti'" cursor.execute(query) db.commit() query="SELECT * FROM Students" cursor.execute(query) for row in cursor: print(row) db.close() The above code deletes a row from the table and prints the remaining rowsof the table. (‘Karan’, 4 ,’Amritsar’ , 95) (‘Sahil’ , 6, ‘Amritsar’ ,93) (‘Amit’ , 9, ‘Delhi’ , 90) (‘Priya’ , 5, ‘Delhi’ ,85) The db.commit() in the above code is important. It is used to commit the changes made to the table. Without using commit(), no changes will be made in the table.
[ { "code": null, "e": 1377, "s": 1062, "text": "We may at times need to delete certain rows from a table. Suppose, we have a table of details of students in the class. It is possible that one of the students left the class and hence, we do not require the details of that particular student. Hence, we need to delete that particular row or record from the table." }, { "code": null, "e": 1592, "s": 1377, "text": "The “DELETE FROM” statement in MySQL is used to delete a row or record from the table, The “WHERE” clause is used to specify the row to be deleted. If WHERE clause is not used, then all the records will be deleted." }, { "code": null, "e": 1614, "s": 1592, "text": "Delete all the rows −" }, { "code": null, "e": 1637, "s": 1614, "text": "DELETE FROM table_name" }, { "code": null, "e": 1661, "s": 1637, "text": "Delete a specific row −" }, { "code": null, "e": 1700, "s": 1661, "text": "DELETE FROM table_name WHERE condition" }, { "code": null, "e": 1723, "s": 1700, "text": "import MySQL connector" }, { "code": null, "e": 1746, "s": 1723, "text": "import MySQL connector" }, { "code": null, "e": 1802, "s": 1746, "text": "establish connection with the connector using connect()" }, { "code": null, "e": 1858, "s": 1802, "text": "establish connection with the connector using connect()" }, { "code": null, "e": 1905, "s": 1858, "text": "create the cursor object using cursor() method" }, { "code": null, "e": 1952, "s": 1905, "text": "create the cursor object using cursor() method" }, { "code": null, "e": 2006, "s": 1952, "text": "create a query using the appropriate mysql statements" }, { "code": null, "e": 2060, "s": 2006, "text": "create a query using the appropriate mysql statements" }, { "code": null, "e": 2105, "s": 2060, "text": "execute the SQL query using execute() method" }, { "code": null, "e": 2150, "s": 2105, "text": "execute the SQL query using execute() method" }, { "code": null, "e": 2200, "s": 2150, "text": "commit the changes made using the commit() method" }, { "code": null, "e": 2250, "s": 2200, "text": "commit the changes made using the commit() method" }, { "code": null, "e": 2271, "s": 2250, "text": "close the connection" }, { "code": null, "e": 2292, "s": 2271, "text": "close the connection" }, { "code": null, "e": 2345, "s": 2292, "text": "Suppose we have a table named “Student” as follows −" }, { "code": null, "e": 2777, "s": 2345, "text": "+----------+---------+-----------+------------+\n| Name | Class | City | Marks |\n+----------+---------+-----------+------------+\n| Karan | 4 | Amritsar | 95 |\n| Sahil | 6 | Amritsar | 93 |\n| Kriti | 3 | Batala | 88 |\n| Khushi | 9 | Delhi | 90 |\n| Kirat | 5 | Delhi | 85 |\n+----------+---------+-----------+------------+" }, { "code": null, "e": 2886, "s": 2777, "text": "Suppose, we have the above table of students and we want to delete the record of Kriti from the above table." }, { "code": null, "e": 3228, "s": 2886, "text": "import mysql.connector\n\ndb=mysql.connector.connect(host=\"your host\", user=\"your username\", password=\"your\npassword\",database=\"database_name\")\n\ncursor=db.cursor()\n\nquery=\"DELETE FROM Students WHERE Name='Kriti'\"\ncursor.execute(query)\ndb.commit()\nquery=\"SELECT * FROM Students\"\ncursor.execute(query)\nfor row in cursor:\n print(row)\ndb.close()" }, { "code": null, "e": 3315, "s": 3228, "text": "The above code deletes a row from the table and prints the remaining rowsof the table." }, { "code": null, "e": 3429, "s": 3315, "text": "(‘Karan’, 4 ,’Amritsar’ , 95)\n(‘Sahil’ , 6, ‘Amritsar’ ,93)\n(‘Amit’ , 9, ‘Delhi’ , 90)\n(‘Priya’ , 5, ‘Delhi’ ,85)" }, { "code": null, "e": 3591, "s": 3429, "text": "The db.commit() in the above code is important. It is used to commit the changes made to the table. Without using commit(), no changes will be made in the table." } ]
Java program to convert a Set to an array
The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. To convert a Set object to an array − Create a Set object. Add elements to it. Create an empty array with size of the created Set. Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it. Print the contents of the array. Live Demo import java.util.HashSet; import java.util.Set; public class SetToArray { public static void main(String args[]){ Set<String> set = new HashSet<String>(); set.add("Apple"); set.add("Orange"); set.add("Banana"); System.out.println("Contents of Set ::"+set); String[] myArray = new String[set.size()]; set.toArray(myArray); for(int i=0; i<myArray.length; i++){ System.out.println("Element at the index "+(i+1)+" is ::"+myArray[i]); } } } Contents of Set ::[Apple, Orange, Banana] Element at the index 1 is ::Apple Element at the index 2 is ::Orange Element at the index 3 is ::Banana
[ { "code": null, "e": 1269, "s": 1062, "text": "The Set object provides a method known as toArray(). This method accepts an empty array as argument, converts the current Set to an array and places in the given array. To convert a Set object to an array −" }, { "code": null, "e": 1291, "s": 1269, "text": " Create a Set object." }, { "code": null, "e": 1312, "s": 1291, "text": " Add elements to it." }, { "code": null, "e": 1365, "s": 1312, "text": " Create an empty array with size of the created Set." }, { "code": null, "e": 1478, "s": 1365, "text": " Convert the Set to an array using the toArray() method, bypassing the above-created array as an argument to it." }, { "code": null, "e": 1512, "s": 1478, "text": " Print the contents of the array." }, { "code": null, "e": 1522, "s": 1512, "text": "Live Demo" }, { "code": null, "e": 2029, "s": 1522, "text": "import java.util.HashSet;\nimport java.util.Set;\npublic class SetToArray {\n public static void main(String args[]){\n Set<String> set = new HashSet<String>();\n set.add(\"Apple\");\n set.add(\"Orange\");\n set.add(\"Banana\");\n\n System.out.println(\"Contents of Set ::\"+set);\n String[] myArray = new String[set.size()];\n set.toArray(myArray);\n\n for(int i=0; i<myArray.length; i++){\n System.out.println(\"Element at the index \"+(i+1)+\" is ::\"+myArray[i]);\n }\n }\n}" }, { "code": null, "e": 2175, "s": 2029, "text": "Contents of Set ::[Apple, Orange, Banana]\nElement at the index 1 is ::Apple\nElement at the index 2 is ::Orange\nElement at the index 3 is ::Banana" } ]
Java Program to get prime numbers using the Sieve of Eratosthenes algorithm
To find all prime numbers up to any given limit, use the Sieve of Eratosthenes algorithm. At first we have set the value to be checked − int val = 30; Now, we have taken a boolean array with a length one more than the val − boolean[] isprime = new boolean[val + 1]; Loop through val and set numbers as TRUE. Also, set 0 and 1 as false since both these number are not prime − isprime[0] = false; isprime[1] = false; Following is an example showing rest of the steps to get prime numbers using the Sieve of Eratosthenes algorithm − Live Demo public class Demo { public static void main(String[] args) { // set a value to check int val = 30; boolean[] isprime = new boolean[val + 1]; for (int i = 0; i <= val; i++) isprime[i] = true; // 0 and 1 is not prime isprime[0] = false; isprime[1] = false; int n = (int) Math.ceil(Math.sqrt(val)); for (int i = 0; i <= n; i++) { if (isprime[i]) for (int j = 2 * i; j <= val; j = j + i) // not prime isprime[j] = false; } int myPrime; for (myPrime = val; !isprime[myPrime]; myPrime--) ; // empty loop body System.out.println("Largest prime less than or equal to " + val + " = " + myPrime); } } Largest prime less than or equal to 30 = 29
[ { "code": null, "e": 1199, "s": 1062, "text": "To find all prime numbers up to any given limit, use the Sieve of Eratosthenes algorithm. At first we have set the value to be checked −" }, { "code": null, "e": 1213, "s": 1199, "text": "int val = 30;" }, { "code": null, "e": 1286, "s": 1213, "text": "Now, we have taken a boolean array with a length one more than the val −" }, { "code": null, "e": 1328, "s": 1286, "text": "boolean[] isprime = new boolean[val + 1];" }, { "code": null, "e": 1437, "s": 1328, "text": "Loop through val and set numbers as TRUE. Also, set 0 and 1 as false since both these number are not prime −" }, { "code": null, "e": 1477, "s": 1437, "text": "isprime[0] = false;\nisprime[1] = false;" }, { "code": null, "e": 1592, "s": 1477, "text": "Following is an example showing rest of the steps to get prime numbers using the Sieve of Eratosthenes algorithm −" }, { "code": null, "e": 1603, "s": 1592, "text": " Live Demo" }, { "code": null, "e": 2320, "s": 1603, "text": "public class Demo {\n public static void main(String[] args) {\n // set a value to check\n int val = 30;\n boolean[] isprime = new boolean[val + 1];\n for (int i = 0; i <= val; i++)\n isprime[i] = true;\n // 0 and 1 is not prime\n isprime[0] = false;\n isprime[1] = false;\n int n = (int) Math.ceil(Math.sqrt(val));\n for (int i = 0; i <= n; i++) {\n if (isprime[i])\n for (int j = 2 * i; j <= val; j = j + i)\n // not prime\n isprime[j] = false;\n }\n int myPrime;\n for (myPrime = val; !isprime[myPrime]; myPrime--) ; // empty loop body\n System.out.println(\"Largest prime less than or equal to \" + val + \" = \" + myPrime);\n }\n}" }, { "code": null, "e": 2364, "s": 2320, "text": "Largest prime less than or equal to 30 = 29" } ]
Introducing DataJob — build and deploy a serverless data pipeline on AWS | by Vincent Claes | Towards Data Science
One of the core activities of a data engineer is to build, deploy, run and monitor data pipelines. While working in the field of data and ML engineering I lacked a tool that eased the process of deploying my data pipeline on AWS services like Glue and Sagemaker and how to easily orchestrate the steps of my data pipeline with Step Functions. This made me develop DataJob! 🚀 In this article I will show you how to install DataJob, guide you through a simple example, and showcase a couple of features of DataJob. To continue my development i would like to get some feedback from the community to either continue and add additional services (lambda, ecs fargate, aws batch, ...), change direction or abbandon this open source project. Let me know in a response! 🙏 github.com You can install DataJob from PyPI. DataJob uses AWS CDK to provision AWS services, so make sure to install this as well. If you want to follow the example, you need an AWS account of course 🙂 pip install --upgrade pippip install datajob# take latest of v1, there is no support for v2 yetnpm install -g [email protected] We have a simple data pipeline composed of 2 tasks that print “Hello World” and these tasks need to be orchestrated sequentially. The tasks are deployed to Glue and orchestrated by Step Functions. We add the above code in a file called datajob_stack.py in the root of the project. This file contains everything you need to configure the AWS services, deploy your code, and run your data pipeline. To continue, clone the repo and navigate to the example. git clone https://github.com/vincentclaes/datajob.gitcd datajob/examples/data_pipeline_simple To configure CDK you need AWS credentials. If you don’t know how to configure your AWS credentials, follow the steps here. export AWS_PROFILE=default# use the aws cli to get your account numberexport AWS_ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile $AWS_PROFILE)export AWS_DEFAULT_REGION=eu-west-1# bootstrap aws account for your regioncdk bootstrap aws://$AWS_ACCOUNT/$AWS_DEFAULT_REGION ⏳ Bootstrapping environment aws://01234567890/eu-west-1... CDKToolkit: creating CloudFormation changeset... ✅ Environment aws://01234567890/eu-west-1 bootstrapped. Create the DataJob stack with the Glue jobs that contain you code and the Step Functions state machine that will orchestrate the Glue jobs. cdk deploy --app "python datajob_stack.py" --require-approval never data-pipeline-simple: deploying... [0%] start: Publishing [50%] success: Published [100%] success: Published data-pipeline-simple: creating CloudFormation changeset... ✅ data-pipeline-simple when cdk deploy successfully finishes, the services are configured and ready to be executed. Trigger the Step Functions state machine that will orchestrate the data pipeline. datajob execute --state-machine data-pipeline-simple-workflow executing: data-pipeline-simple-workflow status: RUNNING view the execution on the AWS console: <here will be a link to see the step functions workflow> The terminal will show a link to the step functions web page to follow up on your pipeline run. If you click the link you should see something like the following: Once your data pipeline has finished, remove it from AWS. This will leave you with a clean AWS account. cdk destroy --app "python datajob_stack.py" data-pipeline-simple: destroying... ✅ data-pipeline-simple: destroyed Find out more in the examples. Specify a stage as a context parameter in CDK to deploy an isolated pipeline. Typical examples are dev , prod, ... cdk deploy --app "python datajob_stack.py" --context stage=dev To speed up your data pipeline you might want to run tasks in parallel. This is possible with DataJob! I borrowed the concept of Airflow where you can use the operator >> to orchestrate the different tasks. with StepfunctionsWorkflow(datajob_stack=datajob_stack, name="workflow") as sfn: task1 >> task2 task3 >> task4 task2 >> task5 task4 >> task5 DataJob figures out what tasks can run in parallel to speed up the execution. Find out more in the examples. Provide the parameter notification with an email address in the constructor of a StepfunctionsWorkflow object. This will create an SNS Topic which will be triggered in case of failure or success. The email will receive a notification in its inbox. with StepfunctionsWorkflow(datajob_stack=datajob_stack, name="workflow", notification="[email protected]") as sfn: task1 >> task2 Ship your project with all its dependencies to Glue. By specifying project_root in the constructor of DataJobStack, DataJob will look for a wheel (.whl file) in the dist/ folder in your project_root. current_dir = str(pathlib.Path(__file__).parent.absolute())with DataJobStack( scope=app, id="data-pipeline-pkg", project_root=current_dir) as datajob_stack: Find out more in the examples Check the new example of an End-to-end Machine Learning Pipeline on the GitHub repo with Glue, Sagemaker, and Step functions. ⚠️ Give me a response on what you like, didn't like, and what other services you would want to see next in DataJob! ⚠️ github.com 👋 Follow me on Medium, Linkedin, and Twitter if you want to read more on ML engineering and ML pipelines.
[ { "code": null, "e": 547, "s": 172, "text": "One of the core activities of a data engineer is to build, deploy, run and monitor data pipelines. While working in the field of data and ML engineering I lacked a tool that eased the process of deploying my data pipeline on AWS services like Glue and Sagemaker and how to easily orchestrate the steps of my data pipeline with Step Functions. This made me develop DataJob! 🚀" }, { "code": null, "e": 685, "s": 547, "text": "In this article I will show you how to install DataJob, guide you through a simple example, and showcase a couple of features of DataJob." }, { "code": null, "e": 906, "s": 685, "text": "To continue my development i would like to get some feedback from the community to either continue and add additional services (lambda, ecs fargate, aws batch, ...), change direction or abbandon this open source project." }, { "code": null, "e": 935, "s": 906, "text": "Let me know in a response! 🙏" }, { "code": null, "e": 946, "s": 935, "text": "github.com" }, { "code": null, "e": 1138, "s": 946, "text": "You can install DataJob from PyPI. DataJob uses AWS CDK to provision AWS services, so make sure to install this as well. If you want to follow the example, you need an AWS account of course 🙂" }, { "code": null, "e": 1264, "s": 1138, "text": "pip install --upgrade pippip install datajob# take latest of v1, there is no support for v2 yetnpm install -g [email protected]" }, { "code": null, "e": 1461, "s": 1264, "text": "We have a simple data pipeline composed of 2 tasks that print “Hello World” and these tasks need to be orchestrated sequentially. The tasks are deployed to Glue and orchestrated by Step Functions." }, { "code": null, "e": 1661, "s": 1461, "text": "We add the above code in a file called datajob_stack.py in the root of the project. This file contains everything you need to configure the AWS services, deploy your code, and run your data pipeline." }, { "code": null, "e": 1718, "s": 1661, "text": "To continue, clone the repo and navigate to the example." }, { "code": null, "e": 1812, "s": 1718, "text": "git clone https://github.com/vincentclaes/datajob.gitcd datajob/examples/data_pipeline_simple" }, { "code": null, "e": 1935, "s": 1812, "text": "To configure CDK you need AWS credentials. If you don’t know how to configure your AWS credentials, follow the steps here." }, { "code": null, "e": 2409, "s": 1935, "text": "export AWS_PROFILE=default# use the aws cli to get your account numberexport AWS_ACCOUNT=$(aws sts get-caller-identity --query Account --output text --profile $AWS_PROFILE)export AWS_DEFAULT_REGION=eu-west-1# bootstrap aws account for your regioncdk bootstrap aws://$AWS_ACCOUNT/$AWS_DEFAULT_REGION ⏳ Bootstrapping environment aws://01234567890/eu-west-1... CDKToolkit: creating CloudFormation changeset... ✅ Environment aws://01234567890/eu-west-1 bootstrapped." }, { "code": null, "e": 2549, "s": 2409, "text": "Create the DataJob stack with the Glue jobs that contain you code and the Step Functions state machine that will orchestrate the Glue jobs." }, { "code": null, "e": 2841, "s": 2549, "text": "cdk deploy --app \"python datajob_stack.py\" --require-approval never data-pipeline-simple: deploying... [0%] start: Publishing [50%] success: Published [100%] success: Published data-pipeline-simple: creating CloudFormation changeset... ✅ data-pipeline-simple" }, { "code": null, "e": 2934, "s": 2841, "text": "when cdk deploy successfully finishes, the services are configured and ready to be executed." }, { "code": null, "e": 3016, "s": 2934, "text": "Trigger the Step Functions state machine that will orchestrate the data pipeline." }, { "code": null, "e": 3246, "s": 3016, "text": "datajob execute --state-machine data-pipeline-simple-workflow executing: data-pipeline-simple-workflow status: RUNNING view the execution on the AWS console: <here will be a link to see the step functions workflow>" }, { "code": null, "e": 3409, "s": 3246, "text": "The terminal will show a link to the step functions web page to follow up on your pipeline run. If you click the link you should see something like the following:" }, { "code": null, "e": 3513, "s": 3409, "text": "Once your data pipeline has finished, remove it from AWS. This will leave you with a clean AWS account." }, { "code": null, "e": 3635, "s": 3513, "text": "cdk destroy --app \"python datajob_stack.py\" data-pipeline-simple: destroying... ✅ data-pipeline-simple: destroyed" }, { "code": null, "e": 3666, "s": 3635, "text": "Find out more in the examples." }, { "code": null, "e": 3781, "s": 3666, "text": "Specify a stage as a context parameter in CDK to deploy an isolated pipeline. Typical examples are dev , prod, ..." }, { "code": null, "e": 3844, "s": 3781, "text": "cdk deploy --app \"python datajob_stack.py\" --context stage=dev" }, { "code": null, "e": 4051, "s": 3844, "text": "To speed up your data pipeline you might want to run tasks in parallel. This is possible with DataJob! I borrowed the concept of Airflow where you can use the operator >> to orchestrate the different tasks." }, { "code": null, "e": 4204, "s": 4051, "text": "with StepfunctionsWorkflow(datajob_stack=datajob_stack, name=\"workflow\") as sfn: task1 >> task2 task3 >> task4 task2 >> task5 task4 >> task5" }, { "code": null, "e": 4282, "s": 4204, "text": "DataJob figures out what tasks can run in parallel to speed up the execution." }, { "code": null, "e": 4313, "s": 4282, "text": "Find out more in the examples." }, { "code": null, "e": 4561, "s": 4313, "text": "Provide the parameter notification with an email address in the constructor of a StepfunctionsWorkflow object. This will create an SNS Topic which will be triggered in case of failure or success. The email will receive a notification in its inbox." }, { "code": null, "e": 4745, "s": 4561, "text": "with StepfunctionsWorkflow(datajob_stack=datajob_stack, name=\"workflow\", notification=\"[email protected]\") as sfn: task1 >> task2" }, { "code": null, "e": 4945, "s": 4745, "text": "Ship your project with all its dependencies to Glue. By specifying project_root in the constructor of DataJobStack, DataJob will look for a wheel (.whl file) in the dist/ folder in your project_root." }, { "code": null, "e": 5105, "s": 4945, "text": "current_dir = str(pathlib.Path(__file__).parent.absolute())with DataJobStack( scope=app, id=\"data-pipeline-pkg\", project_root=current_dir) as datajob_stack:" }, { "code": null, "e": 5135, "s": 5105, "text": "Find out more in the examples" }, { "code": null, "e": 5261, "s": 5135, "text": "Check the new example of an End-to-end Machine Learning Pipeline on the GitHub repo with Glue, Sagemaker, and Step functions." }, { "code": null, "e": 5380, "s": 5261, "text": "⚠️ Give me a response on what you like, didn't like, and what other services you would want to see next in DataJob! ⚠️" }, { "code": null, "e": 5391, "s": 5380, "text": "github.com" } ]
How to add background color to a div in Bootstrap ? - GeeksforGeeks
09 Aug, 2021 Bootstrap provides many classes to set the background color of an element. We can easily set the background of an element to any contextual class. Anchor components will darken on hover, just like the text classes. Some classes of background colors are listed below example. We can add background color to a div by simply adding class “bg-primary”, “bg-success”, “bg-danger”, “bg-info”, and many more as shown in the following examples. Step by step guide for the implementation: Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js”></script> Step 2: Add <div> tag in the HTML body with class container. Step 3: Add <li> tag with .bg-primary, .bg-success and so on classes in the <body> tag. Example 1: The following example shows different background-color classes to set the background color of a content. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <ul> <li class="bg-primary">.bg-primary class</li> <li class="bg-success">.bg-success class</li> <li class="bg-info">.bg-info class</li> <li class="bg-warning">.bg-warning class</li> <li class="bg-danger">.bg-danger class</li> </ul> </div></body> </html> Output: example of different background colors Example 2: The following example shows how to add background color and other classes to HTML div. First, find the div in your HTML code and add a predefined class to the opening tag. Add a Bootstrap predefined class to the div you would like to change. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="p-3 mb-2 bg-primary text-white">.bg-primary</div> <div class="p-3 mb-2 bg-secondary text-white">.bg-secondary</div> <div class="p-3 mb-2 bg-success text-white">.bg-success</div> <div class="p-3 mb-2 bg-danger text-white">.bg-danger</div> <div class="p-3 mb-2 bg-warning text-dark">.bg-warning</div> <div class="p-3 mb-2 bg-info text-white">.bg-info</div></body> </html> Output: background color of div tag (these spaces in between each div is padding) Bootstrap-4 Bootstrap-Questions Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to pass data into a bootstrap modal? How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Difference between Bootstrap 4 and Bootstrap 5 Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24033, "s": 24005, "text": "\n09 Aug, 2021" }, { "code": null, "e": 24308, "s": 24033, "text": "Bootstrap provides many classes to set the background color of an element. We can easily set the background of an element to any contextual class. Anchor components will darken on hover, just like the text classes. Some classes of background colors are listed below example." }, { "code": null, "e": 24470, "s": 24308, "text": "We can add background color to a div by simply adding class “bg-primary”, “bg-success”, “bg-danger”, “bg-info”, and many more as shown in the following examples." }, { "code": null, "e": 24513, "s": 24470, "text": "Step by step guide for the implementation:" }, { "code": null, "e": 24620, "s": 24513, "text": "Step 1: Include Bootstrap and jQuery CDN into the <head> tag before all other stylesheets to load our CSS." }, { "code": null, "e": 24999, "s": 24622, "text": "<link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css”><script src=”https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js”></script><script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js”></script><script src=”https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js”></script>" }, { "code": null, "e": 25060, "s": 24999, "text": "Step 2: Add <div> tag in the HTML body with class container." }, { "code": null, "e": 25148, "s": 25060, "text": "Step 3: Add <li> tag with .bg-primary, .bg-success and so on classes in the <body> tag." }, { "code": null, "e": 25264, "s": 25148, "text": "Example 1: The following example shows different background-color classes to set the background color of a content." }, { "code": null, "e": 25269, "s": 25264, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <ul> <li class=\"bg-primary\">.bg-primary class</li> <li class=\"bg-success\">.bg-success class</li> <li class=\"bg-info\">.bg-info class</li> <li class=\"bg-warning\">.bg-warning class</li> <li class=\"bg-danger\">.bg-danger class</li> </ul> </div></body> </html>", "e": 26218, "s": 25269, "text": null }, { "code": null, "e": 26229, "s": 26220, "text": "Output: " }, { "code": null, "e": 26269, "s": 26229, "text": "example of different background colors " }, { "code": null, "e": 26367, "s": 26269, "text": "Example 2: The following example shows how to add background color and other classes to HTML div." }, { "code": null, "e": 26452, "s": 26367, "text": "First, find the div in your HTML code and add a predefined class to the opening tag." }, { "code": null, "e": 26522, "s": 26452, "text": "Add a Bootstrap predefined class to the div you would like to change." }, { "code": null, "e": 26527, "s": 26522, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"p-3 mb-2 bg-primary text-white\">.bg-primary</div> <div class=\"p-3 mb-2 bg-secondary text-white\">.bg-secondary</div> <div class=\"p-3 mb-2 bg-success text-white\">.bg-success</div> <div class=\"p-3 mb-2 bg-danger text-white\">.bg-danger</div> <div class=\"p-3 mb-2 bg-warning text-dark\">.bg-warning</div> <div class=\"p-3 mb-2 bg-info text-white\">.bg-info</div></body> </html>", "e": 27514, "s": 26527, "text": null }, { "code": null, "e": 27522, "s": 27514, "text": "Output:" }, { "code": null, "e": 27596, "s": 27522, "text": "background color of div tag (these spaces in between each div is padding)" }, { "code": null, "e": 27608, "s": 27596, "text": "Bootstrap-4" }, { "code": null, "e": 27628, "s": 27608, "text": "Bootstrap-Questions" }, { "code": null, "e": 27635, "s": 27628, "text": "Picked" }, { "code": null, "e": 27645, "s": 27635, "text": "Bootstrap" }, { "code": null, "e": 27662, "s": 27645, "text": "Web Technologies" }, { "code": null, "e": 27760, "s": 27662, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27769, "s": 27760, "text": "Comments" }, { "code": null, "e": 27782, "s": 27769, "text": "Old Comments" }, { "code": null, "e": 27823, "s": 27782, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 27864, "s": 27823, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 27927, "s": 27864, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 27960, "s": 27927, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 28007, "s": 27960, "text": "Difference between Bootstrap 4 and Bootstrap 5" }, { "code": null, "e": 28063, "s": 28007, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 28096, "s": 28063, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28158, "s": 28096, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 28201, "s": 28158, "text": "How to fetch data from an API in ReactJS ?" } ]
Python break, continue and pass Statements
You might face a situation in which you need to exit a loop completely when an external condition is triggered or there may also be a situation when you want to skip a part of the loop and start next execution. Python provides break and continue statements to handle such situations and to have good control on your loop. This tutorial will discuss the break, continue and pass statements available in Python. The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C. The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops. #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': break print 'Current Letter :', letter var = 10 # Second Example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: break print "Good bye!" This will produce the following result: Current Letter : P Current Letter : y Current Letter : t Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Good bye! The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop. The continue statement can be used in both while and for loops. #!/usr/bin/python for letter in 'Python': # First Example if letter == 'h': continue print 'Current Letter :', letter var = 10 # Second Example while var > 0: var = var -1 if var == 5: continue print 'Current variable value :', var print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t Current Letter : o Current Letter : n Current variable value : 10 Current variable value : 9 Current variable value : 8 Current variable value : 7 Current variable value : 6 Current variable value : 4 Current variable value : 3 Current variable value : 2 Current variable value : 1 Good bye! Python supports to have an else statement associated with a loop statements. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list. If the else statement is used with a while loop, the else statement is executed when the condition becomes false. If the else statement is used with a while loop, the else statement is executed when the condition becomes false. The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20. #!/usr/bin/python for num in range(10,20): #to iterate between 10 to 20 for i in range(2,num): #to iterate on the factors of the number if num%i == 0: #to determine the first factor j=num/i #to calculate the second factor print '%d equals %d * %d' % (num,i,j) break #to move to the next number, the #first FOR else: # else part of the loop print num, 'is a prime number' This will produce following result: 10 equals 2 * 5 11 is a prime number 12 equals 2 * 6 13 is a prime number 14 equals 2 * 7 15 equals 3 * 5 16 equals 2 * 8 17 is a prime number 18 equals 2 * 9 19 is a prime number Similar way you can use else statement with while loop. The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute. The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example): #!/usr/bin/python for letter in 'Python': if letter == 'h': pass print 'This is pass block' print 'Current Letter :', letter print "Good bye!" This will produce following result: Current Letter : P Current Letter : y Current Letter : t This is pass block Current Letter : h Current Letter : o Current Letter : n Good bye! The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block but it is no longer required. You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code. Copyright © 2014 by tutorialspoint. All Rights Reserved. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2455, "s": 2244, "text": "You might face a situation in which you need to exit a loop completely when an external condition is triggered or there may also be a situation when you want to skip a part of the loop and start next execution." }, { "code": null, "e": 2566, "s": 2455, "text": "Python provides break and continue statements to handle such situations and to have good control on your loop." }, { "code": null, "e": 2654, "s": 2566, "text": "This tutorial will discuss the break, continue and pass statements available in Python." }, { "code": null, "e": 2801, "s": 2654, "text": "The break statement in Python terminates the current loop and resumes execution at the next statement, just like the traditional break found in C." }, { "code": null, "e": 2973, "s": 2801, "text": "The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops." }, { "code": null, "e": 3286, "s": 2973, "text": "#!/usr/bin/python\n\nfor letter in 'Python': # First Example\n if letter == 'h':\n break\n print 'Current Letter :', letter\n \nvar = 10 # Second Example\nwhile var > 0: \n print 'Current variable value :', var\n var = var -1\n if var == 5:\n break\n\nprint \"Good bye!\"" }, { "code": null, "e": 3326, "s": 3286, "text": "This will produce the following result:" }, { "code": null, "e": 3530, "s": 3326, "text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent variable value : 10\nCurrent variable value : 9\nCurrent variable value : 8\nCurrent variable value : 7\nCurrent variable value : 6\nGood bye!\n" }, { "code": null, "e": 3767, "s": 3530, "text": "The continue statement in Python returns the control to the beginning of the while loop. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop." }, { "code": null, "e": 3831, "s": 3767, "text": "The continue statement can be used in both while and for loops." }, { "code": null, "e": 4147, "s": 3831, "text": "#!/usr/bin/python\n\nfor letter in 'Python': # First Example\n if letter == 'h':\n continue\n print 'Current Letter :', letter\n\nvar = 10 # Second Example\nwhile var > 0: \n var = var -1\n if var == 5:\n continue\n print 'Current variable value :', var\nprint \"Good bye!\"" }, { "code": null, "e": 4183, "s": 4147, "text": "This will produce following result:" }, { "code": null, "e": 4533, "s": 4183, "text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent Letter : o\nCurrent Letter : n\nCurrent variable value : 10\nCurrent variable value : 9\nCurrent variable value : 8\nCurrent variable value : 7\nCurrent variable value : 6\nCurrent variable value : 4\nCurrent variable value : 3\nCurrent variable value : 2\nCurrent variable value : 1\nGood bye!\n" }, { "code": null, "e": 4610, "s": 4533, "text": "Python supports to have an else statement associated with a loop statements." }, { "code": null, "e": 4736, "s": 4610, "text": "If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list." }, { "code": null, "e": 4862, "s": 4736, "text": "If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list." }, { "code": null, "e": 4976, "s": 4862, "text": "If the else statement is used with a while loop, the else statement is executed when the condition becomes false." }, { "code": null, "e": 5090, "s": 4976, "text": "If the else statement is used with a while loop, the else statement is executed when the condition becomes false." }, { "code": null, "e": 5234, "s": 5090, "text": "The following example illustrates the combination of an else statement with a for statement that searches for prime numbers\nfrom 10 through 20." }, { "code": null, "e": 5664, "s": 5234, "text": "#!/usr/bin/python\n\nfor num in range(10,20): #to iterate between 10 to 20\n for i in range(2,num): #to iterate on the factors of the number\n if num%i == 0: #to determine the first factor\n j=num/i #to calculate the second factor\n print '%d equals %d * %d' % (num,i,j)\n break #to move to the next number, the #first FOR\n else: # else part of the loop\n print num, 'is a prime number'" }, { "code": null, "e": 5700, "s": 5664, "text": "This will produce following result:" }, { "code": null, "e": 5881, "s": 5700, "text": "10 equals 2 * 5\n11 is a prime number\n12 equals 2 * 6\n13 is a prime number\n14 equals 2 * 7\n15 equals 3 * 5\n16 equals 2 * 8\n17 is a prime number\n18 equals 2 * 9\n19 is a prime number\n" }, { "code": null, "e": 5937, "s": 5881, "text": "Similar way you can use else statement with while loop." }, { "code": null, "e": 6069, "s": 5937, "text": "The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute." }, { "code": null, "e": 6272, "s": 6069, "text": "The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):" }, { "code": null, "e": 6436, "s": 6272, "text": "#!/usr/bin/python\n\nfor letter in 'Python': \n if letter == 'h':\n pass\n print 'This is pass block'\n print 'Current Letter :', letter\n\nprint \"Good bye!\"" }, { "code": null, "e": 6472, "s": 6436, "text": "This will produce following result:" }, { "code": null, "e": 6616, "s": 6472, "text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nThis is pass block\nCurrent Letter : h\nCurrent Letter : o\nCurrent Letter : n\nGood bye!\n" }, { "code": null, "e": 6800, "s": 6616, "text": "The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block but it is no longer required." }, { "code": null, "e": 6958, "s": 6800, "text": "You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code." }, { "code": null, "e": 7015, "s": 6958, "text": "Copyright © 2014 by tutorialspoint. All Rights Reserved." }, { "code": null, "e": 7052, "s": 7015, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 7068, "s": 7052, "text": " Malhar Lathkar" }, { "code": null, "e": 7101, "s": 7068, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 7120, "s": 7101, "text": " Arnab Chakraborty" }, { "code": null, "e": 7155, "s": 7120, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 7177, "s": 7155, "text": " In28Minutes Official" }, { "code": null, "e": 7211, "s": 7177, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 7239, "s": 7211, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 7274, "s": 7239, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 7288, "s": 7274, "text": " Lets Kode It" }, { "code": null, "e": 7321, "s": 7288, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 7338, "s": 7321, "text": " Abhilash Nelson" }, { "code": null, "e": 7345, "s": 7338, "text": " Print" }, { "code": null, "e": 7356, "s": 7345, "text": " Add Notes" } ]
How do we compare the elements of two lists in Python?
The method cmp() compares elements of two lists. If elements are of the same type, it performs the compare and returns the result. If elements are different types, it checks to see if they are numbers. If they are numbers, it performs type coercion if necessary and compares. If either element is a number, then the other element is "larger" (numbers are "smallest"). Otherwise, types are sorted alphabetically by name. If we reached the end of one of the lists, the longer list is "larger." If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned. list1 = [123, 'xyz'] list2 = [456, 'abc'] print(cmp(list1, list2)) print(cmp(list2, list1)) list2 = [123, 'xyz'] print(cmp(list1, list2)) This will give the output − -1 1 0
[ { "code": null, "e": 1482, "s": 1062, "text": "The method cmp() compares elements of two lists. If elements are of the same type, it performs the compare and returns the result. If elements are different types, it checks to see if they are numbers. If they are numbers, it performs type coercion if necessary and compares. If either element is a number, then the other element is \"larger\" (numbers are \"smallest\"). Otherwise, types are sorted alphabetically by name." }, { "code": null, "e": 1653, "s": 1482, "text": "If we reached the end of one of the lists, the longer list is \"larger.\" If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned." }, { "code": null, "e": 1791, "s": 1653, "text": "list1 = [123, 'xyz']\nlist2 = [456, 'abc']\nprint(cmp(list1, list2))\nprint(cmp(list2, list1))\nlist2 = [123, 'xyz']\nprint(cmp(list1, list2))" }, { "code": null, "e": 1819, "s": 1791, "text": "This will give the output −" }, { "code": null, "e": 1826, "s": 1819, "text": "-1\n1\n0" } ]
Sort prime numbers of an array in descending order
11 May, 2021 Given an array of integers ‘arr’, the task is to sort all the prime numbers from the array in descending order in their relative positions i.e. other positions of the other elements must not be affected.Examples: Input: arr[] = {2, 5, 8, 4, 3} Output: 5 3 8 4 2 Input: arr[] = {10, 12, 2, 6, 5} Output: 10 12 5 6 2 Approach: Create a sieve to check whether an element is prime or not in O(1). Traverse the array and check if the number is prime. If it is prime, store it in a vector. Then, sort the vector in descending order. Again traverse the array and replace the prime numbers with the vector elements one by one. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; bool prime[100005]; void SieveOfEratosthenes(int n){ memset(prime, true, sizeof(prime)); // false here indicates // that it is not prime prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (int i = p * 2; i <= n; i += p) prime[i] = false; } }} // Function that sorts// all the prime numbers// from the array in descendingvoid sortPrimes(int arr[], int n){ SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort vector<int> v; for (int i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) v.push_back(arr[i]); } sort(v.begin(), v.end(), greater<int>()); int j = 0; // update the array elements for (int i = 0; i < n; i++) { if (prime[arr[i]]) arr[i] = v[j++]; }} // Driver codeint main(){ int arr[] = { 4, 3, 2, 6, 100, 17 }; int n = sizeof(arr) / sizeof(arr[0]); sortPrimes(arr, n); // print the results. for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static boolean prime[] = new boolean[100005]; static void SieveOfEratosthenes(int n) { Arrays.fill(prime, true); // false here indicates // that it is not prime prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (int i = p * 2; i < n; i += p) { prime[i] = false; } } } } // Function that sorts // all the prime numbers // from the array in descending static void sortPrimes(int arr[], int n) { SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort Vector<Integer> v = new Vector<Integer>(); for (int i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) { v.add(arr[i]); } } Comparator comparator = Collections.reverseOrder(); Collections.sort(v, comparator); int j = 0; // update the array elements for (int i = 0; i < n; i++) { if (prime[arr[i]]) { arr[i] = v.get(j++); } } } // Driver code public static void main(String[] args) { int arr[] = {4, 3, 2, 6, 100, 17}; int n = arr.length; sortPrimes(arr, n); // print the results. for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } }} // This code is contributed by 29AjayKumar # Python3 implementation of the approach def SieveOfEratosthenes(n): # false here indicates # that it is not prime prime[1] = False p = 2 while p * p <= n: # If prime[p] is not changed, # then it is a prime if prime[p]: # Update all multiples of p, # set them to non-prime for i in range(p * 2, n + 1, p): prime[i] = False p += 1 # Function that sorts all the prime# numbers from the array in descendingdef sortPrimes(arr, n): SieveOfEratosthenes(100005) # This vector will contain # prime numbers to sort v = [] for i in range(0, n): # If the element is prime if prime[arr[i]]: v.append(arr[i]) v.sort(reverse = True) j = 0 # update the array elements for i in range(0, n): if prime[arr[i]]: arr[i] = v[j] j += 1 return arr # Driver codeif __name__ == "__main__": arr = [4, 3, 2, 6, 100, 17] n = len(arr) prime = [True] * 100006 arr = sortPrimes(arr, n) # print the results. for i in range(0, n): print(arr[i], end = " ") # This code is contributed by Rituraj Jain // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static bool []prime = new bool[100005]; static void SieveOfEratosthenes(int n) { for(int i = 0; i < 100005; i++) prime[i] = true; // false here indicates // that it is not prime prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (int i = p * 2; i < n; i += p) { prime[i] = false; } } } } // Function that sorts // all the prime numbers // from the array in descending static void sortPrimes(int []arr, int n) { SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort List<int> v = new List<int>(); for (int i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) { v.Add(arr[i]); } } v.Sort(); v.Reverse(); int j = 0; // update the array elements for (int i = 0; i < n; i++) { if (prime[arr[i]]) { arr[i] = v[j++]; } } } // Driver code public static void Main(String[] args) { int []arr = {4, 3, 2, 6, 100, 17}; int n = arr.Length; sortPrimes(arr, n); // print the results. for (int i = 0; i < n; i++) { Console.Write(arr[i] + " "); } }} // This code contributed by Rajput-Ji <script> // Javascript implementation of the approach var prime = Array(100005).fill(true); function SieveOfEratosthenes( n){ // false here indicates // that it is not prime prime[1] = false; for (var p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (var i = p * 2; i <= n; i += p) prime[i] = false; } }} // Function that sorts// all the prime numbers// from the array in descendingfunction sortPrimes(arr, n){ SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort var v = []; for (var i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) v.push(arr[i]); } v.sort((a,b)=>b-a) var j = 0; // update the array elements for (var i = 0; i < n; i++) { if (prime[arr[i]]) arr[i] = v[j++]; }} // Driver codevar arr = [4, 3, 2, 6, 100, 17 ];var n = arr.length;sortPrimes(arr, n);// print the results.for (var i = 0; i < n; i++) { document.write( arr[i] + " ");} </script> 4 17 3 6 100 2 rituraj_jain 29AjayKumar Rajput-Ji rrrtnx Prime Number sieve Arrays Competitive Programming Mathematical Sorting Arrays Mathematical Sorting Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2021" }, { "code": null, "e": 267, "s": 52, "text": "Given an array of integers ‘arr’, the task is to sort all the prime numbers from the array in descending order in their relative positions i.e. other positions of the other elements must not be affected.Examples: " }, { "code": null, "e": 370, "s": 267, "text": "Input: arr[] = {2, 5, 8, 4, 3}\nOutput: 5 3 8 4 2\n\nInput: arr[] = {10, 12, 2, 6, 5}\nOutput: 10 12 5 6 2" }, { "code": null, "e": 384, "s": 372, "text": "Approach: " }, { "code": null, "e": 452, "s": 384, "text": "Create a sieve to check whether an element is prime or not in O(1)." }, { "code": null, "e": 543, "s": 452, "text": "Traverse the array and check if the number is prime. If it is prime, store it in a vector." }, { "code": null, "e": 586, "s": 543, "text": "Then, sort the vector in descending order." }, { "code": null, "e": 678, "s": 586, "text": "Again traverse the array and replace the prime numbers with the vector elements one by one." }, { "code": null, "e": 730, "s": 678, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 734, "s": 730, "text": "C++" }, { "code": null, "e": 739, "s": 734, "text": "Java" }, { "code": null, "e": 747, "s": 739, "text": "Python3" }, { "code": null, "e": 750, "s": 747, "text": "C#" }, { "code": null, "e": 761, "s": 750, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; bool prime[100005]; void SieveOfEratosthenes(int n){ memset(prime, true, sizeof(prime)); // false here indicates // that it is not prime prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (int i = p * 2; i <= n; i += p) prime[i] = false; } }} // Function that sorts// all the prime numbers// from the array in descendingvoid sortPrimes(int arr[], int n){ SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort vector<int> v; for (int i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) v.push_back(arr[i]); } sort(v.begin(), v.end(), greater<int>()); int j = 0; // update the array elements for (int i = 0; i < n; i++) { if (prime[arr[i]]) arr[i] = v[j++]; }} // Driver codeint main(){ int arr[] = { 4, 3, 2, 6, 100, 17 }; int n = sizeof(arr) / sizeof(arr[0]); sortPrimes(arr, n); // print the results. for (int i = 0; i < n; i++) { cout << arr[i] << \" \"; } return 0;}", "e": 2097, "s": 761, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static boolean prime[] = new boolean[100005]; static void SieveOfEratosthenes(int n) { Arrays.fill(prime, true); // false here indicates // that it is not prime prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (int i = p * 2; i < n; i += p) { prime[i] = false; } } } } // Function that sorts // all the prime numbers // from the array in descending static void sortPrimes(int arr[], int n) { SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort Vector<Integer> v = new Vector<Integer>(); for (int i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) { v.add(arr[i]); } } Comparator comparator = Collections.reverseOrder(); Collections.sort(v, comparator); int j = 0; // update the array elements for (int i = 0; i < n; i++) { if (prime[arr[i]]) { arr[i] = v.get(j++); } } } // Driver code public static void main(String[] args) { int arr[] = {4, 3, 2, 6, 100, 17}; int n = arr.length; sortPrimes(arr, n); // print the results. for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } }} // This code is contributed by 29AjayKumar", "e": 3888, "s": 2097, "text": null }, { "code": "# Python3 implementation of the approach def SieveOfEratosthenes(n): # false here indicates # that it is not prime prime[1] = False p = 2 while p * p <= n: # If prime[p] is not changed, # then it is a prime if prime[p]: # Update all multiples of p, # set them to non-prime for i in range(p * 2, n + 1, p): prime[i] = False p += 1 # Function that sorts all the prime# numbers from the array in descendingdef sortPrimes(arr, n): SieveOfEratosthenes(100005) # This vector will contain # prime numbers to sort v = [] for i in range(0, n): # If the element is prime if prime[arr[i]]: v.append(arr[i]) v.sort(reverse = True) j = 0 # update the array elements for i in range(0, n): if prime[arr[i]]: arr[i] = v[j] j += 1 return arr # Driver codeif __name__ == \"__main__\": arr = [4, 3, 2, 6, 100, 17] n = len(arr) prime = [True] * 100006 arr = sortPrimes(arr, n) # print the results. for i in range(0, n): print(arr[i], end = \" \") # This code is contributed by Rituraj Jain", "e": 5099, "s": 3888, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static bool []prime = new bool[100005]; static void SieveOfEratosthenes(int n) { for(int i = 0; i < 100005; i++) prime[i] = true; // false here indicates // that it is not prime prime[1] = false; for (int p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (int i = p * 2; i < n; i += p) { prime[i] = false; } } } } // Function that sorts // all the prime numbers // from the array in descending static void sortPrimes(int []arr, int n) { SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort List<int> v = new List<int>(); for (int i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) { v.Add(arr[i]); } } v.Sort(); v.Reverse(); int j = 0; // update the array elements for (int i = 0; i < n; i++) { if (prime[arr[i]]) { arr[i] = v[j++]; } } } // Driver code public static void Main(String[] args) { int []arr = {4, 3, 2, 6, 100, 17}; int n = arr.Length; sortPrimes(arr, n); // print the results. for (int i = 0; i < n; i++) { Console.Write(arr[i] + \" \"); } }} // This code contributed by Rajput-Ji", "e": 6868, "s": 5099, "text": null }, { "code": "<script> // Javascript implementation of the approach var prime = Array(100005).fill(true); function SieveOfEratosthenes( n){ // false here indicates // that it is not prime prime[1] = false; for (var p = 2; p * p <= n; p++) { // If prime[p] is not changed, // then it is a prime if (prime[p]) { // Update all multiples of p, // set them to non-prime for (var i = p * 2; i <= n; i += p) prime[i] = false; } }} // Function that sorts// all the prime numbers// from the array in descendingfunction sortPrimes(arr, n){ SieveOfEratosthenes(100005); // this vector will contain // prime numbers to sort var v = []; for (var i = 0; i < n; i++) { // if the element is prime if (prime[arr[i]]) v.push(arr[i]); } v.sort((a,b)=>b-a) var j = 0; // update the array elements for (var i = 0; i < n; i++) { if (prime[arr[i]]) arr[i] = v[j++]; }} // Driver codevar arr = [4, 3, 2, 6, 100, 17 ];var n = arr.length;sortPrimes(arr, n);// print the results.for (var i = 0; i < n; i++) { document.write( arr[i] + \" \");} </script>", "e": 8059, "s": 6868, "text": null }, { "code": null, "e": 8074, "s": 8059, "text": "4 17 3 6 100 2" }, { "code": null, "e": 8089, "s": 8076, "text": "rituraj_jain" }, { "code": null, "e": 8101, "s": 8089, "text": "29AjayKumar" }, { "code": null, "e": 8111, "s": 8101, "text": "Rajput-Ji" }, { "code": null, "e": 8118, "s": 8111, "text": "rrrtnx" }, { "code": null, "e": 8131, "s": 8118, "text": "Prime Number" }, { "code": null, "e": 8137, "s": 8131, "text": "sieve" }, { "code": null, "e": 8144, "s": 8137, "text": "Arrays" }, { "code": null, "e": 8168, "s": 8144, "text": "Competitive Programming" }, { "code": null, "e": 8181, "s": 8168, "text": "Mathematical" }, { "code": null, "e": 8189, "s": 8181, "text": "Sorting" }, { "code": null, "e": 8196, "s": 8189, "text": "Arrays" }, { "code": null, "e": 8209, "s": 8196, "text": "Mathematical" }, { "code": null, "e": 8217, "s": 8209, "text": "Sorting" }, { "code": null, "e": 8230, "s": 8217, "text": "Prime Number" }, { "code": null, "e": 8236, "s": 8230, "text": "sieve" } ]
Internal working of list in Python
09 Dec, 2021 Introduction to Python lists : Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becomes costly if preallocated space becomes full.We can create a list in python as shown below.Example: Python3 list1 = [1, 2, 3, 4] We can access each element of a list in python by their assigned index. In python starting index of list sequence is 0 and ending index is (if N elements are there) N-1. Also as shown in above array lists also have negative index starting from -N (if N elements in the list) till -1.Viewing the elements of List in Python : Individual items of a list can be accessed through their indexes as done in below code segment. Python3 list1 = [1, 2, 3, 4] # for printing only one item from a listprint(list1[1]) # to print a sequence of item in a list# we use ':' value before this is starting# and value after that tells ending of sequenceprint(list1[1:4]) # accessing through negative indexprint(list1[-1]) Assigning and Accessing data: For creating a list we need to specify the elements inside square brackets ‘[]’ and then give it a name. Whenever you want to access the list elements then use this list name and index of element you want to show. Each element in list is assigned an index in positive indexing we have index from 0 to end of the list and in negative indexing we have index from -N(if elements are N) till -1. As shown in above examples the work of accessing elements is manual. We can also access or assign elements through loops. Python3 # assigning elements to listlist1 =[]for i in range(0, 11): list1.append(i) # accessing elements from a listfor i in range(0, 11): print(list1[i]) Updating list: We can update already assigned elements to the list and also can append one element at a time to your list.Even you can extend your list by adding another list to current list. The above task can be performed as follows. Python3 list1 =[1, 2, 3, 4] # updatinglist1[2]= 5print(list1) # appendinglist1.append(6)print(list1) # extendinglist1.extend([1, 2, 3])print(list1) Note: append() and extend() are built in methods in python for lists.Deleting elements of list : We can delete elements in lists by making use of del function. In this you need to specify the position of element that is the index of the element and that element will be deleted from the list and index will be updated. In above shown image the element 3 in index 2 has been deleted and after that index has been updated. Python3 list1 = [1, 2, 3, 4, 5]print(list1) # deleting elementdel list1[2]print(list1) Time Complexities of Operations Source : Python WikiPython list and its operations. sweetyty Picked python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n09 Dec, 2021" }, { "code": null, "e": 455, "s": 53, "text": "Introduction to Python lists : Python lists are internally represented as arrays. The idea used is similar to implementation of vectors in C++ or ArrayList in Java. The costly operations are inserting and deleting items near the beginning (as everything has to be moved). Insert at the end also becomes costly if preallocated space becomes full.We can create a list in python as shown below.Example: " }, { "code": null, "e": 463, "s": 455, "text": "Python3" }, { "code": "list1 = [1, 2, 3, 4]", "e": 484, "s": 463, "text": null }, { "code": null, "e": 655, "s": 484, "text": "We can access each element of a list in python by their assigned index. In python starting index of list sequence is 0 and ending index is (if N elements are there) N-1. " }, { "code": null, "e": 907, "s": 655, "text": "Also as shown in above array lists also have negative index starting from -N (if N elements in the list) till -1.Viewing the elements of List in Python : Individual items of a list can be accessed through their indexes as done in below code segment. " }, { "code": null, "e": 915, "s": 907, "text": "Python3" }, { "code": "list1 = [1, 2, 3, 4] # for printing only one item from a listprint(list1[1]) # to print a sequence of item in a list# we use ':' value before this is starting# and value after that tells ending of sequenceprint(list1[1:4]) # accessing through negative indexprint(list1[-1])", "e": 1189, "s": 915, "text": null }, { "code": null, "e": 1734, "s": 1189, "text": "Assigning and Accessing data: For creating a list we need to specify the elements inside square brackets ‘[]’ and then give it a name. Whenever you want to access the list elements then use this list name and index of element you want to show. Each element in list is assigned an index in positive indexing we have index from 0 to end of the list and in negative indexing we have index from -N(if elements are N) till -1. As shown in above examples the work of accessing elements is manual. We can also access or assign elements through loops. " }, { "code": null, "e": 1742, "s": 1734, "text": "Python3" }, { "code": "# assigning elements to listlist1 =[]for i in range(0, 11): list1.append(i) # accessing elements from a listfor i in range(0, 11): print(list1[i])", "e": 1897, "s": 1742, "text": null }, { "code": null, "e": 2134, "s": 1897, "text": "Updating list: We can update already assigned elements to the list and also can append one element at a time to your list.Even you can extend your list by adding another list to current list. The above task can be performed as follows. " }, { "code": null, "e": 2142, "s": 2134, "text": "Python3" }, { "code": "list1 =[1, 2, 3, 4] # updatinglist1[2]= 5print(list1) # appendinglist1.append(6)print(list1) # extendinglist1.extend([1, 2, 3])print(list1)", "e": 2282, "s": 2142, "text": null }, { "code": null, "e": 2602, "s": 2282, "text": "Note: append() and extend() are built in methods in python for lists.Deleting elements of list : We can delete elements in lists by making use of del function. In this you need to specify the position of element that is the index of the element and that element will be deleted from the list and index will be updated. " }, { "code": null, "e": 2705, "s": 2602, "text": "In above shown image the element 3 in index 2 has been deleted and after that index has been updated. " }, { "code": null, "e": 2713, "s": 2705, "text": "Python3" }, { "code": "list1 = [1, 2, 3, 4, 5]print(list1) # deleting elementdel list1[2]print(list1)", "e": 2792, "s": 2713, "text": null }, { "code": null, "e": 2826, "s": 2792, "text": "Time Complexities of Operations " }, { "code": null, "e": 2879, "s": 2826, "text": "Source : Python WikiPython list and its operations. " }, { "code": null, "e": 2888, "s": 2879, "text": "sweetyty" }, { "code": null, "e": 2895, "s": 2888, "text": "Picked" }, { "code": null, "e": 2907, "s": 2895, "text": "python-list" }, { "code": null, "e": 2914, "s": 2907, "text": "Python" }, { "code": null, "e": 2926, "s": 2914, "text": "python-list" } ]
Express.js req.params Property
08 Jul, 2020 The req.params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id. This object defaults to {}. Syntax: req.params Parameter: No parameters. Return Value: Object Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express(); var PORT = 3000; app.get('/:id', function (req, res) { console.log(req.params['id']); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/123, now you can see the following output on your console:Server listening on PORT 3000 123 The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now open your browser and go to http://localhost:3000/123, now you can see the following output on your console:Server listening on PORT 3000 123 Server listening on PORT 3000 123 Example 2: Filename: index.js var express = require('express');const e = require('express');var app = express(); var PORT = 3000; var student = express.Router();app.use('/student', student); student.get('/profile/:start/:end', function (req, res) { console.log("Starting Page: ", req.params['start']); console.log("Ending Page: ", req.params['end']); res.send();}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Output:Now open your browser and make GET request to http://localhost:3000/student/profile/12/17, now you can see the following output on your console: Server listening on PORT 3000 Starting Page: 12 Ending Page: 17 Reference: https://expressjs.com/en/4x/api.html#req.params Express.js 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": "\n08 Jul, 2020" }, { "code": null, "e": 258, "s": 28, "text": "The req.params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id. This object defaults to {}." }, { "code": null, "e": 266, "s": 258, "text": "Syntax:" }, { "code": null, "e": 277, "s": 266, "text": "req.params" }, { "code": null, "e": 303, "s": 277, "text": "Parameter: No parameters." }, { "code": null, "e": 324, "s": 303, "text": "Return Value: Object" }, { "code": null, "e": 356, "s": 324, "text": "Installation of express module:" }, { "code": null, "e": 751, "s": 356, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 872, "s": 751, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 892, "s": 872, "text": "npm install express" }, { "code": null, "e": 1020, "s": 892, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 1040, "s": 1020, "text": "npm version express" }, { "code": null, "e": 1188, "s": 1040, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 1202, "s": 1188, "text": "node index.js" }, { "code": null, "e": 1232, "s": 1202, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express(); var PORT = 3000; app.get('/:id', function (req, res) { console.log(req.params['id']); res.send();}); app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 1506, "s": 1232, "text": null }, { "code": null, "e": 1532, "s": 1506, "text": "Steps to run the program:" }, { "code": null, "e": 1900, "s": 1532, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow open your browser and go to http://localhost:3000/123, now you can see the following output on your console:Server listening on PORT 3000\n123\n" }, { "code": null, "e": 1943, "s": 1900, "text": "The project structure will look like this:" }, { "code": null, "e": 2035, "s": 1943, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 2055, "s": 2035, "text": "npm install express" }, { "code": null, "e": 2144, "s": 2055, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 2158, "s": 2144, "text": "node index.js" }, { "code": null, "e": 2166, "s": 2158, "text": "Output:" }, { "code": null, "e": 2197, "s": 2166, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 2344, "s": 2197, "text": "Now open your browser and go to http://localhost:3000/123, now you can see the following output on your console:Server listening on PORT 3000\n123\n" }, { "code": null, "e": 2379, "s": 2344, "text": "Server listening on PORT 3000\n123\n" }, { "code": null, "e": 2409, "s": 2379, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');const e = require('express');var app = express(); var PORT = 3000; var student = express.Router();app.use('/student', student); student.get('/profile/:start/:end', function (req, res) { console.log(\"Starting Page: \", req.params['start']); console.log(\"Ending Page: \", req.params['end']); res.send();}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 2871, "s": 2409, "text": null }, { "code": null, "e": 2910, "s": 2871, "text": "Run index.js file using below command:" }, { "code": null, "e": 2924, "s": 2910, "text": "node index.js" }, { "code": null, "e": 3076, "s": 2924, "text": "Output:Now open your browser and make GET request to http://localhost:3000/student/profile/12/17, now you can see the following output on your console:" }, { "code": null, "e": 3143, "s": 3076, "text": "Server listening on PORT 3000\nStarting Page: 12\nEnding Page: 17\n" }, { "code": null, "e": 3202, "s": 3143, "text": "Reference: https://expressjs.com/en/4x/api.html#req.params" }, { "code": null, "e": 3213, "s": 3202, "text": "Express.js" }, { "code": null, "e": 3221, "s": 3213, "text": "Node.js" }, { "code": null, "e": 3238, "s": 3221, "text": "Web Technologies" } ]
Components of Storage Area Network (SAN)
11 Oct, 2021 Components of Storage Area Network (SAN) involves 3 basic components: (a). Server (b). Network Infrastructure (c). Storage The above elements are classified into following elements like, (1). Node port (2). Cables (3). Interconnection Devices (4). Storage Array, and (5). SAN Management Software These are explained as following below. 1. Node port:In fiber channel, devices like, Host Storage Tape Libraries are referred as nodes Nodes consists of ports for transmission between other nodes. Ports operate in Full-duplex data transmission mode with transmit(Tx) and Receive(Rx) link. 2. Cables:SAN implements optical fiber cabling. Copper cables are used for short distance connectivity and optical cables for long distance connection establishment.There are 2 types of optical cables: Multi-mode fiber and Single-mode fiber are as given below. Multi-mode fiber:Also called MMF, as it carries multiple rays of light projected at different angles simultaneously onto the core of the cable. In MMF transmission, light beam travelling inside the cable tend to disperse and collide. This collision, weakens the signal strength after it travels certain distance, and it is called modal dispersion.MMF cables are used for distance up-to 500 meters because of signal degradation(attenuation) due to modal dispersion.Single-mode fiber:Also called SMF, as it carries a single beam of light through the core of the fiber. Small core in the cable reduces modal dispersion. SMF cables are used for distance up-to 10 kilometers due to less attenuation. SMF is costlier than MMF. Multi-mode fiber:Also called MMF, as it carries multiple rays of light projected at different angles simultaneously onto the core of the cable. In MMF transmission, light beam travelling inside the cable tend to disperse and collide. This collision, weakens the signal strength after it travels certain distance, and it is called modal dispersion.MMF cables are used for distance up-to 500 meters because of signal degradation(attenuation) due to modal dispersion. MMF cables are used for distance up-to 500 meters because of signal degradation(attenuation) due to modal dispersion. Single-mode fiber:Also called SMF, as it carries a single beam of light through the core of the fiber. Small core in the cable reduces modal dispersion. SMF cables are used for distance up-to 10 kilometers due to less attenuation. SMF is costlier than MMF. Other than these cables, Standard Connectors (SC) and Lucent Connectors (LC) are commonly used fiber cables with data transmission speed up-to 1 Gbps and 4 Gbps respectively. Small Form-factor Pluggable (SFP) is an optical transceiver used in optical communication with transmission speed up-to 10 Gbps. 3. Interconnection Devices:The commonly used interconnection devices in SAN are: HubsSwitches andDirectors Hubs Switches and Directors Hubs are communication devices used in fiber cable implementations. They connect nodes in loop or star topology.Switches are more intelligent than hubs. They directly route data from one port to other. They are cheap and their performance is better than hubs.Directors are larger than switches, used for data center implementations. Directors have high fault tolerance and high port count than switches. 4. Storage Array: A disk array also called a storage array, is a data storage system used for block-based storage, file-based storage, or object storage. The term is used to describe dedicated storage hardware that contains spinning hard disk drives (HDDs) or solid-state drives (SSDs). The fundamental purpose of a SAN is to provide host access to storage resources. SAN storage implementations provides: high availability and redundancy, improved performance, business continuity and multiple host connectivity. 5. SAN Management Software:This software manages the interface between the host, interconnection devices, and storage arrays. It includes key management functions like mapping of storage devices, switches, and logical partitioning of SAN, called zoning. It also manages the important components of SAN like storage devices and interconnection devices. yasara218 DBMS Misc Misc Misc DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL Difference between Clustered and Non-clustered index Introduction of DBMS (Database Management System) | Set 1 Introduction of B-Tree SQL Trigger | Student Database 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 How to write Regular Expressions? Program for nth Catalan Number
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2021" }, { "code": null, "e": 98, "s": 28, "text": "Components of Storage Area Network (SAN) involves 3 basic components:" }, { "code": null, "e": 152, "s": 98, "text": "(a). Server \n(b). Network Infrastructure\n(c). Storage" }, { "code": null, "e": 216, "s": 152, "text": "The above elements are classified into following elements like," }, { "code": null, "e": 326, "s": 216, "text": "(1). Node port\n(2). Cables\n(3). Interconnection Devices\n(4). Storage Array, and\n(5). SAN Management Software " }, { "code": null, "e": 366, "s": 326, "text": "These are explained as following below." }, { "code": null, "e": 411, "s": 366, "text": "1. Node port:In fiber channel, devices like," }, { "code": null, "e": 416, "s": 411, "text": "Host" }, { "code": null, "e": 424, "s": 416, "text": "Storage" }, { "code": null, "e": 461, "s": 424, "text": "Tape Libraries are referred as nodes" }, { "code": null, "e": 615, "s": 461, "text": "Nodes consists of ports for transmission between other nodes. Ports operate in Full-duplex data transmission mode with transmit(Tx) and Receive(Rx) link." }, { "code": null, "e": 876, "s": 615, "text": "2. Cables:SAN implements optical fiber cabling. Copper cables are used for short distance connectivity and optical cables for long distance connection establishment.There are 2 types of optical cables: Multi-mode fiber and Single-mode fiber are as given below." }, { "code": null, "e": 1597, "s": 876, "text": "Multi-mode fiber:Also called MMF, as it carries multiple rays of light projected at different angles simultaneously onto the core of the cable. In MMF transmission, light beam travelling inside the cable tend to disperse and collide. This collision, weakens the signal strength after it travels certain distance, and it is called modal dispersion.MMF cables are used for distance up-to 500 meters because of signal degradation(attenuation) due to modal dispersion.Single-mode fiber:Also called SMF, as it carries a single beam of light through the core of the fiber. Small core in the cable reduces modal dispersion. SMF cables are used for distance up-to 10 kilometers due to less attenuation. SMF is costlier than MMF." }, { "code": null, "e": 2062, "s": 1597, "text": "Multi-mode fiber:Also called MMF, as it carries multiple rays of light projected at different angles simultaneously onto the core of the cable. In MMF transmission, light beam travelling inside the cable tend to disperse and collide. This collision, weakens the signal strength after it travels certain distance, and it is called modal dispersion.MMF cables are used for distance up-to 500 meters because of signal degradation(attenuation) due to modal dispersion." }, { "code": null, "e": 2180, "s": 2062, "text": "MMF cables are used for distance up-to 500 meters because of signal degradation(attenuation) due to modal dispersion." }, { "code": null, "e": 2437, "s": 2180, "text": "Single-mode fiber:Also called SMF, as it carries a single beam of light through the core of the fiber. Small core in the cable reduces modal dispersion. SMF cables are used for distance up-to 10 kilometers due to less attenuation. SMF is costlier than MMF." }, { "code": null, "e": 2741, "s": 2437, "text": "Other than these cables, Standard Connectors (SC) and Lucent Connectors (LC) are commonly used fiber cables with data transmission speed up-to 1 Gbps and 4 Gbps respectively. Small Form-factor Pluggable (SFP) is an optical transceiver used in optical communication with transmission speed up-to 10 Gbps." }, { "code": null, "e": 2822, "s": 2741, "text": "3. Interconnection Devices:The commonly used interconnection devices in SAN are:" }, { "code": null, "e": 2848, "s": 2822, "text": "HubsSwitches andDirectors" }, { "code": null, "e": 2853, "s": 2848, "text": "Hubs" }, { "code": null, "e": 2866, "s": 2853, "text": "Switches and" }, { "code": null, "e": 2876, "s": 2866, "text": "Directors" }, { "code": null, "e": 3280, "s": 2876, "text": "Hubs are communication devices used in fiber cable implementations. They connect nodes in loop or star topology.Switches are more intelligent than hubs. They directly route data from one port to other. They are cheap and their performance is better than hubs.Directors are larger than switches, used for data center implementations. Directors have high fault tolerance and high port count than switches." }, { "code": null, "e": 3298, "s": 3280, "text": "4. Storage Array:" }, { "code": null, "e": 3567, "s": 3298, "text": "A disk array also called a storage array, is a data storage system used for block-based storage, file-based storage, or object storage. The term is used to describe dedicated storage hardware that contains spinning hard disk drives (HDDs) or solid-state drives (SSDs)." }, { "code": null, "e": 3686, "s": 3567, "text": "The fundamental purpose of a SAN is to provide host access to storage resources. SAN storage implementations provides:" }, { "code": null, "e": 3720, "s": 3686, "text": "high availability and redundancy," }, { "code": null, "e": 3742, "s": 3720, "text": "improved performance," }, { "code": null, "e": 3766, "s": 3742, "text": "business continuity and" }, { "code": null, "e": 3794, "s": 3766, "text": "multiple host connectivity." }, { "code": null, "e": 4146, "s": 3794, "text": "5. SAN Management Software:This software manages the interface between the host, interconnection devices, and storage arrays. It includes key management functions like mapping of storage devices, switches, and logical partitioning of SAN, called zoning. It also manages the important components of SAN like storage devices and interconnection devices." }, { "code": null, "e": 4156, "s": 4146, "text": "yasara218" }, { "code": null, "e": 4161, "s": 4156, "text": "DBMS" }, { "code": null, "e": 4166, "s": 4161, "text": "Misc" }, { "code": null, "e": 4171, "s": 4166, "text": "Misc" }, { "code": null, "e": 4176, "s": 4171, "text": "Misc" }, { "code": null, "e": 4181, "s": 4176, "text": "DBMS" }, { "code": null, "e": 4279, "s": 4181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4290, "s": 4279, "text": "CTE in SQL" }, { "code": null, "e": 4343, "s": 4290, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 4401, "s": 4343, "text": "Introduction of DBMS (Database Management System) | Set 1" }, { "code": null, "e": 4424, "s": 4401, "text": "Introduction of B-Tree" }, { "code": null, "e": 4455, "s": 4424, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 4516, "s": 4455, "text": "Overview of Data Structures | Set 1 (Linear Data Structures)" }, { "code": null, "e": 4570, "s": 4516, "text": "vector::push_back() and vector::pop_back() in C++ STL" }, { "code": null, "e": 4611, "s": 4570, "text": "Top 10 algorithms in Interview Questions" }, { "code": null, "e": 4645, "s": 4611, "text": "How to write Regular Expressions?" } ]
Get video duration using Python – OpenCV
02 Dec, 2020 Prerequisites: Opencv module datetime module OpenCV is one of the most popular cross-platform libraries and it is widely used in Deep Learning, image processing, video capturing, and many more. In this article, we will learn how to get the duration of a given video using python and computer vision. Opencv can be downloaded by running the given command on the terminal: pip install Opencv To get the duration of a video, following steps has to be followed: Import required modules. Create a VideoCapture object by providing video URL to VideoCapture() method. Syntax: VideoCapture("url") Count the total numbers of frames and frames per second of a given video by providing cv2.CAP_PROP_FRAME_COUNT and cv2.CAP_PROP_FPS to get() method. Calculate the duration of the video in seconds by dividing frames and fps. Also, calculate video time using timedelta() method. Syntax: timedelta(time) Below is the implementation. Python3 # import moduleimport cv2import datetime # create video capture objectdata = cv2.VideoCapture('C:/Users/Asus/Documents/videoDuration.mp4') # count the number of framesframes = data.get(cv2.CAP_PROP_FRAME_COUNT)fps = int(data.get(cv2.CAP_PROP_FPS)) # calculate dusration of the videoseconds = int(frames / fps)video_time = str(datetime.timedelta(seconds=seconds))print("duration in seconds:", seconds)print("video time:", video_time) Output : duration in seconds: 32 video time: 0:00:28 Python-OpenCV Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2020" }, { "code": null, "e": 44, "s": 28, "text": "Prerequisites: " }, { "code": null, "e": 58, "s": 44, "text": "Opencv module" }, { "code": null, "e": 74, "s": 58, "text": "datetime module" }, { "code": null, "e": 330, "s": 74, "text": "OpenCV is one of the most popular cross-platform libraries and it is widely used in Deep Learning, image processing, video capturing, and many more. In this article, we will learn how to get the duration of a given video using python and computer vision. " }, { "code": null, "e": 401, "s": 330, "text": "Opencv can be downloaded by running the given command on the terminal:" }, { "code": null, "e": 420, "s": 401, "text": "pip install Opencv" }, { "code": null, "e": 488, "s": 420, "text": "To get the duration of a video, following steps has to be followed:" }, { "code": null, "e": 513, "s": 488, "text": "Import required modules." }, { "code": null, "e": 592, "s": 513, "text": "Create a VideoCapture object by providing video URL to VideoCapture() method." }, { "code": null, "e": 600, "s": 592, "text": "Syntax:" }, { "code": null, "e": 620, "s": 600, "text": "VideoCapture(\"url\")" }, { "code": null, "e": 770, "s": 620, "text": "Count the total numbers of frames and frames per second of a given video by providing cv2.CAP_PROP_FRAME_COUNT and cv2.CAP_PROP_FPS to get() method." }, { "code": null, "e": 845, "s": 770, "text": "Calculate the duration of the video in seconds by dividing frames and fps." }, { "code": null, "e": 898, "s": 845, "text": "Also, calculate video time using timedelta() method." }, { "code": null, "e": 906, "s": 898, "text": "Syntax:" }, { "code": null, "e": 922, "s": 906, "text": "timedelta(time)" }, { "code": null, "e": 951, "s": 922, "text": "Below is the implementation." }, { "code": null, "e": 959, "s": 951, "text": "Python3" }, { "code": "# import moduleimport cv2import datetime # create video capture objectdata = cv2.VideoCapture('C:/Users/Asus/Documents/videoDuration.mp4') # count the number of framesframes = data.get(cv2.CAP_PROP_FRAME_COUNT)fps = int(data.get(cv2.CAP_PROP_FPS)) # calculate dusration of the videoseconds = int(frames / fps)video_time = str(datetime.timedelta(seconds=seconds))print(\"duration in seconds:\", seconds)print(\"video time:\", video_time)", "e": 1395, "s": 959, "text": null }, { "code": null, "e": 1404, "s": 1395, "text": "Output :" }, { "code": null, "e": 1448, "s": 1404, "text": "duration in seconds: 32\nvideo time: 0:00:28" }, { "code": null, "e": 1462, "s": 1448, "text": "Python-OpenCV" }, { "code": null, "e": 1486, "s": 1462, "text": "Technical Scripter 2020" }, { "code": null, "e": 1493, "s": 1486, "text": "Python" }, { "code": null, "e": 1512, "s": 1493, "text": "Technical Scripter" } ]
Program to find Class, Broadcast and Network addresses
20 Jan, 2022 Prerequisite – Introduction and Classful Addressing, Classless Addressing Given a valid IPv4 address in the form of a string. The task is to determine the class of the given IPv4 address as well as separate Network and Host ID parts from it.IPv4 address: Every host and router on the internet has an IP address that encodes its network number and host number, a combination of the two is unique. An IP address does not actually refer to a host but refers to a network interface, so if the host is on two networks, it must have two IP addresses.Default Mask: An address mask determines which portion of an IP address represents network number and which part represents host number, e.g., IP address, the mask has four octets. If a given bit of the mask is 1, the corresponding bit of the IP address is the in-network portion and if the given bit of the mask is 0, the corresponding bit of the IP address is in the host portion. CIDR: Classless Inter-Domain Routing uses slash(/) notation to specify the mask with IPv4 address. The address is given as x.y.z.t/n where x.y.z.t is the IP address and n is the number of 1’s in the default mask.Network address: The first address of a network is a network address. It is obtained by ANDing the mask with the IP address (Both in binary form). Another method is to set the last 32-n bits of the IP address to 0.Broadcast address: The last address of a network is a broadcast address. It is obtained by ORing the complement mask with the IP address(Both in binary form). Another method is to set the last 32-n bits of the IP address to 1.Class: The class of an address is identified by the first byte of the address. There are currently five classes A, B, C, D, and E. The range of the first byte of each class is: Class A: 0 - 127 Class B: 128 - 191 Class C: 192 - 223 Class D: 224 - 239 Class E: 240 - 255 Example-1: CIDR: 192.168.32.1/24(x.y.z.t/n) IP Address(Binary): 11000000101010000010000000000001 Default Mask(Binary): 11111111111111111111111100000000 Default Mask: 255.255.255.0 32-n=32-24=8 First Address: Set last 8 bits of IP address to 0 = 11000000101010000010000000000000 = 192.168.32.0 Last Address: Set last 8 bits of IP address to 1 = 11000000101010000010000011111111 = 192.168.32.255 Example-2: CIDR: 205.15.37.39/28(x.y.z.t/n) IP Address(Binary): 11001101000011110010010100100111 Default Mask(Binary): 11111111111111111111111111110000 Default Mask: 255.255.255.240 32-n=32-28=4 First Address: Set last 4 bits of IP address to 0 = 11001101000011110010010100100000 = 205.15.37.32 Last Address: Set last 4 bits of IP address to 1 = 11001101000011110010010100101111 = 205.15.37.47 Implementation: The following code uses the concepts mentioned above: C++ Java #include <iostream>#include <string.h>#include <stack>#include <vector>#include <math.h> using namespace std; // Converts IP address to the binary formvector<int> bina(vector<string> str) { vector<int> re(32,0); int a, b, c, d, i, rem; a = b = c = d = 1; stack<int> st; // Separate each number of the IP address a = stoi(str[0]); b = stoi(str[1]); c = stoi(str[2]); d = stoi(str[3]); // convert first number to binary for (i = 0; i <= 7; i++) { rem = a % 2; st.push(rem); a = a / 2; } // Obtain First octet for (i = 0; i <= 7; i++) { re[i] = st.top(); st.pop(); } // convert second number to binary for (i = 8; i <= 15; i++) { rem = b % 2; st.push(rem); b = b / 2; } // Obtain Second octet for (i = 8; i <= 15; i++) { re[i] = st.top(); st.pop(); } // convert Third number to binary for (i = 16; i <= 23; i++) { rem = c % 2; st.push(rem); c = c / 2; } // Obtain Third octet for (i = 16; i <= 23; i++) { re[i] = st.top(); st.pop(); } // convert fourth number to binary for (i = 24; i <= 31; i++) { rem = d % 2; st.push(rem); d = d / 2; } // Obtain Fourth octet for (i = 24; i <= 31; i++) { re[i] = st.top(); st.pop(); } return (re); } // cls returns class of given IP addresschar cls(vector<string> str) { int a = stoi(str[0]); if (a >= 0 && a <= 127) return ('A'); else if (a >= 128 && a <= 191) return ('B'); else if (a >= 192 && a <= 223) return ('C'); else if (a >= 224 && a <= 239) return ('D'); else return ('E'); } // Converts IP address // from binary to decimal formvector<int> deci(vector<int> bi) { vector<int> arr(4,0); int a, b, c, d, i, j; a = b = c = d = 0; j = 7; for (i = 0; i < 8; i++) { a = a + (int)(pow(2, j)) * bi[i]; j--; } j = 7; for (i = 8; i < 16; i++) { b = b + bi[i] * (int)(pow(2, j)); j--; } j = 7; for (i = 16; i < 24; i++) { c = c + bi[i] * (int)(pow(2, j)); j--; } j = 7; for (i = 24; i < 32; i++) { d = d + bi[i] * (int)(pow(2, j)); j--; } arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; return arr; } int main() { string ipr = "192.168.1.1/24"; // You can take user input here // instead of using default address // Ask user to enter IP address of form(x.y.z.t/n) cout<<"IP address CIDR format is:"<< ipr; // Separate IP address and n string str1 = ""; int idx = 0; int len = ipr.size(); len -= 3; while(len--){ str1 += ipr[idx]; idx++; } cout<<endl; cout<<"IP Address : " <<str1<<endl; string str2 = ""; idx++; str2 += ipr[idx]; idx++; str2 += ipr[idx]; cout<<"Value of n : "<< str2<<endl; // IP address string tr = str1; // Split IP address into 4 subparts x, y, z, t //str = tr.split("\\."); vector<string> str; string temp; int n = tr.size(); for(int i = 0; i < n; i++){ if(tr[i] >= 48 && tr[i] <= 57) temp +=tr[i]; else{ str.push_back(temp); temp = ""; } } str.push_back(temp); //cout<<str[0]<<endl<<str[1]<<endl<<str[2]<<endl<<str[3]<<endl; vector<int> b; cout<<endl; // Convert IP address to binary form b = bina(str); n = stoi(str2); vector<int> ntwk(32,0); vector<int> brd(32,0); int t = 32 - n; // Obtaining network address for (int i = 0; i <= (31 - t); i++) { ntwk[i] = b[i]; brd[i] = b[i]; } // Set 32-n bits to 0 for (int i = 31; i > (31 - t); i--) { ntwk[i] = 0; } // Obtaining Broadcast address // by setting 32-n bits to 1 for (int i = 31; i > (31 - t); i--) { brd[i] = 1; } cout<<endl; // Obtaining class of Address char c = cls(str); cout<<"Class : " << c << endl; // Converting network address to decimal vector<int> nt = deci(ntwk); // Converting broadcast address to decimal vector<int> br = deci(brd); // Printing in dotted decimal format cout<<"First Address : " << nt[0] << "." <<nt[1] <<"." << nt[2] <<"." << nt[3]<<endl; // Printing in dotted decimal format cout<<"Last Address : " <<br[0] << "." <<br[1] << "." << br[2] <<"." << br[3] << endl; //Printing Number of Addresses in Block cout<<"Total Number of Addresses :" <<br[3]-nt[3]+1<<endl; return 0;} import java.util.*;import java.io.*;import java.net.*;import java.lang.Math; class Ip { // Converts IP address to the binary form public static int[] bina(String[] str) { int re[] = new int[32]; int a, b, c, d, i, rem; a = b = c = d = 1; Stack<Integer> st = new Stack<Integer>(); // Separate each number of the IP address if (str != null) { a = Integer.parseInt(str[0]); b = Integer.parseInt(str[1]); c = Integer.parseInt(str[2]); d = Integer.parseInt(str[3]); } // convert first number to binary for (i = 0; i <= 7; i++) { rem = a % 2; st.push(rem); a = a / 2; } // Obtain First octet for (i = 0; i <= 7; i++) { re[i] = st.pop(); } // convert second number to binary for (i = 8; i <= 15; i++) { rem = b % 2; st.push(rem); b = b / 2; } // Obtain Second octet for (i = 8; i <= 15; i++) { re[i] = st.pop(); } // convert Third number to binary for (i = 16; i <= 23; i++) { rem = c % 2; st.push(rem); c = c / 2; } // Obtain Third octet for (i = 16; i <= 23; i++) { re[i] = st.pop(); } // convert fourth number to binary for (i = 24; i <= 31; i++) { rem = d % 2; st.push(rem); d = d / 2; } // Obtain Fourth octet for (i = 24; i <= 31; i++) { re[i] = st.pop(); } return (re); } // cls returns class of given IP address public static char cls(String[] str) { int a = Integer.parseInt(str[0]); if (a >= 0 && a <= 127) return ('A'); else if (a >= 128 && a <= 191) return ('B'); else if (a >= 192 && a <= 223) return ('C'); else if (a >= 224 && a <= 239) return ('D'); else return ('E'); } // Converts IP address // from binary to decimal form public static int[] deci(int[] bi) { int[] arr = new int[4]; int a, b, c, d, i, j; a = b = c = d = 0; j = 7; for (i = 0; i < 8; i++) { a = a + (int)(Math.pow(2, j)) * bi[i]; j--; } j = 7; for (i = 8; i < 16; i++) { b = b + bi[i] * (int)(Math.pow(2, j)); j--; } j = 7; for (i = 16; i < 24; i++) { c = c + bi[i] * (int)(Math.pow(2, j)); j--; } j = 7; for (i = 24; i < 32; i++) { d = d + bi[i] * (int)(Math.pow(2, j)); j--; } arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; return arr; } public static void main(String args[]) { int i; String[] str = new String[4]; String ipr = "192.168.1.1/24"; // You can take user input here // instead of using default address // Ask user to enter IP address of form(x.y.z.t/n) System.out.println("IP address CIDR format is:" + ipr); // Separate IP address and n String[] str1 = ipr.split("/"); // IP address String tr = str1[0]; // Split IP address into 4 subparts x, y, z, t str = tr.split("\\."); int[] b = new int[32]; System.out.println(); // Convert IP address to binary form b = bina(str); int n = Integer.parseInt(str1[1]); int[] ntwk = new int[32]; int[] brd = new int[32]; int t = 32 - n; // Obtaining network address for (i = 0; i <= (31 - t); i++) { ntwk[i] = b[i]; brd[i] = b[i]; } // Set 32-n bits to 0 for (i = 31; i > (31 - t); i--) { ntwk[i] = 0; } // Obtaining Broadcast address // by setting 32-n bits to 1 for (i = 31; i > (31 - t); i--) { brd[i] = 1; } System.out.println(); // Obtaining class of Address char c = cls(str); System.out.println("Class : " + c); // Converting network address to decimal int[] nt = deci(ntwk); // Converting broadcast address to decimal int[] br = deci(brd); // Printing in dotted decimal format System.out.println("Network Address : " + nt[0] + "." + nt[1] + "." + nt[2] + "." + nt[3]); // Printing in dotted decimal format System.out.println("Broadcast Address : " + br[0] + "." + br[1] + "." + br[2] + "." + br[3]); }} Output: IP address CIDR format is:192.168.1.1/24 Class : C Network Address : 192.168.1.0 Broadcast Address : 192.168.1.255 kaustubhdwivedi1729 vaibhavsinghtanwar3 avtarkumar719 Computer Networks-IP Addressing Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jan, 2022" }, { "code": null, "e": 981, "s": 53, "text": "Prerequisite – Introduction and Classful Addressing, Classless Addressing Given a valid IPv4 address in the form of a string. The task is to determine the class of the given IPv4 address as well as separate Network and Host ID parts from it.IPv4 address: Every host and router on the internet has an IP address that encodes its network number and host number, a combination of the two is unique. An IP address does not actually refer to a host but refers to a network interface, so if the host is on two networks, it must have two IP addresses.Default Mask: An address mask determines which portion of an IP address represents network number and which part represents host number, e.g., IP address, the mask has four octets. If a given bit of the mask is 1, the corresponding bit of the IP address is the in-network portion and if the given bit of the mask is 0, the corresponding bit of the IP address is in the host portion. " }, { "code": null, "e": 1811, "s": 981, "text": "CIDR: Classless Inter-Domain Routing uses slash(/) notation to specify the mask with IPv4 address. The address is given as x.y.z.t/n where x.y.z.t is the IP address and n is the number of 1’s in the default mask.Network address: The first address of a network is a network address. It is obtained by ANDing the mask with the IP address (Both in binary form). Another method is to set the last 32-n bits of the IP address to 0.Broadcast address: The last address of a network is a broadcast address. It is obtained by ORing the complement mask with the IP address(Both in binary form). Another method is to set the last 32-n bits of the IP address to 1.Class: The class of an address is identified by the first byte of the address. There are currently five classes A, B, C, D, and E. The range of the first byte of each class is: " }, { "code": null, "e": 1905, "s": 1811, "text": "Class A: 0 - 127\nClass B: 128 - 191\nClass C: 192 - 223\nClass D: 224 - 239\nClass E: 240 - 255 " }, { "code": null, "e": 1917, "s": 1905, "text": "Example-1: " }, { "code": null, "e": 2365, "s": 1917, "text": "CIDR: 192.168.32.1/24(x.y.z.t/n)\nIP Address(Binary): 11000000101010000010000000000001\nDefault Mask(Binary): 11111111111111111111111100000000\nDefault Mask: 255.255.255.0\n\n32-n=32-24=8 \n\nFirst Address: Set last 8 bits of IP address to 0\n = 11000000101010000010000000000000\n = 192.168.32.0\n\nLast Address: Set last 8 bits of IP address to 1\n = 11000000101010000010000011111111\n = 192.168.32.255 " }, { "code": null, "e": 2377, "s": 2365, "text": "Example-2: " }, { "code": null, "e": 2824, "s": 2377, "text": "CIDR: 205.15.37.39/28(x.y.z.t/n)\nIP Address(Binary): 11001101000011110010010100100111\nDefault Mask(Binary): 11111111111111111111111111110000\nDefault Mask: 255.255.255.240\n\n32-n=32-28=4 \n\nFirst Address: Set last 4 bits of IP address to 0\n = 11001101000011110010010100100000\n = 205.15.37.32\n\nLast Address: Set last 4 bits of IP address to 1\n = 11001101000011110010010100101111\n = 205.15.37.47 " }, { "code": null, "e": 2894, "s": 2824, "text": "Implementation: The following code uses the concepts mentioned above:" }, { "code": null, "e": 2898, "s": 2894, "text": "C++" }, { "code": null, "e": 2903, "s": 2898, "text": "Java" }, { "code": "#include <iostream>#include <string.h>#include <stack>#include <vector>#include <math.h> using namespace std; // Converts IP address to the binary formvector<int> bina(vector<string> str) { vector<int> re(32,0); int a, b, c, d, i, rem; a = b = c = d = 1; stack<int> st; // Separate each number of the IP address a = stoi(str[0]); b = stoi(str[1]); c = stoi(str[2]); d = stoi(str[3]); // convert first number to binary for (i = 0; i <= 7; i++) { rem = a % 2; st.push(rem); a = a / 2; } // Obtain First octet for (i = 0; i <= 7; i++) { re[i] = st.top(); st.pop(); } // convert second number to binary for (i = 8; i <= 15; i++) { rem = b % 2; st.push(rem); b = b / 2; } // Obtain Second octet for (i = 8; i <= 15; i++) { re[i] = st.top(); st.pop(); } // convert Third number to binary for (i = 16; i <= 23; i++) { rem = c % 2; st.push(rem); c = c / 2; } // Obtain Third octet for (i = 16; i <= 23; i++) { re[i] = st.top(); st.pop(); } // convert fourth number to binary for (i = 24; i <= 31; i++) { rem = d % 2; st.push(rem); d = d / 2; } // Obtain Fourth octet for (i = 24; i <= 31; i++) { re[i] = st.top(); st.pop(); } return (re); } // cls returns class of given IP addresschar cls(vector<string> str) { int a = stoi(str[0]); if (a >= 0 && a <= 127) return ('A'); else if (a >= 128 && a <= 191) return ('B'); else if (a >= 192 && a <= 223) return ('C'); else if (a >= 224 && a <= 239) return ('D'); else return ('E'); } // Converts IP address // from binary to decimal formvector<int> deci(vector<int> bi) { vector<int> arr(4,0); int a, b, c, d, i, j; a = b = c = d = 0; j = 7; for (i = 0; i < 8; i++) { a = a + (int)(pow(2, j)) * bi[i]; j--; } j = 7; for (i = 8; i < 16; i++) { b = b + bi[i] * (int)(pow(2, j)); j--; } j = 7; for (i = 16; i < 24; i++) { c = c + bi[i] * (int)(pow(2, j)); j--; } j = 7; for (i = 24; i < 32; i++) { d = d + bi[i] * (int)(pow(2, j)); j--; } arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; return arr; } int main() { string ipr = \"192.168.1.1/24\"; // You can take user input here // instead of using default address // Ask user to enter IP address of form(x.y.z.t/n) cout<<\"IP address CIDR format is:\"<< ipr; // Separate IP address and n string str1 = \"\"; int idx = 0; int len = ipr.size(); len -= 3; while(len--){ str1 += ipr[idx]; idx++; } cout<<endl; cout<<\"IP Address : \" <<str1<<endl; string str2 = \"\"; idx++; str2 += ipr[idx]; idx++; str2 += ipr[idx]; cout<<\"Value of n : \"<< str2<<endl; // IP address string tr = str1; // Split IP address into 4 subparts x, y, z, t //str = tr.split(\"\\\\.\"); vector<string> str; string temp; int n = tr.size(); for(int i = 0; i < n; i++){ if(tr[i] >= 48 && tr[i] <= 57) temp +=tr[i]; else{ str.push_back(temp); temp = \"\"; } } str.push_back(temp); //cout<<str[0]<<endl<<str[1]<<endl<<str[2]<<endl<<str[3]<<endl; vector<int> b; cout<<endl; // Convert IP address to binary form b = bina(str); n = stoi(str2); vector<int> ntwk(32,0); vector<int> brd(32,0); int t = 32 - n; // Obtaining network address for (int i = 0; i <= (31 - t); i++) { ntwk[i] = b[i]; brd[i] = b[i]; } // Set 32-n bits to 0 for (int i = 31; i > (31 - t); i--) { ntwk[i] = 0; } // Obtaining Broadcast address // by setting 32-n bits to 1 for (int i = 31; i > (31 - t); i--) { brd[i] = 1; } cout<<endl; // Obtaining class of Address char c = cls(str); cout<<\"Class : \" << c << endl; // Converting network address to decimal vector<int> nt = deci(ntwk); // Converting broadcast address to decimal vector<int> br = deci(brd); // Printing in dotted decimal format cout<<\"First Address : \" << nt[0] << \".\" <<nt[1] <<\".\" << nt[2] <<\".\" << nt[3]<<endl; // Printing in dotted decimal format cout<<\"Last Address : \" <<br[0] << \".\" <<br[1] << \".\" << br[2] <<\".\" << br[3] << endl; //Printing Number of Addresses in Block cout<<\"Total Number of Addresses :\" <<br[3]-nt[3]+1<<endl; return 0;}", "e": 8194, "s": 2903, "text": null }, { "code": "import java.util.*;import java.io.*;import java.net.*;import java.lang.Math; class Ip { // Converts IP address to the binary form public static int[] bina(String[] str) { int re[] = new int[32]; int a, b, c, d, i, rem; a = b = c = d = 1; Stack<Integer> st = new Stack<Integer>(); // Separate each number of the IP address if (str != null) { a = Integer.parseInt(str[0]); b = Integer.parseInt(str[1]); c = Integer.parseInt(str[2]); d = Integer.parseInt(str[3]); } // convert first number to binary for (i = 0; i <= 7; i++) { rem = a % 2; st.push(rem); a = a / 2; } // Obtain First octet for (i = 0; i <= 7; i++) { re[i] = st.pop(); } // convert second number to binary for (i = 8; i <= 15; i++) { rem = b % 2; st.push(rem); b = b / 2; } // Obtain Second octet for (i = 8; i <= 15; i++) { re[i] = st.pop(); } // convert Third number to binary for (i = 16; i <= 23; i++) { rem = c % 2; st.push(rem); c = c / 2; } // Obtain Third octet for (i = 16; i <= 23; i++) { re[i] = st.pop(); } // convert fourth number to binary for (i = 24; i <= 31; i++) { rem = d % 2; st.push(rem); d = d / 2; } // Obtain Fourth octet for (i = 24; i <= 31; i++) { re[i] = st.pop(); } return (re); } // cls returns class of given IP address public static char cls(String[] str) { int a = Integer.parseInt(str[0]); if (a >= 0 && a <= 127) return ('A'); else if (a >= 128 && a <= 191) return ('B'); else if (a >= 192 && a <= 223) return ('C'); else if (a >= 224 && a <= 239) return ('D'); else return ('E'); } // Converts IP address // from binary to decimal form public static int[] deci(int[] bi) { int[] arr = new int[4]; int a, b, c, d, i, j; a = b = c = d = 0; j = 7; for (i = 0; i < 8; i++) { a = a + (int)(Math.pow(2, j)) * bi[i]; j--; } j = 7; for (i = 8; i < 16; i++) { b = b + bi[i] * (int)(Math.pow(2, j)); j--; } j = 7; for (i = 16; i < 24; i++) { c = c + bi[i] * (int)(Math.pow(2, j)); j--; } j = 7; for (i = 24; i < 32; i++) { d = d + bi[i] * (int)(Math.pow(2, j)); j--; } arr[0] = a; arr[1] = b; arr[2] = c; arr[3] = d; return arr; } public static void main(String args[]) { int i; String[] str = new String[4]; String ipr = \"192.168.1.1/24\"; // You can take user input here // instead of using default address // Ask user to enter IP address of form(x.y.z.t/n) System.out.println(\"IP address CIDR format is:\" + ipr); // Separate IP address and n String[] str1 = ipr.split(\"/\"); // IP address String tr = str1[0]; // Split IP address into 4 subparts x, y, z, t str = tr.split(\"\\\\.\"); int[] b = new int[32]; System.out.println(); // Convert IP address to binary form b = bina(str); int n = Integer.parseInt(str1[1]); int[] ntwk = new int[32]; int[] brd = new int[32]; int t = 32 - n; // Obtaining network address for (i = 0; i <= (31 - t); i++) { ntwk[i] = b[i]; brd[i] = b[i]; } // Set 32-n bits to 0 for (i = 31; i > (31 - t); i--) { ntwk[i] = 0; } // Obtaining Broadcast address // by setting 32-n bits to 1 for (i = 31; i > (31 - t); i--) { brd[i] = 1; } System.out.println(); // Obtaining class of Address char c = cls(str); System.out.println(\"Class : \" + c); // Converting network address to decimal int[] nt = deci(ntwk); // Converting broadcast address to decimal int[] br = deci(brd); // Printing in dotted decimal format System.out.println(\"Network Address : \" + nt[0] + \".\" + nt[1] + \".\" + nt[2] + \".\" + nt[3]); // Printing in dotted decimal format System.out.println(\"Broadcast Address : \" + br[0] + \".\" + br[1] + \".\" + br[2] + \".\" + br[3]); }}", "e": 13213, "s": 8194, "text": null }, { "code": null, "e": 13222, "s": 13213, "text": "Output: " }, { "code": null, "e": 13340, "s": 13222, "text": "IP address CIDR format is:192.168.1.1/24\n\n\nClass : C\nNetwork Address : 192.168.1.0\nBroadcast Address : 192.168.1.255 " }, { "code": null, "e": 13362, "s": 13342, "text": "kaustubhdwivedi1729" }, { "code": null, "e": 13382, "s": 13362, "text": "vaibhavsinghtanwar3" }, { "code": null, "e": 13396, "s": 13382, "text": "avtarkumar719" }, { "code": null, "e": 13428, "s": 13396, "text": "Computer Networks-IP Addressing" }, { "code": null, "e": 13446, "s": 13428, "text": "Computer Networks" }, { "code": null, "e": 13464, "s": 13446, "text": "Computer Networks" } ]
JavaFX | Line with examples
14 Apr, 2021 Line is a part of JavaFX. The Line class represents a line in a 2D space.Constructor for the class: Line(): Creates a new instance for lineLine(double startX, double startY, double endX, double endY): Creates a new Line with specified starting and ending point Line(): Creates a new instance for line Line(double startX, double startY, double endX, double endY): Creates a new Line with specified starting and ending point Commonly Used Methods: Below programs illustrate the Line class: Java program to create a line with starting and ending coordinates passed as arguments: This program creates a Line indicated by the name line( start point and the end point is passed as arguments). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached. The group is attached to the scene. Finally, the show() method is called to display the final results. Java program to create a line with starting and ending coordinates passed as arguments: This program creates a Line indicated by the name line( start point and the end point is passed as arguments). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached. The group is attached to the scene. Finally, the show() method is called to display the final results. Java // Java program to create a line with starting// and ending coordinates passed as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Line;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group; public class line_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating line"); // create a line Line line = new Line(10.0f, 10.0f, 200.0f, 140.0f); // create a Group Group group = new Group(line); // translate the line to a position line.setTranslateX(100); line.setTranslateY(100); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Output: Java program to create a line with starting and ending coordinates set using function setStartX(), setStartY()setEndX(), setEndY() function: This program creates a Line indicated by the name line(start point and end point is set using setEndX(), setEndY(), setStartX(), setStartY() function). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. Java program to create a line with starting and ending coordinates set using function setStartX(), setStartY()setEndX(), setEndY() function: This program creates a Line indicated by the name line(start point and end point is set using setEndX(), setEndY(), setStartX(), setStartY() function). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. Java // Java program to create a line with starting// and ending coordinates set using function// setStartX(), setStartY() setEndX(),// setEndY() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Line;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group; public class line_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating line"); // create a line Line line = new Line(); // set starting position line.setStartX(10.0f); line.setStartY(10.0f); // set ending position line.setEndX(140.0f); line.setEndY(140.0f); // create a Group Group group = new Group(line); // translate the line to a position line.setTranslateX(100); line.setTranslateY(100); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }} Output: Output: Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Line.html sweetyty JavaFX Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array Java program to count the occurrence of each character in a string using Hashmap Iterate through List in Java How to Iterate HashMap in Java? Iterate Over the Characters of a String in Java Traverse Through a HashMap in Java Program to print ASCII Value of a character Remove first and last character of a string in Java How to Convert Char to String in Java?
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Apr, 2021" }, { "code": null, "e": 130, "s": 28, "text": "Line is a part of JavaFX. The Line class represents a line in a 2D space.Constructor for the class: " }, { "code": null, "e": 291, "s": 130, "text": "Line(): Creates a new instance for lineLine(double startX, double startY, double endX, double endY): Creates a new Line with specified starting and ending point" }, { "code": null, "e": 331, "s": 291, "text": "Line(): Creates a new instance for line" }, { "code": null, "e": 453, "s": 331, "text": "Line(double startX, double startY, double endX, double endY): Creates a new Line with specified starting and ending point" }, { "code": null, "e": 477, "s": 453, "text": "Commonly Used Methods: " }, { "code": null, "e": 522, "s": 479, "text": "Below programs illustrate the Line class: " }, { "code": null, "e": 1025, "s": 522, "text": "Java program to create a line with starting and ending coordinates passed as arguments: This program creates a Line indicated by the name line( start point and the end point is passed as arguments). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached. The group is attached to the scene. Finally, the show() method is called to display the final results. " }, { "code": null, "e": 1528, "s": 1025, "text": "Java program to create a line with starting and ending coordinates passed as arguments: This program creates a Line indicated by the name line( start point and the end point is passed as arguments). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached. The group is attached to the scene. Finally, the show() method is called to display the final results. " }, { "code": null, "e": 1533, "s": 1528, "text": "Java" }, { "code": "// Java program to create a line with starting// and ending coordinates passed as argumentsimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Line;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group; public class line_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating line\"); // create a line Line line = new Line(10.0f, 10.0f, 200.0f, 140.0f); // create a Group Group group = new Group(line); // translate the line to a position line.setTranslateX(100); line.setTranslateY(100); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 2631, "s": 1533, "text": null }, { "code": null, "e": 2641, "s": 2631, "text": "Output: " }, { "code": null, "e": 2651, "s": 2641, "text": "Output: " }, { "code": null, "e": 3248, "s": 2651, "text": " Java program to create a line with starting and ending coordinates set using function setStartX(), setStartY()setEndX(), setEndY() function: This program creates a Line indicated by the name line(start point and end point is set using setEndX(), setEndY(), setStartX(), setStartY() function). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. " }, { "code": null, "e": 3846, "s": 3250, "text": "Java program to create a line with starting and ending coordinates set using function setStartX(), setStartY()setEndX(), setEndY() function: This program creates a Line indicated by the name line(start point and end point is set using setEndX(), setEndY(), setStartX(), setStartY() function). The Line will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the line is attached.The group is attached to the scene. Finally, the show() method is called to display the final results. " }, { "code": null, "e": 3851, "s": 3846, "text": "Java" }, { "code": "// Java program to create a line with starting// and ending coordinates set using function// setStartX(), setStartY() setEndX(),// setEndY() functionimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.shape.DrawMode;import javafx.scene.layout.*;import javafx.event.ActionEvent;import javafx.scene.shape.Line;import javafx.scene.control.*;import javafx.stage.Stage;import javafx.scene.Group; public class line_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating line\"); // create a line Line line = new Line(); // set starting position line.setStartX(10.0f); line.setStartY(10.0f); // set ending position line.setEndX(140.0f); line.setEndY(140.0f); // create a Group Group group = new Group(line); // translate the line to a position line.setTranslateX(100); line.setTranslateY(100); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } // Main Method public static void main(String args[]) { // launch the application launch(args); }}", "e": 5161, "s": 3851, "text": null }, { "code": null, "e": 5170, "s": 5161, "text": "Output: " }, { "code": null, "e": 5179, "s": 5170, "text": "Output: " }, { "code": null, "e": 5352, "s": 5179, "text": "Note: The above programs might not run in an online IDE. Please use an offline compiler.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Line.html " }, { "code": null, "e": 5361, "s": 5352, "text": "sweetyty" }, { "code": null, "e": 5368, "s": 5361, "text": "JavaFX" }, { "code": null, "e": 5382, "s": 5368, "text": "Java Programs" }, { "code": null, "e": 5480, "s": 5382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5518, "s": 5480, "text": "Factory method design pattern in Java" }, { "code": null, "e": 5575, "s": 5518, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 5656, "s": 5575, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 5685, "s": 5656, "text": "Iterate through List in Java" }, { "code": null, "e": 5717, "s": 5685, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 5765, "s": 5717, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 5800, "s": 5765, "text": "Traverse Through a HashMap in Java" }, { "code": null, "e": 5844, "s": 5800, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 5896, "s": 5844, "text": "Remove first and last character of a string in Java" } ]
Intersection of two arrays in Python ( Lambda expression and filter function )
20 Oct, 2018 Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. # Function to find intersection of two arrays def interSection(arr1,arr2): # filter(lambda x: x in arr1, arr2) --> # filter element x from list arr2 where x # also lies in arr1 result = list(filter(lambda x: x in arr1, arr2)) print ("Intersection : ",result) # Driver programif __name__ == "__main__": arr1 = [1, 3, 4, 5, 7] arr2 = [2, 3, 5, 6] interSection(arr1,arr2) Output: Intersection : [3, 5] python-lambda python-list Arrays Python python-list Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Oct, 2018" }, { "code": null, "e": 95, "s": 52, "text": "Given two arrays, find their intersection." }, { "code": null, "e": 105, "s": 95, "text": "Examples:" }, { "code": null, "e": 199, "s": 105, "text": "Input: arr1[] = [1, 3, 4, 5, 7]\n arr2[] = [2, 3, 5, 6]\nOutput: Intersection : [3, 5]\n" }, { "code": null, "e": 380, "s": 199, "text": "We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function." }, { "code": "# Function to find intersection of two arrays def interSection(arr1,arr2): # filter(lambda x: x in arr1, arr2) --> # filter element x from list arr2 where x # also lies in arr1 result = list(filter(lambda x: x in arr1, arr2)) print (\"Intersection : \",result) # Driver programif __name__ == \"__main__\": arr1 = [1, 3, 4, 5, 7] arr2 = [2, 3, 5, 6] interSection(arr1,arr2)", "e": 784, "s": 380, "text": null }, { "code": null, "e": 792, "s": 784, "text": "Output:" }, { "code": null, "e": 815, "s": 792, "text": "Intersection : [3, 5]\n" }, { "code": null, "e": 829, "s": 815, "text": "python-lambda" }, { "code": null, "e": 841, "s": 829, "text": "python-list" }, { "code": null, "e": 848, "s": 841, "text": "Arrays" }, { "code": null, "e": 855, "s": 848, "text": "Python" }, { "code": null, "e": 867, "s": 855, "text": "python-list" }, { "code": null, "e": 874, "s": 867, "text": "Arrays" } ]
autoreconf command in Linux with examples
03 Jun, 2021 autoreconf is a Autotool which is used to create automatically buildable source code for Unix-like systems. Autotool is a common name for autoconf, automake, etc. These all together are termed as Autotools. Important Points: Provides Portability of source code packages by automatic buildable capability. Provides common build facilities like make install. Automatic dependency generation for C/C++. Syntax: autoreconf [OPTION]... [DIRECTORY]... Options: -h, –help : Print the help message and exit. -V, –version : Used to show the version number, and then exit. -v, –verbose : Verbosely report processing. -d, –debug : Don’t remove temporary files. -f, –force : This option is used to consider all files obsolete. -i, –install : Copy missing auxiliary files. –no-recursive : Don’t rebuild sub-packages. -s, –symlink : With -i option it is used to install symbolic links instead of copies. -m, –make : When applicable, re-run ./configure && make. Note: Autotools are used to make automatically buildable source code for distribution purpose. Important Configuration Files: configure.ac : Describes configuration for autoreconf. Makefile.am : Describes sources of program files and compiler flags for automake.Step 1: Make a directory and a C program file. Step 1: Make a directory and a C program file. Hello, World Program Hello, World Program #include void main() { printf("Hello, World"); } Step 2: Make a configure.ac file for autoreconf. # initialize the process AC_INIT([hello], [0.01]) # make config headers AC_CONFIG_HEADERS([config.h]) #Auxiliary files go here AC_CONFIG_AUX_DIR([build-aux]) # init automake AM_INIT_AUTOMAKE([1.11]) #configure and create "Makefile" AC_CONFIG_FILES([Makefile]) #find and probe C compiler AC_PROG_CC #End AC_OUTPUT Step 3: Make a Makefile.am for automake. #list of programs to be installed in bin directory bin_PROGRAMS = hello #sources for targets hello_SOURCES = hello.c Step 4: Run the following commands on terminal. It will give an error because it is for distribution purpose and VCS(Version Control System) should have some standard license files. Step 5: Lets make license files. Step 6: Retry Step 6: Now, Let’s run the program. See, now Hello, World is printed on the screen nidhi_biet adnanirshad158 linux-command Linux-system-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Jun, 2021" }, { "code": null, "e": 236, "s": 28, "text": "autoreconf is a Autotool which is used to create automatically buildable source code for Unix-like systems. Autotool is a common name for autoconf, automake, etc. These all together are termed as Autotools. " }, { "code": null, "e": 255, "s": 236, "text": "Important Points: " }, { "code": null, "e": 337, "s": 257, "text": "Provides Portability of source code packages by automatic buildable capability." }, { "code": null, "e": 389, "s": 337, "text": "Provides common build facilities like make install." }, { "code": null, "e": 432, "s": 389, "text": "Automatic dependency generation for C/C++." }, { "code": null, "e": 441, "s": 432, "text": "Syntax: " }, { "code": null, "e": 481, "s": 443, "text": "autoreconf [OPTION]... [DIRECTORY]..." }, { "code": null, "e": 491, "s": 481, "text": "Options: " }, { "code": null, "e": 538, "s": 493, "text": "-h, –help : Print the help message and exit." }, { "code": null, "e": 601, "s": 538, "text": "-V, –version : Used to show the version number, and then exit." }, { "code": null, "e": 645, "s": 601, "text": "-v, –verbose : Verbosely report processing." }, { "code": null, "e": 688, "s": 645, "text": "-d, –debug : Don’t remove temporary files." }, { "code": null, "e": 753, "s": 688, "text": "-f, –force : This option is used to consider all files obsolete." }, { "code": null, "e": 798, "s": 753, "text": "-i, –install : Copy missing auxiliary files." }, { "code": null, "e": 842, "s": 798, "text": "–no-recursive : Don’t rebuild sub-packages." }, { "code": null, "e": 928, "s": 842, "text": "-s, –symlink : With -i option it is used to install symbolic links instead of copies." }, { "code": null, "e": 985, "s": 928, "text": "-m, –make : When applicable, re-run ./configure && make." }, { "code": null, "e": 1081, "s": 985, "text": "Note: Autotools are used to make automatically buildable source code for distribution purpose. " }, { "code": null, "e": 1113, "s": 1081, "text": "Important Configuration Files: " }, { "code": null, "e": 1170, "s": 1115, "text": "configure.ac : Describes configuration for autoreconf." }, { "code": null, "e": 1300, "s": 1170, "text": "Makefile.am : Describes sources of program files and compiler flags for automake.Step 1: Make a directory and a C program file. " }, { "code": null, "e": 1349, "s": 1300, "text": "Step 1: Make a directory and a C program file. " }, { "code": null, "e": 1374, "s": 1351, "text": "Hello, World Program " }, { "code": null, "e": 1396, "s": 1374, "text": "Hello, World Program " }, { "code": null, "e": 1450, "s": 1398, "text": "#include\nvoid main()\n{\n printf(\"Hello, World\");\n}" }, { "code": null, "e": 1505, "s": 1454, "text": "Step 2: Make a configure.ac file for autoreconf. " }, { "code": null, "e": 1820, "s": 1507, "text": "# initialize the process\nAC_INIT([hello], [0.01])\n# make config headers\nAC_CONFIG_HEADERS([config.h])\n#Auxiliary files go here\nAC_CONFIG_AUX_DIR([build-aux])\n# init automake\nAM_INIT_AUTOMAKE([1.11])\n#configure and create \"Makefile\"\nAC_CONFIG_FILES([Makefile])\n#find and probe C compiler\nAC_PROG_CC\n#End\nAC_OUTPUT" }, { "code": null, "e": 1867, "s": 1824, "text": "Step 3: Make a Makefile.am for automake. " }, { "code": null, "e": 1986, "s": 1869, "text": "#list of programs to be installed in bin directory\nbin_PROGRAMS = hello\n#sources for targets\nhello_SOURCES = hello.c" }, { "code": null, "e": 2174, "s": 1990, "text": "Step 4: Run the following commands on terminal. It will give an error because it is for distribution purpose and VCS(Version Control System) should have some standard license files. " }, { "code": null, "e": 2215, "s": 2180, "text": "Step 5: Lets make license files. " }, { "code": null, "e": 2233, "s": 2217, "text": "Step 6: Retry " }, { "code": null, "e": 2324, "s": 2239, "text": "Step 6: Now, Let’s run the program. See, now Hello, World is printed on the screen " }, { "code": null, "e": 2337, "s": 2326, "text": "nidhi_biet" }, { "code": null, "e": 2352, "s": 2337, "text": "adnanirshad158" }, { "code": null, "e": 2366, "s": 2352, "text": "linux-command" }, { "code": null, "e": 2388, "s": 2366, "text": "Linux-system-commands" }, { "code": null, "e": 2395, "s": 2388, "text": "Picked" }, { "code": null, "e": 2406, "s": 2395, "text": "Linux-Unix" } ]
An introduction to plotting with Matplotlib in Python | by Philip Wilkinson | Towards Data Science
This year, as Head of Science for the UCL Data Science Society, the society is presenting a series of 20 workshops covering topics such as introduction to Python, a Data Scientists toolkit and Machine learning methods, throughout the academic year. For each of these the aim is to create a series of small blogposts that will outline the main points with links to the full workshop for anyone who wishes to follow along. All of these can be found in our GitHub repository, and will be updated throughout the year with new workshops and challenges. The seventh workshop in the series is an introduction to the matplotlib python package as part of the toolkit for Data Scientist series. In this workshop we introduce how to build a basic plot, plotting different information on the same graph and plotting information across multiple axes. While some of the highlights will be shared here, the full workshop including a problem sheet to test yourself can be found here. If you have missed any of our previous workshops you can find the last three at the following links: towardsdatascience.com towardsdatascience.com towardsdatascience.com Matplotlib is another one of the core data science libraries that should be within any data scientists toolkit, along with the previously introduced libraries of Numpy and Pandas. The main purpose of this library is to create visualisations to be able to better understand the data that you have, and pandas builds on this library for its own functionality. On the Matplotlib website is it described as: Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python. Where the aim and purpose of the library is to make plotting as easy as possible as it also states: Matplotlib makes easy things easy and hard things possible. While there are many other visualisation libraries out there in Python, including seaborn and plotly, this is often the first visualisation tool you learn and hence is the reason why we cover it in one of our workshops. The first thing we need to do, before we create any plots, is to actually create data that we will use to plot! Since we have already been introduced to the Numpy library and its extensive functionality, we can use the Numpy array and its mathematical functionality to create data that we can plot. We can do this as: # Creating an array with 100 values from 0 to 2pix = np.linspace(0,2*np.pi,100)# An array with the sine of all the values in array xy = np.sin(x) Now we have an data for our x and y, we can start to create our plot! For this, we can start by creating a rather basic plot where we show data quite simply as a line on an axis as follows: # Produces the figureplt.figure()# Plots the sine functionplt.plot(x,y) The simplicity of this is that we have only used two lines of code in order to create our graph (you could even remove the first line and it would still work!). How nice and simple is that! Of course, this is a rather basic plot so we can start to improve it. One of the first things we notice is that we can’t necessarily see how the data line ups on the plot as there is no grid to show where the peaks and troughs of the sine wave are. We can thus add a grid to our plot using plt.grid as follows: # Produces the figureplt.figure()# Adds a gridplt.grid(True)# Plots the sine functionplt.plot(x,y) From this we can now see that the y value peaks at 1 and bottoms out at -1 and we could more accurately read of data in relation to where we are on the x and y value. We can then begin to customise the look of the plot. For example, if we want to change the color from blue to red, we can specify the color as r and if we want to change the line style from a solid line to dots we can specify r. as follows: # Produces the figureplt.figure()# Adds a gridplt.grid(True)# Plots the sine function with red dotsplt.plot(x,y,'r.') Other ways to do this can be done using the color and linestyle paramaters of the plot to change the look as well, including a wide range of colors for the line and different looks line style as well. Of course, we have been able to make our line look a little better and clearer, but anyone else looking at this plot may not understand what we are trying to show with the plot itself. Thus, for this we will want to add a title and labels as well to indicate what we are trying to show. We can do that as follows: # Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title("Plot of a sine function", fontsize = 20, pad = 15)# Adds label for the x-axisplt.xlabel("x", fontsize = 15, labelpad = 20)# Adds label for the y-axisplt.ylabel("sin(x)", fontsize = 15, labelpad = 15)# Plots the sine function with red + signsplt.plot(x,y,'r+') Where we have used the plt.xlabel , plt.ylabel and plt.title functions to add these to the plot. We have also specified fontsize to dictate the size of the font used on the labels and labelpad and pad to move the labels away from the axis so that they become clearer to read. From this, we can start to add to build up more functionality into our plots and create our own style that we can use across all of the plots we create. However, Matplotlib has a wealth of inbuilt style sheets that we can access using plt.style.use(`namedstyle`) . One of my favourite ones from this is the fivethirtyeight style sheet because of its ability to produce nice and clear visuals, along with a clean and easily recognisable colour palette. We can implement this as: # Changing style to fivethityeightplt.style.use('fivethirtyeight')# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title("Plot of a sine function", fontsize = 20, pad = 15)# Adds label for the x-axisplt.xlabel("x", fontsize = 15, labelpad = 20)# Adds label for the y-axisplt.ylabel("sin(x)", fontsize = 15, labelpad = 15)# Plots the sine function with red + signsplt.plot(x,y, "+") Which now looks a lot cleaner! More of these, along with examples of what they look like, can be found at this link here. While we now have a nice looking plot that shows all the information we would want from this, what if we wanted to add more information to the same plot? We can simply do this by reusing the same axis and plotting the new data. In our case, since we have already created a sine wave, we can also create a cosine wave using the same x series to compare how they change over the same values. We can do this as follows: # Generates an array of cos(x) valuesy1 = np.cos(x)# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title("Plot of a sine and cosine function")# Adds label for the x-axisplt.xlabel("x")# Adds label for the y-axisplt.ylabel("y")# Plots the sine function with red + signsplt.plot(x,y,'r+')# Plots the cos function with green crossesplt.plot(x,y1,'gx') Great! We can see we have been able to use the same functions we have done previously to add the grid and the labels, but now we have been able to add the cosine function as well with green crosses. The only issue now is that unless we saw the original plot with the sine function on (or we know what a sine function should look like), we don’t necessarily know how we can tell them apart. This is where a legend comes in handy! In order to add a legend to our plots we need to specify a label for the plots for both the sine and cosine function to be able to differentiate them. This is done by adding an additional argument label= to the plt.plot function. This label needs to be set to the string which we want to label the plot. Then we add an additional line of plt.legend for the legend to appear. The optional argument here loc="best" is often used which simply tries to ensure that the legend is placed in the most suitable location of the plot. We can try this as follows: # Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title("Plot of a sine and cosine function")# Adds label for the x-axisplt.xlabel("x")# Adds label for the y-axisplt.ylabel("y")# Plots the sine function with red + signs and defines a legend labelplt.plot(x,y,'r+',label="sin(x)")# Plots the cos function with green crosses and defines a legend labelplt.plot(x,y1,'gx',label="cos(x)")# Adds a legend in the best positionplt.legend(loc='best') Now we can clearly tell which is the sine function and which is the cosine function. The only issue that remains is that we now have some white space at either end of the plot where our lines run out essentially. We can thus try to limit our axis so that we only show where values are actually plotted using the plt.xlim and plt.ylim functions as follows: # Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title("Plot of a sine and cosine function")# Adds label for the x-axisplt.xlabel("x")# Adds label for the y-axisplt.ylabel("y")# Defines a region along the x-axis to be displayedplt.xlim(0,2*np.pi)# Plots the sine function with red + signs and defines a legend labelplt.plot(x,y,'r+',label="sin(x)")# Plots the cos function with green crosses and defines a legend labelplt.plot(x,y1,'gx',label="cos(x)")# Adds a legend in the best positionplt.legend(loc='best') So far we have been able to create an plot showing a single piece of data, then we have been able to create a plot showing multiple pieces of data. What if we had two seperate pieces of data that we wanted to show on multiple plots but we didn’t want to create two seperate plots? Well, we can do this by create an array of subplots! There are two ways we can do this. The first is create a base figure, as we have done already, and then add subplots to the original figure to which we can then add our data. For this, we can use fig.add_subplot(1,2,1) where the first two numbers indicate the size of the array created (here 1 row and 2 columns), while the third number indicates which subplot this will be. We can assign this back to a variable to create it as an axis. The only difference here between what we previously did and here is now we have an axis where instead of using fig.title or fig.xlabel we now have to use ax.set_title and ax.set_xlabel . For example, we can create two sub axes to add our plots to as we did before: # Defines a variable for your array of subplotsfig = plt.figure(figsize=(10,5))# Adds a subplot to the arrayax1 = fig.add_subplot(1,2,1)# Plots the sine function on the first subplotax1.plot(x,y1,'r')ax1.set_title("Sine function")ax1.set_xlabel("x")ax1.set_ylabel("y")ax1.grid(True)# Plots the cosine function on the second subplotax2 = fig.add_subplot(1,2,2)ax2.plot(x,y2,'g')ax2.set_title("Cosine function")ax2.set_xlabel("x")ax2.set_ylabel("y")ax2.grid(True)#to ensure no overlappingplt.tight_layout() We can see now we have created two seperate axis to which we can then plot our data! The alternative is to use fig, ax = plt.subplots(1,2, figsize = (10,5)) to specify straight away that we are creating subplots where fig is our base axis and ax is an array of axis which we can access just as we would a list or an array. We can thus plot the same information as have done previously as follows: fig, ax = plt.subplots(1,2, figsize = (10,5))# Plots the sine function on the first subplotax[0].plot(x,y1,'r')ax[0].set_title("Sine function")ax[0].set_xlabel("x")ax[0].set_ylabel("y")ax[0].grid(True)# Plots the cosine function on the second subplotax[1].plot(x,y2,'g')ax[1].set_title("Cosine function")ax[1].set_xlabel("x")ax[1].set_ylabel("y")ax[1].grid(True)#to ensure no overlappingplt.tight_layout() Where we now have the exact same plot but using slightly different notation! We can then use these to create multiple arrays of subplots to show multiple types of data within the same overall plot! To this end, the latter method of creating subplots is more often used because you are specifying straight away that you are creating several sub-axis, rather than specifying this later on. It is also often used when you are creating a single axis (specifying 1,1 ) because it ensures that everything is plotted on the same axis when you are plotting more than one piece of information! Of course, Matplotlib can do a lot more than just plot basic information like this, and we cover creating matrix plots, choropleth plots, radar plots and more in the actual workshop itself. Matplotlib is a very extensive library and it allows you to do a lot with it, including box plots, scatter plots, bar charts and histograms among others, but there are also other visualisation libraries out there such as seaborn and plotly. I would recommend you explore and practice plotting, including trying our problem worksheet to challenge you! The full workshop notebook, along with further examples and challenges, can be found HERE. If you want any further information on our society feel free to follow us on our socials: Facebook: https://www.facebook.com/ucldata Instagram: https://www.instagram.com/ucl.datasci/ LinkedIn: https://www.linkedin.com/company/ucldata/ And if you want to keep up date with stories from the UCL Data Science Society and other amazing authors, feel free to sign up to medium using my referral code below.
[ { "code": null, "e": 719, "s": 171, "text": "This year, as Head of Science for the UCL Data Science Society, the society is presenting a series of 20 workshops covering topics such as introduction to Python, a Data Scientists toolkit and Machine learning methods, throughout the academic year. For each of these the aim is to create a series of small blogposts that will outline the main points with links to the full workshop for anyone who wishes to follow along. All of these can be found in our GitHub repository, and will be updated throughout the year with new workshops and challenges." }, { "code": null, "e": 1139, "s": 719, "text": "The seventh workshop in the series is an introduction to the matplotlib python package as part of the toolkit for Data Scientist series. In this workshop we introduce how to build a basic plot, plotting different information on the same graph and plotting information across multiple axes. While some of the highlights will be shared here, the full workshop including a problem sheet to test yourself can be found here." }, { "code": null, "e": 1240, "s": 1139, "text": "If you have missed any of our previous workshops you can find the last three at the following links:" }, { "code": null, "e": 1263, "s": 1240, "text": "towardsdatascience.com" }, { "code": null, "e": 1286, "s": 1263, "text": "towardsdatascience.com" }, { "code": null, "e": 1309, "s": 1286, "text": "towardsdatascience.com" }, { "code": null, "e": 1667, "s": 1309, "text": "Matplotlib is another one of the core data science libraries that should be within any data scientists toolkit, along with the previously introduced libraries of Numpy and Pandas. The main purpose of this library is to create visualisations to be able to better understand the data that you have, and pandas builds on this library for its own functionality." }, { "code": null, "e": 1713, "s": 1667, "text": "On the Matplotlib website is it described as:" }, { "code": null, "e": 1824, "s": 1713, "text": "Matplotlib is a comprehensive library for creating static, animated, and interactive visualizations in Python." }, { "code": null, "e": 1924, "s": 1824, "text": "Where the aim and purpose of the library is to make plotting as easy as possible as it also states:" }, { "code": null, "e": 1984, "s": 1924, "text": "Matplotlib makes easy things easy and hard things possible." }, { "code": null, "e": 2204, "s": 1984, "text": "While there are many other visualisation libraries out there in Python, including seaborn and plotly, this is often the first visualisation tool you learn and hence is the reason why we cover it in one of our workshops." }, { "code": null, "e": 2522, "s": 2204, "text": "The first thing we need to do, before we create any plots, is to actually create data that we will use to plot! Since we have already been introduced to the Numpy library and its extensive functionality, we can use the Numpy array and its mathematical functionality to create data that we can plot. We can do this as:" }, { "code": null, "e": 2668, "s": 2522, "text": "# Creating an array with 100 values from 0 to 2pix = np.linspace(0,2*np.pi,100)# An array with the sine of all the values in array xy = np.sin(x)" }, { "code": null, "e": 2738, "s": 2668, "text": "Now we have an data for our x and y, we can start to create our plot!" }, { "code": null, "e": 2858, "s": 2738, "text": "For this, we can start by creating a rather basic plot where we show data quite simply as a line on an axis as follows:" }, { "code": null, "e": 2930, "s": 2858, "text": "# Produces the figureplt.figure()# Plots the sine functionplt.plot(x,y)" }, { "code": null, "e": 3120, "s": 2930, "text": "The simplicity of this is that we have only used two lines of code in order to create our graph (you could even remove the first line and it would still work!). How nice and simple is that!" }, { "code": null, "e": 3431, "s": 3120, "text": "Of course, this is a rather basic plot so we can start to improve it. One of the first things we notice is that we can’t necessarily see how the data line ups on the plot as there is no grid to show where the peaks and troughs of the sine wave are. We can thus add a grid to our plot using plt.grid as follows:" }, { "code": null, "e": 3530, "s": 3431, "text": "# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Plots the sine functionplt.plot(x,y)" }, { "code": null, "e": 3697, "s": 3530, "text": "From this we can now see that the y value peaks at 1 and bottoms out at -1 and we could more accurately read of data in relation to where we are on the x and y value." }, { "code": null, "e": 3938, "s": 3697, "text": "We can then begin to customise the look of the plot. For example, if we want to change the color from blue to red, we can specify the color as r and if we want to change the line style from a solid line to dots we can specify r. as follows:" }, { "code": null, "e": 4056, "s": 3938, "text": "# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Plots the sine function with red dotsplt.plot(x,y,'r.')" }, { "code": null, "e": 4257, "s": 4056, "text": "Other ways to do this can be done using the color and linestyle paramaters of the plot to change the look as well, including a wide range of colors for the line and different looks line style as well." }, { "code": null, "e": 4571, "s": 4257, "text": "Of course, we have been able to make our line look a little better and clearer, but anyone else looking at this plot may not understand what we are trying to show with the plot itself. Thus, for this we will want to add a title and labels as well to indicate what we are trying to show. We can do that as follows:" }, { "code": null, "e": 4968, "s": 4571, "text": "# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title(\"Plot of a sine function\", fontsize = 20, pad = 15)# Adds label for the x-axisplt.xlabel(\"x\", fontsize = 15, labelpad = 20)# Adds label for the y-axisplt.ylabel(\"sin(x)\", fontsize = 15, labelpad = 15)# Plots the sine function with red + signsplt.plot(x,y,'r+')" }, { "code": null, "e": 5244, "s": 4968, "text": "Where we have used the plt.xlabel , plt.ylabel and plt.title functions to add these to the plot. We have also specified fontsize to dictate the size of the font used on the labels and labelpad and pad to move the labels away from the axis so that they become clearer to read." }, { "code": null, "e": 5722, "s": 5244, "text": "From this, we can start to add to build up more functionality into our plots and create our own style that we can use across all of the plots we create. However, Matplotlib has a wealth of inbuilt style sheets that we can access using plt.style.use(`namedstyle`) . One of my favourite ones from this is the fivethirtyeight style sheet because of its ability to produce nice and clear visuals, along with a clean and easily recognisable colour palette. We can implement this as:" }, { "code": null, "e": 6185, "s": 5722, "text": "# Changing style to fivethityeightplt.style.use('fivethirtyeight')# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title(\"Plot of a sine function\", fontsize = 20, pad = 15)# Adds label for the x-axisplt.xlabel(\"x\", fontsize = 15, labelpad = 20)# Adds label for the y-axisplt.ylabel(\"sin(x)\", fontsize = 15, labelpad = 15)# Plots the sine function with red + signsplt.plot(x,y, \"+\")" }, { "code": null, "e": 6307, "s": 6185, "text": "Which now looks a lot cleaner! More of these, along with examples of what they look like, can be found at this link here." }, { "code": null, "e": 6535, "s": 6307, "text": "While we now have a nice looking plot that shows all the information we would want from this, what if we wanted to add more information to the same plot? We can simply do this by reusing the same axis and plotting the new data." }, { "code": null, "e": 6724, "s": 6535, "text": "In our case, since we have already created a sine wave, we can also create a cosine wave using the same x series to compare how they change over the same values. We can do this as follows:" }, { "code": null, "e": 7103, "s": 6724, "text": "# Generates an array of cos(x) valuesy1 = np.cos(x)# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title(\"Plot of a sine and cosine function\")# Adds label for the x-axisplt.xlabel(\"x\")# Adds label for the y-axisplt.ylabel(\"y\")# Plots the sine function with red + signsplt.plot(x,y,'r+')# Plots the cos function with green crossesplt.plot(x,y1,'gx')" }, { "code": null, "e": 7532, "s": 7103, "text": "Great! We can see we have been able to use the same functions we have done previously to add the grid and the labels, but now we have been able to add the cosine function as well with green crosses. The only issue now is that unless we saw the original plot with the sine function on (or we know what a sine function should look like), we don’t necessarily know how we can tell them apart. This is where a legend comes in handy!" }, { "code": null, "e": 8085, "s": 7532, "text": "In order to add a legend to our plots we need to specify a label for the plots for both the sine and cosine function to be able to differentiate them. This is done by adding an additional argument label= to the plt.plot function. This label needs to be set to the string which we want to label the plot. Then we add an additional line of plt.legend for the legend to appear. The optional argument here loc=\"best\" is often used which simply tries to ensure that the legend is placed in the most suitable location of the plot. We can try this as follows:" }, { "code": null, "e": 8555, "s": 8085, "text": "# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title(\"Plot of a sine and cosine function\")# Adds label for the x-axisplt.xlabel(\"x\")# Adds label for the y-axisplt.ylabel(\"y\")# Plots the sine function with red + signs and defines a legend labelplt.plot(x,y,'r+',label=\"sin(x)\")# Plots the cos function with green crosses and defines a legend labelplt.plot(x,y1,'gx',label=\"cos(x)\")# Adds a legend in the best positionplt.legend(loc='best')" }, { "code": null, "e": 8911, "s": 8555, "text": "Now we can clearly tell which is the sine function and which is the cosine function. The only issue that remains is that we now have some white space at either end of the plot where our lines run out essentially. We can thus try to limit our axis so that we only show where values are actually plotted using the plt.xlim and plt.ylim functions as follows:" }, { "code": null, "e": 9451, "s": 8911, "text": "# Produces the figureplt.figure()# Adds a gridplt.grid(True)# Adds a titleplt.title(\"Plot of a sine and cosine function\")# Adds label for the x-axisplt.xlabel(\"x\")# Adds label for the y-axisplt.ylabel(\"y\")# Defines a region along the x-axis to be displayedplt.xlim(0,2*np.pi)# Plots the sine function with red + signs and defines a legend labelplt.plot(x,y,'r+',label=\"sin(x)\")# Plots the cos function with green crosses and defines a legend labelplt.plot(x,y1,'gx',label=\"cos(x)\")# Adds a legend in the best positionplt.legend(loc='best')" }, { "code": null, "e": 9785, "s": 9451, "text": "So far we have been able to create an plot showing a single piece of data, then we have been able to create a plot showing multiple pieces of data. What if we had two seperate pieces of data that we wanted to show on multiple plots but we didn’t want to create two seperate plots? Well, we can do this by create an array of subplots!" }, { "code": null, "e": 10488, "s": 9785, "text": "There are two ways we can do this. The first is create a base figure, as we have done already, and then add subplots to the original figure to which we can then add our data. For this, we can use fig.add_subplot(1,2,1) where the first two numbers indicate the size of the array created (here 1 row and 2 columns), while the third number indicates which subplot this will be. We can assign this back to a variable to create it as an axis. The only difference here between what we previously did and here is now we have an axis where instead of using fig.title or fig.xlabel we now have to use ax.set_title and ax.set_xlabel . For example, we can create two sub axes to add our plots to as we did before:" }, { "code": null, "e": 10993, "s": 10488, "text": "# Defines a variable for your array of subplotsfig = plt.figure(figsize=(10,5))# Adds a subplot to the arrayax1 = fig.add_subplot(1,2,1)# Plots the sine function on the first subplotax1.plot(x,y1,'r')ax1.set_title(\"Sine function\")ax1.set_xlabel(\"x\")ax1.set_ylabel(\"y\")ax1.grid(True)# Plots the cosine function on the second subplotax2 = fig.add_subplot(1,2,2)ax2.plot(x,y2,'g')ax2.set_title(\"Cosine function\")ax2.set_xlabel(\"x\")ax2.set_ylabel(\"y\")ax2.grid(True)#to ensure no overlappingplt.tight_layout()" }, { "code": null, "e": 11078, "s": 10993, "text": "We can see now we have created two seperate axis to which we can then plot our data!" }, { "code": null, "e": 11390, "s": 11078, "text": "The alternative is to use fig, ax = plt.subplots(1,2, figsize = (10,5)) to specify straight away that we are creating subplots where fig is our base axis and ax is an array of axis which we can access just as we would a list or an array. We can thus plot the same information as have done previously as follows:" }, { "code": null, "e": 11796, "s": 11390, "text": "fig, ax = plt.subplots(1,2, figsize = (10,5))# Plots the sine function on the first subplotax[0].plot(x,y1,'r')ax[0].set_title(\"Sine function\")ax[0].set_xlabel(\"x\")ax[0].set_ylabel(\"y\")ax[0].grid(True)# Plots the cosine function on the second subplotax[1].plot(x,y2,'g')ax[1].set_title(\"Cosine function\")ax[1].set_xlabel(\"x\")ax[1].set_ylabel(\"y\")ax[1].grid(True)#to ensure no overlappingplt.tight_layout()" }, { "code": null, "e": 11994, "s": 11796, "text": "Where we now have the exact same plot but using slightly different notation! We can then use these to create multiple arrays of subplots to show multiple types of data within the same overall plot!" }, { "code": null, "e": 12381, "s": 11994, "text": "To this end, the latter method of creating subplots is more often used because you are specifying straight away that you are creating several sub-axis, rather than specifying this later on. It is also often used when you are creating a single axis (specifying 1,1 ) because it ensures that everything is plotted on the same axis when you are plotting more than one piece of information!" }, { "code": null, "e": 12922, "s": 12381, "text": "Of course, Matplotlib can do a lot more than just plot basic information like this, and we cover creating matrix plots, choropleth plots, radar plots and more in the actual workshop itself. Matplotlib is a very extensive library and it allows you to do a lot with it, including box plots, scatter plots, bar charts and histograms among others, but there are also other visualisation libraries out there such as seaborn and plotly. I would recommend you explore and practice plotting, including trying our problem worksheet to challenge you!" }, { "code": null, "e": 13103, "s": 12922, "text": "The full workshop notebook, along with further examples and challenges, can be found HERE. If you want any further information on our society feel free to follow us on our socials:" }, { "code": null, "e": 13146, "s": 13103, "text": "Facebook: https://www.facebook.com/ucldata" }, { "code": null, "e": 13196, "s": 13146, "text": "Instagram: https://www.instagram.com/ucl.datasci/" }, { "code": null, "e": 13248, "s": 13196, "text": "LinkedIn: https://www.linkedin.com/company/ucldata/" } ]
LCM of two large numbers - GeeksforGeeks
19 Aug, 2020 Given two large numbers ‘a’ and ‘b’ such that(10^20<=a, b<=10^300). Find the LCM of two large numbers given.Examples: Input: a = 234516789234023485693020129 b = 176892058718950472893785940 Output: 41484157651764614525905399263631111992263435437186260 Input: a = 36594652830916364940473625749407 b = 448507083624364748494746353648484939 Output: 443593541011902763984944550799004089258248037004507648321189937329 Solution: In the given problem, we can see that the number are very large which is outside the limit of all available primitive data types, so we have to use the concept of BigInteger Class in Java. So we convert the given strings into biginteger and then we use java.math.BigInteger.gcd(BigInteger val) method to compute gcd of large numbers and then we calculate lcm using following formula:LCM * HCF = x * y, where x and y are two numbers Below is implementation of the above idea. Java Python3 // Java Program to find LCM of two large numbersimport java.math.*;import java.lang.*;import java.util.*; public class GFG { // function to calculate LCM of two large numbers public static BigInteger lcm(String a, String b) { // convert string 'a' and 'b' into BigInteger BigInteger s = new BigInteger(a); BigInteger s1 = new BigInteger(b); // calculate multiplication of two bigintegers BigInteger mul = s.multiply(s1); // calculate gcd of two bigintegers BigInteger gcd = s.gcd(s1); // calculate lcm using formula: lcm * gcd = x * y BigInteger lcm = mul.divide(gcd); return lcm; } // Driver Code public static void main(String[] args) { // Input 'a' and 'b' are in the form of strings because // they can not be handled by integer data type String a = "36594652830916364940473625749407"; String b = "448507083624364748494746353648484939"; System.out.print(lcm(a, b)); }}// Code contributed by Saurav Jain # Python3 program to find LCM of two # large numbersimport math # Function to calculate LCM of two# large numbersdef lcm (a, b): # Convert string 'a' and 'b' # into Integer s = int(a) s1 = int(b) # Calculate multiplication of # both integers mul = s * s1 # Calculate gcd of two integers gcd = math.gcd(s, s1) # Calculate lcm using # formula: lcm * gcd = x * y lcm = mul // gcd return lcm # Driver Codeif __name__ == '__main__': # Input 'a' and 'b' are in the # form of strings a = "36594652830916364940473625749407" b = "448507083624364748494746353648484939" print(lcm(a, b)) # This code is contributed by himanshu77 Output: 443593541011902763984944550799004089258248037004507648321189937329 himanshu77 GCD-LCM large-numbers Modular Arithmetic Mathematical Mathematical Modular Arithmetic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Find all factors of a natural number | Set 1 Check if a number is Palindrome Program to print prime numbers from 1 to N. Program to add two binary strings Program to multiply two matrices Fizz Buzz Implementation Find pair with maximum GCD in an array Find Union and Intersection of two unsorted arrays Count all possible paths from top left to bottom right of a mXn matrix Count ways to reach the n'th stair
[ { "code": null, "e": 24327, "s": 24299, "text": "\n19 Aug, 2020" }, { "code": null, "e": 24445, "s": 24327, "text": "Given two large numbers ‘a’ and ‘b’ such that(10^20<=a, b<=10^300). Find the LCM of two large numbers given.Examples:" }, { "code": null, "e": 24760, "s": 24445, "text": " Input: a = 234516789234023485693020129\n b = 176892058718950472893785940\n Output: 41484157651764614525905399263631111992263435437186260\n\n Input: a = 36594652830916364940473625749407\n b = 448507083624364748494746353648484939\n Output: 443593541011902763984944550799004089258248037004507648321189937329\n" }, { "code": null, "e": 25202, "s": 24760, "text": "Solution: In the given problem, we can see that the number are very large which is outside the limit of all available primitive data types, so we have to use the concept of BigInteger Class in Java. So we convert the given strings into biginteger and then we use java.math.BigInteger.gcd(BigInteger val) method to compute gcd of large numbers and then we calculate lcm using following formula:LCM * HCF = x * y, where x and y are two numbers" }, { "code": null, "e": 25245, "s": 25202, "text": "Below is implementation of the above idea." }, { "code": null, "e": 25250, "s": 25245, "text": "Java" }, { "code": null, "e": 25258, "s": 25250, "text": "Python3" }, { "code": "// Java Program to find LCM of two large numbersimport java.math.*;import java.lang.*;import java.util.*; public class GFG { // function to calculate LCM of two large numbers public static BigInteger lcm(String a, String b) { // convert string 'a' and 'b' into BigInteger BigInteger s = new BigInteger(a); BigInteger s1 = new BigInteger(b); // calculate multiplication of two bigintegers BigInteger mul = s.multiply(s1); // calculate gcd of two bigintegers BigInteger gcd = s.gcd(s1); // calculate lcm using formula: lcm * gcd = x * y BigInteger lcm = mul.divide(gcd); return lcm; } // Driver Code public static void main(String[] args) { // Input 'a' and 'b' are in the form of strings because // they can not be handled by integer data type String a = \"36594652830916364940473625749407\"; String b = \"448507083624364748494746353648484939\"; System.out.print(lcm(a, b)); }}// Code contributed by Saurav Jain", "e": 26309, "s": 25258, "text": null }, { "code": "# Python3 program to find LCM of two # large numbersimport math # Function to calculate LCM of two# large numbersdef lcm (a, b): # Convert string 'a' and 'b' # into Integer s = int(a) s1 = int(b) # Calculate multiplication of # both integers mul = s * s1 # Calculate gcd of two integers gcd = math.gcd(s, s1) # Calculate lcm using # formula: lcm * gcd = x * y lcm = mul // gcd return lcm # Driver Codeif __name__ == '__main__': # Input 'a' and 'b' are in the # form of strings a = \"36594652830916364940473625749407\" b = \"448507083624364748494746353648484939\" print(lcm(a, b)) # This code is contributed by himanshu77", "e": 27000, "s": 26309, "text": null }, { "code": null, "e": 27008, "s": 27000, "text": "Output:" }, { "code": null, "e": 27076, "s": 27008, "text": "443593541011902763984944550799004089258248037004507648321189937329\n" }, { "code": null, "e": 27087, "s": 27076, "text": "himanshu77" }, { "code": null, "e": 27095, "s": 27087, "text": "GCD-LCM" }, { "code": null, "e": 27109, "s": 27095, "text": "large-numbers" }, { "code": null, "e": 27128, "s": 27109, "text": "Modular Arithmetic" }, { "code": null, "e": 27141, "s": 27128, "text": "Mathematical" }, { "code": null, "e": 27154, "s": 27141, "text": "Mathematical" }, { "code": null, "e": 27173, "s": 27154, "text": "Modular Arithmetic" }, { "code": null, "e": 27271, "s": 27173, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27280, "s": 27271, "text": "Comments" }, { "code": null, "e": 27293, "s": 27280, "text": "Old Comments" }, { "code": null, "e": 27338, "s": 27293, "text": "Find all factors of a natural number | Set 1" }, { "code": null, "e": 27370, "s": 27338, "text": "Check if a number is Palindrome" }, { "code": null, "e": 27414, "s": 27370, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 27448, "s": 27414, "text": "Program to add two binary strings" }, { "code": null, "e": 27481, "s": 27448, "text": "Program to multiply two matrices" }, { "code": null, "e": 27506, "s": 27481, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 27545, "s": 27506, "text": "Find pair with maximum GCD in an array" }, { "code": null, "e": 27596, "s": 27545, "text": "Find Union and Intersection of two unsorted arrays" }, { "code": null, "e": 27667, "s": 27596, "text": "Count all possible paths from top left to bottom right of a mXn matrix" } ]
String comparison using == vs strcmp() in PHP - GeeksforGeeks
30 Nov, 2021 In this article, we will see the string comparison using the equal (==) operator & strcmp() Function in PHP, along with understanding their implementation through the example. PHP == Operator: The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns a true value if both of the values are the same (It compares the only value of the variable, not data types) and returns a false value if both of the values are not the same. This should always be kept in mind that the present equality operator == is different from the assignment operator =. The assignment operator assigns the variable on the left to have a new value as the variable on right, while the equal operator == tests for equality and returns true or false as per the comparison results. Example: This example describes the string comparison using the == operator. PHP <?php // Declaration of strings $name1 = "Geeks"; $name2 = "Geeks"; // Use == operator if ($name1 == $name2) { echo 'Both strings are equal'; } else { echo 'Both strings are not equal'; }?> Output: Both the strings are equal PHP strcmp() Function: The strcmp() is an inbuilt function in PHP that is used to compare two strings. This function is case-sensitive which points that capital and small cases will be treated differently, during comparison. This function compares two strings and tells whether the first string is greater or smaller or equals the second string. This function is binary-safe string comparison. Syntax: strcmp( $string1, $string2 ) Parameters: This function accepts two parameters as mentioned above and described below: $string1: This parameter refers to the first string to be used in the comparison. It is a mandatory parameter. $string2: This parameter refers to the second string to be used in the comparison. It is a mandatory parameter. Return Values: The function returns a random integer value depending on the condition of the match, which is given by: Returns 0 if the strings are equal. Returns a negative value (< 0), if $string2 is greater than $string1. Returns a positive value (> 0) if $string1 is greater than $string2. Example: This example illustrates the string comparison using the strcmp() function. PHP <?php // Declaration of strings $name1 = "Geeks"; $name2 = "geeks"; // Use strcmp() function if (strcmp($name1, $name2) !== 0) { echo 'Both strings are not equal'; } else { echo 'Both strings are equal'; }?> Output: Both strings are not equal Reference: http://php.net/manual/en/language.operators.comparison.php http://php.net/manual/en/function.strcmp.php PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. bhaskargeeksforgeeks PHP-Operators Picked Technical Scripter 2018 PHP PHP Programs Technical Scripter PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to receive JSON POST with PHP ? Comparing two dates in PHP PHP | Converting string to Date and DateTime 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 ? Comparing two dates in PHP How to fetch data from localserver database and display on HTML table using PHP ?
[ { "code": null, "e": 25005, "s": 24977, "text": "\n30 Nov, 2021" }, { "code": null, "e": 25181, "s": 25005, "text": "In this article, we will see the string comparison using the equal (==) operator & strcmp() Function in PHP, along with understanding their implementation through the example." }, { "code": null, "e": 25507, "s": 25181, "text": "PHP == Operator: The comparison operator called Equal Operator is the double equal sign “==”. This operator accepts two inputs to compare and returns a true value if both of the values are the same (It compares the only value of the variable, not data types) and returns a false value if both of the values are not the same. " }, { "code": null, "e": 25832, "s": 25507, "text": "This should always be kept in mind that the present equality operator == is different from the assignment operator =. The assignment operator assigns the variable on the left to have a new value as the variable on right, while the equal operator == tests for equality and returns true or false as per the comparison results." }, { "code": null, "e": 25910, "s": 25832, "text": "Example: This example describes the string comparison using the == operator. " }, { "code": null, "e": 25914, "s": 25910, "text": "PHP" }, { "code": "<?php // Declaration of strings $name1 = \"Geeks\"; $name2 = \"Geeks\"; // Use == operator if ($name1 == $name2) { echo 'Both strings are equal'; } else { echo 'Both strings are not equal'; }?>", "e": 26124, "s": 25914, "text": null }, { "code": null, "e": 26132, "s": 26124, "text": "Output:" }, { "code": null, "e": 26159, "s": 26132, "text": "Both the strings are equal" }, { "code": null, "e": 26553, "s": 26159, "text": "PHP strcmp() Function: The strcmp() is an inbuilt function in PHP that is used to compare two strings. This function is case-sensitive which points that capital and small cases will be treated differently, during comparison. This function compares two strings and tells whether the first string is greater or smaller or equals the second string. This function is binary-safe string comparison." }, { "code": null, "e": 26561, "s": 26553, "text": "Syntax:" }, { "code": null, "e": 26590, "s": 26561, "text": "strcmp( $string1, $string2 )" }, { "code": null, "e": 26679, "s": 26590, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 26790, "s": 26679, "text": "$string1: This parameter refers to the first string to be used in the comparison. It is a mandatory parameter." }, { "code": null, "e": 26902, "s": 26790, "text": "$string2: This parameter refers to the second string to be used in the comparison. It is a mandatory parameter." }, { "code": null, "e": 27022, "s": 26902, "text": "Return Values: The function returns a random integer value depending on the condition of the match, which is given by: " }, { "code": null, "e": 27058, "s": 27022, "text": "Returns 0 if the strings are equal." }, { "code": null, "e": 27128, "s": 27058, "text": "Returns a negative value (< 0), if $string2 is greater than $string1." }, { "code": null, "e": 27197, "s": 27128, "text": "Returns a positive value (> 0) if $string1 is greater than $string2." }, { "code": null, "e": 27282, "s": 27197, "text": "Example: This example illustrates the string comparison using the strcmp() function." }, { "code": null, "e": 27286, "s": 27282, "text": "PHP" }, { "code": "<?php // Declaration of strings $name1 = \"Geeks\"; $name2 = \"geeks\"; // Use strcmp() function if (strcmp($name1, $name2) !== 0) { echo 'Both strings are not equal'; } else { echo 'Both strings are equal'; }?>", "e": 27514, "s": 27286, "text": null }, { "code": null, "e": 27522, "s": 27514, "text": "Output:" }, { "code": null, "e": 27549, "s": 27522, "text": "Both strings are not equal" }, { "code": null, "e": 27560, "s": 27549, "text": "Reference:" }, { "code": null, "e": 27619, "s": 27560, "text": "http://php.net/manual/en/language.operators.comparison.php" }, { "code": null, "e": 27664, "s": 27619, "text": "http://php.net/manual/en/function.strcmp.php" }, { "code": null, "e": 27833, "s": 27664, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 27854, "s": 27833, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 27868, "s": 27854, "text": "PHP-Operators" }, { "code": null, "e": 27875, "s": 27868, "text": "Picked" }, { "code": null, "e": 27899, "s": 27875, "text": "Technical Scripter 2018" }, { "code": null, "e": 27903, "s": 27899, "text": "PHP" }, { "code": null, "e": 27916, "s": 27903, "text": "PHP Programs" }, { "code": null, "e": 27935, "s": 27916, "text": "Technical Scripter" }, { "code": null, "e": 27939, "s": 27935, "text": "PHP" }, { "code": null, "e": 28037, "s": 27939, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28046, "s": 28037, "text": "Comments" }, { "code": null, "e": 28059, "s": 28046, "text": "Old Comments" }, { "code": null, "e": 28109, "s": 28059, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28149, "s": 28109, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28185, "s": 28149, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 28212, "s": 28185, "text": "Comparing two dates in PHP" }, { "code": null, "e": 28257, "s": 28212, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 28307, "s": 28257, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28347, "s": 28307, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 28399, "s": 28347, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 28426, "s": 28399, "text": "Comparing two dates in PHP" } ]
Reports Fields
Report fields are elements, which represent mapping of data between datasource and report template. Fields can be combined in the report expressions to obtain the desired output. A report template can contain zero or more <field> elements. When declaring report fields, the data source should supply data corresponding to all the fields defined in the report template. Field declaration is done as shown below − <field name = "FieldName" class = "java.lang.String"/> The name attribute of the <field> element is mandatory. It references the field in report expressions by name. The class attribute specifies the class name for the field values. Its default value is java.lang.String. This can be changed to any class available at runtime. Irrespective of the type of a report field, the engine takes care of casting in the report expressions in which the $F{} token is used, hence making manual casts unnecessary. The <fieldDesciption> element is an optional element. This is very useful when implementing a custom data source. For example, we can store a key or some information, by which we can retrieve the value of field from the custom data source at runtime. By using the <fieldDesciption> element instead of the field name, you can easily overcome restrictions of field-naming conventions when retrieving the field values from the data source. Following is a piece of code from our existing JRXML file (Chapter Report Designs). Here, we can see usage of name, class, and fieldDescription elements. <field name = "country" class = "java.lang.String"> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = "name" class = "java.lang.String"> <fieldDescription><![CDATA[name]]></fieldDescription> </field> At the times when data sorting is required and the data source implementation doesn't support it (for e.g. CSV datasource), JasperReports supports in-memory field-based data source sorting. The sorting can be done using one or more <sortField> elements in the report template. If at least one sort field is specified, during report filling process, the data source is passed to a JRSortableDataSource instance. This in turn, fetches all the records from data source, performs in memory sort according to the specified fields, and replaces the original data source. The sort field name should be identical to the report field name. Fields used for sorting should have types that implement java.util.Comparable. Natural order sorting is performed for all fields except those of type java.lang.String (for String type, collator corresponding to the report fill locale is used). When several sort Fields are specified, the sorting will be performed using the fields as sort keys in the order in which they appear in the report template. Following example demonstrates the sorting feature. Let's add the <sortField> element to our existing report template (Chapter Report designs). Let's sort field country in descending order. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\tools\jasperreports-5.0.1\test directory − <?xml version = "1.0"?> <!DOCTYPE jasperReport PUBLIC "//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name = "jasper_report_template" pageWidth = "595" pageHeight = "842" columnWidth = "515" leftMargin = "40" rightMargin = "40" topMargin = "50" bottomMargin = "50"> <parameter name = "ReportTitle" class = "java.lang.String"/> <parameter name = "Author" class = "java.lang.String"/> <queryString> <![CDATA[]]> </queryString> <field name = "country" class = "java.lang.String"> <fieldDescription><![CDATA[country]]></fieldDescription> </field> <field name = "name" class = "java.lang.String"> <fieldDescription><![CDATA[name]]></fieldDescription> </field> <sortField name = "country" order = "Descending"/> <sortField name = "name"/> <title> <band height = "70"> <line> <reportElement x = "0" y = "0" width = "515" height = "1"/> </line> <textField isBlankWhenNull = "true" bookmarkLevel = "1"> <reportElement x = "0" y = "10" width = "515" height = "30"/> <textElement textAlignment = "Center"> <font size = "22"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{ReportTitle}]]> </textFieldExpression> <anchorNameExpression> <![CDATA["Title"]]> </anchorNameExpression> </textField> <textField isBlankWhenNull = "true"> <reportElement x = "0" y = "40" width = "515" height = "20"/> <textElement textAlignment = "Center"> <font size = "10"/> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$P{Author}]]> </textFieldExpression> </textField> </band> </title> <columnHeader> <band height = "23"> <staticText> <reportElement mode = "Opaque" x = "0" y = "3" width = "535" height = "15" backcolor = "#70A9A9" /> <box> <bottomPen lineWidth = "1.0" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <staticText> <reportElement x = "414" y = "3" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Country]]></text> </staticText> <staticText> <reportElement x = "0" y = "3" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font isBold = "true" /> </textElement> <text><![CDATA[Name]]></text> </staticText> </band> </columnHeader> <detail> <band height = "16"> <staticText> <reportElement mode = "Opaque" x = "0" y = "0" width = "535" height = "14" backcolor = "#E5ECF9" /> <box> <bottomPen lineWidth = "0.25" lineColor = "#CCCCCC" /> </box> <textElement /> <text> <![CDATA[]]> </text> </staticText> <textField> <reportElement x = "414" y = "0" width = "121" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font size = "9" /> </textElement> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{country}]]> </textFieldExpression> </textField> <textField> <reportElement x = "0" y = "0" width = "136" height = "15" /> <textElement textAlignment = "Center" verticalAlignment = "Middle" /> <textFieldExpression class = "java.lang.String"> <![CDATA[$F{name}]]> </textFieldExpression> </textField> </band> </detail> </jasperReport> The java codes for report filling remains unchanged. The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\JasperReportFill.java are as given below − package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; public class JasperReportFill { @SuppressWarnings("unchecked") public static void main(String[] args) { String sourceFileName = "C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper"; DataBeanList DataBeanList = new DataBeanList(); ArrayList<DataBean> dataList = DataBeanList.getDataBeanList(); JRBeanCollectionDataSource beanColDataSource = new JRBeanCollectionDataSource(dataList); Map parameters = new HashMap(); /** * Passing ReportTitle and Author as parameters */ parameters.put("ReportTitle", "List of Contacts"); parameters.put("Author", "Prepared By Manisha"); try { JasperFillManager.fillReportToFile( sourceFileName, parameters, beanColDataSource); } catch (JRException e) { e.printStackTrace(); } } } The contents of the POJO file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBean.java are as given below − package com.tutorialspoint; public class DataBean { private String name; private String country; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } The contents of the file C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint\DataBeanList.java are as given below − package com.tutorialspoint; import java.util.ArrayList; public class DataBeanList { public ArrayList<DataBean> getDataBeanList() { ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>(); dataBeanList.add(produce("Manisha", "India")); dataBeanList.add(produce("Dennis Ritchie", "USA")); dataBeanList.add(produce("V.Anand", "India")); dataBeanList.add(produce("Shrinath", "California")); return dataBeanList; } /** * This method returns a DataBean object, * with name and country set in it. */ private DataBean produce(String name, String country) { DataBean dataBean = new DataBean(); dataBean.setName(name); dataBean.setCountry(country); return dataBean; } } We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below. The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml. <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "viewFillReport" basedir = "."> <import file = "baseBuild.xml" /> <target name = "viewFillReport" depends = "compile,compilereportdesing,run" description = "Launches the report viewer to preview the report stored in the .JRprint file."> <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true"> <arg value = "-F${file.name}.JRprint" /> <classpath refid = "classpath" /> </java> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows − C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml clean-sample: [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint compile: [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning: 'includeantruntime' was not set, defaulting to build.sysclasspath=last; set to false for repeatable builds [javac] Compiling 7 source files to C:\tools\jasperreports-5.0.1\test\classes compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK. run: [echo] Runnin class : com.tutorialspoint.JasperReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. viewFillReport: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL Total time: 18 seconds As a result of above compilation, a JasperViewer window opens up as shown in the screen given below − Here, we can see that the country names are arranged in descending order alphabetically. Print Add Notes Bookmark this page
[ { "code": null, "e": 2623, "s": 2254, "text": "Report fields are elements, which represent mapping of data between datasource and report template. Fields can be combined in the report expressions to obtain the desired output. A report template can contain zero or more <field> elements. When declaring report fields, the data source should supply data corresponding to all the fields defined in the report template." }, { "code": null, "e": 2666, "s": 2623, "text": "Field declaration is done as shown below −" }, { "code": null, "e": 2721, "s": 2666, "text": "<field name = \"FieldName\" class = \"java.lang.String\"/>" }, { "code": null, "e": 2832, "s": 2721, "text": "The name attribute of the <field> element is mandatory. It references the field in report expressions by name." }, { "code": null, "e": 3168, "s": 2832, "text": "The class attribute specifies the class name for the field values. Its default value is java.lang.String. This can be changed to any class available at runtime. Irrespective of the type of a report field, the engine takes care of casting in the report expressions in which the $F{} token is used, hence making manual casts unnecessary." }, { "code": null, "e": 3605, "s": 3168, "text": "The <fieldDesciption> element is an optional element. This is very useful when implementing a custom data source. For example, we can store a key or some information, by which we can retrieve the value of field from the custom data source at runtime. By using the <fieldDesciption> element instead of the field name, you can easily overcome restrictions of field-naming conventions when retrieving the field values from the data source." }, { "code": null, "e": 3759, "s": 3605, "text": "Following is a piece of code from our existing JRXML file (Chapter Report Designs). Here, we can see usage of name, class, and fieldDescription elements." }, { "code": null, "e": 3996, "s": 3759, "text": "<field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n</field>\n\n<field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n</field>" }, { "code": null, "e": 4274, "s": 3996, "text": "At the times when data sorting is required and the data source implementation doesn't support it (for e.g. CSV datasource), JasperReports supports in-memory field-based data source sorting. The sorting can be done using one or more <sortField> elements in the report template. " }, { "code": null, "e": 4562, "s": 4274, "text": "If at least one sort field is specified, during report filling process, the data source is passed to a JRSortableDataSource instance. This in turn, fetches all the records from data source, performs in memory sort according to the specified fields, and replaces the original data source." }, { "code": null, "e": 5082, "s": 4562, "text": "The sort field name should be identical to the report field name. Fields used for sorting should have types that implement java.util.Comparable. Natural order sorting is performed for all fields except those of type java.lang.String (for String type, collator corresponding to the report fill locale is used). When several sort Fields are specified, the sorting will be performed using the fields as sort keys in the order in which they appear in the report template. Following example demonstrates the sorting feature." }, { "code": null, "e": 5351, "s": 5082, "text": "Let's add the <sortField> element to our existing report template (Chapter Report designs). Let's sort field country in descending order. The revised report template (jasper_report_template.jrxml) is as follows. Save it to C:\\tools\\jasperreports-5.0.1\\test directory −" }, { "code": null, "e": 10177, "s": 5351, "text": "<?xml version = \"1.0\"?>\n<!DOCTYPE jasperReport PUBLIC\n \"//JasperReports//DTD Report Design//EN\"\n \"http://jasperreports.sourceforge.net/dtds/jasperreport.dtd\">\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\" xmlns:xsi = \n \"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation = \n \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\" \n name = \"jasper_report_template\" pageWidth = \"595\" pageHeight = \"842\" \n columnWidth = \"515\" leftMargin = \"40\" rightMargin = \"40\" \n topMargin = \"50\" bottomMargin = \"50\">\n\t\n <parameter name = \"ReportTitle\" class = \"java.lang.String\"/>\n <parameter name = \"Author\" class = \"java.lang.String\"/>\n \n <queryString>\n <![CDATA[]]>\n </queryString>\n \n <field name = \"country\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[country]]></fieldDescription>\n </field>\n \n <field name = \"name\" class = \"java.lang.String\">\n <fieldDescription><![CDATA[name]]></fieldDescription>\n </field>\n \n <sortField name = \"country\" order = \"Descending\"/>\n <sortField name = \"name\"/>\n \n <title>\n <band height = \"70\">\n \n <line>\n <reportElement x = \"0\" y = \"0\" width = \"515\" height = \"1\"/>\n </line>\n \n <textField isBlankWhenNull = \"true\" bookmarkLevel = \"1\">\n <reportElement x = \"0\" y = \"10\" width = \"515\" height = \"30\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"22\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{ReportTitle}]]>\n </textFieldExpression>\n \n <anchorNameExpression>\n <![CDATA[\"Title\"]]>\n </anchorNameExpression>\n </textField>\n \n <textField isBlankWhenNull = \"true\">\n <reportElement x = \"0\" y = \"40\" width = \"515\" height = \"20\"/>\n \n <textElement textAlignment = \"Center\">\n <font size = \"10\"/>\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$P{Author}]]>\n </textFieldExpression>\n \n </textField>\n \n </band>\n </title>\n\n <columnHeader>\n <band height = \"23\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"3\" width = \"535\" height = \"15\"\n backcolor = \"#70A9A9\" />\n \n <box>\n <bottomPen lineWidth = \"1.0\" lineColor = \"#CCCCCC\" />\n </box>\n \n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"414\" y = \"3\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Country]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"3\" width = \"136\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font isBold = \"true\" />\n </textElement>\n \n <text><![CDATA[Name]]></text>\n </staticText>\n \n </band>\n </columnHeader>\n \n <detail>\n <band height = \"16\">\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"0\" width = \"535\" height = \"14\"\n backcolor = \"#E5ECF9\" />\n \n <box>\n <bottomPen lineWidth = \"0.25\" lineColor = \"#CCCCCC\" />\n </box>\n\t\t\t\t\n <textElement />\n\t\t\t\t\n <text>\n <![CDATA[]]>\n </text>\n </staticText>\n \n <textField>\n <reportElement x = \"414\" y = \"0\" width = \"121\" height = \"15\" />\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font size = \"9\" />\n </textElement>\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{country}]]>\n </textFieldExpression>\n </textField>\n \n <textField>\n <reportElement x = \"0\" y = \"0\" width = \"136\" height = \"15\" />\n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\" />\n \n <textFieldExpression class = \"java.lang.String\">\n <![CDATA[$F{name}]]>\n </textFieldExpression>\n </textField>\n \n </band>\n </detail>\n\n</jasperReport>" }, { "code": null, "e": 10355, "s": 10177, "text": "The java codes for report filling remains unchanged. The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\JasperReportFill.java are as given below −" }, { "code": null, "e": 11489, "s": 10355, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\nimport net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;\n\npublic class JasperReportFill {\n @SuppressWarnings(\"unchecked\")\n public static void main(String[] args) {\n String sourceFileName =\n \"C://tools/jasperreports-5.0.1/test/jasper_report_template.jasper\";\n\n DataBeanList DataBeanList = new DataBeanList();\n ArrayList<DataBean> dataList = DataBeanList.getDataBeanList();\n\n JRBeanCollectionDataSource beanColDataSource =\n new JRBeanCollectionDataSource(dataList);\n\n Map parameters = new HashMap();\n /**\n * Passing ReportTitle and Author as parameters\n */\n parameters.put(\"ReportTitle\", \"List of Contacts\");\n parameters.put(\"Author\", \"Prepared By Manisha\");\n\n try {\n JasperFillManager.fillReportToFile(\n sourceFileName, parameters, beanColDataSource);\n } catch (JRException e) {\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 11611, "s": 11489, "text": "The contents of the POJO file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBean.java are as given below −" }, { "code": null, "e": 11979, "s": 11611, "text": "package com.tutorialspoint;\n\npublic class DataBean {\n private String name;\n private String country;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n}" }, { "code": null, "e": 12100, "s": 11979, "text": "The contents of the file C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint\\DataBeanList.java are as given below −" }, { "code": null, "e": 12864, "s": 12100, "text": "package com.tutorialspoint;\n\nimport java.util.ArrayList;\n\npublic class DataBeanList {\n public ArrayList<DataBean> getDataBeanList() {\n ArrayList<DataBean> dataBeanList = new ArrayList<DataBean>();\n\n dataBeanList.add(produce(\"Manisha\", \"India\"));\n dataBeanList.add(produce(\"Dennis Ritchie\", \"USA\"));\n dataBeanList.add(produce(\"V.Anand\", \"India\"));\n dataBeanList.add(produce(\"Shrinath\", \"California\"));\n\n return dataBeanList;\n }\n\n /**\n * This method returns a DataBean object,\n * with name and country set in it.\n */\n private DataBean produce(String name, String country) {\n DataBean dataBean = new DataBean();\n dataBean.setName(name);\n dataBean.setCountry(country);\n \n return dataBean;\n }\n}" }, { "code": null, "e": 13057, "s": 12864, "text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below." }, { "code": null, "e": 13191, "s": 13057, "text": "The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml." }, { "code": null, "e": 14266, "s": 13191, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview\n the report stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n\t\t\n </target>\n\t\n</project>" }, { "code": null, "e": 14488, "s": 14266, "text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperReportFill (viewFullReport is the default target) as follows −" }, { "code": null, "e": 16161, "s": 14488, "text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28: warning:\n 'includeantruntime' was not set, defaulting to build.sysclasspath=last;\n set to false for repeatable builds\n [javac] Compiling 7 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig\n for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 18 seconds\n" }, { "code": null, "e": 16263, "s": 16161, "text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −" }, { "code": null, "e": 16352, "s": 16263, "text": "Here, we can see that the country names are arranged in descending order alphabetically." }, { "code": null, "e": 16359, "s": 16352, "text": " Print" }, { "code": null, "e": 16370, "s": 16359, "text": " Add Notes" } ]
Get SubList from LinkedList in Java
The subList of a LinkedList can be obtained using the java.util.LinkedList.subList(). This method takes two parameters i.e. the start index for the sub-list(inclusive) and the end index for the sub-list(exclusive) from the required LinkedList. If the start index and the end index are the same, then an empty sub-list is returned. A program that demonstrates this is given as follows − Live Demo import java.util.LinkedList; import java.util.List; public class Demo { public static void main(String[] args) { LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList is: " + l); List subl = l.subList(1, 3); System.out.println("The SubList is: " + subl); } } The LinkedList is: [John, Sara, Susan, Betty, Nathan] The SubList is: [Sara, Susan] Now let us understand the above program. The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows − LinkedList<String> l = new LinkedList<String>(); l.add("John"); l.add("Sara"); l.add("Susan"); l.add("Betty"); l.add("Nathan"); System.out.println("The LinkedList is: " + l); The LinkedList.subList() method is used to create a sub-list which contains the elements from index 1(inclusive) to 3(exclusive) of the LinkedList. Then the sub-list elements are displayed. A code snippet which demonstrates this is as follows − List subl = l.subList(1, 3); System.out.println("The SubList is: " + subl);
[ { "code": null, "e": 1393, "s": 1062, "text": "The subList of a LinkedList can be obtained using the java.util.LinkedList.subList(). This method takes two parameters i.e. the start index for the sub-list(inclusive) and the end index for the sub-list(exclusive) from the required LinkedList. If the start index and the end index are the same, then an empty sub-list is returned." }, { "code": null, "e": 1448, "s": 1393, "text": "A program that demonstrates this is given as follows −" }, { "code": null, "e": 1459, "s": 1448, "text": " Live Demo" }, { "code": null, "e": 1887, "s": 1459, "text": "import java.util.LinkedList;\nimport java.util.List;\npublic class Demo {\n public static void main(String[] args) {\n LinkedList<String> l = new LinkedList<String>();\n l.add(\"John\");\n l.add(\"Sara\");\n l.add(\"Susan\");\n l.add(\"Betty\");\n l.add(\"Nathan\");\n System.out.println(\"The LinkedList is: \" + l);\n List subl = l.subList(1, 3);\n System.out.println(\"The SubList is: \" + subl);\n }\n}" }, { "code": null, "e": 1971, "s": 1887, "text": "The LinkedList is: [John, Sara, Susan, Betty, Nathan]\nThe SubList is: [Sara, Susan]" }, { "code": null, "e": 2012, "s": 1971, "text": "Now let us understand the above program." }, { "code": null, "e": 2199, "s": 2012, "text": "The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2374, "s": 2199, "text": "LinkedList<String> l = new LinkedList<String>();\nl.add(\"John\");\nl.add(\"Sara\");\nl.add(\"Susan\");\nl.add(\"Betty\");\nl.add(\"Nathan\");\nSystem.out.println(\"The LinkedList is: \" + l);" }, { "code": null, "e": 2619, "s": 2374, "text": "The LinkedList.subList() method is used to create a sub-list which contains the elements from index 1(inclusive) to 3(exclusive) of the LinkedList. Then the sub-list elements are displayed. A code snippet which demonstrates this is as follows −" }, { "code": null, "e": 2695, "s": 2619, "text": "List subl = l.subList(1, 3);\nSystem.out.println(\"The SubList is: \" + subl);" } ]
PHP | array_pop() Function - GeeksforGeeks
18 Nov, 2019 This inbuilt function of PHP is used to delete or pop out and return the last element from an array passed to it as parameter. It reduces the size of the array by one since the last element is removed from the array. Syntax: array_pop($array) Parameters: The function takes only one parameter $array, that is the input array and pops out the last element from it, reducing the size by one. Return Value: This function returns the last element of the array. If the array is empty or the input parameter is not an array, then NULL is returned. Note: This function resets the (reset()) the array pointer of the input array after use. Examples: Input : $array = (1=>"ram", 2=>"krishna", 3=>"aakash"); Output : aakash Input : $array = (24, 48, 95, 100, 120); Output : 120 Below programs illustrate the array_pop() function in PHP: Example 1 <?php// PHP code to illustrate the use of array_pop() $array = array(1=>"ram", 2=>"krishna", 3=>"aakash"); print_r("Popped element is ");echo array_pop($array); print_r("\nAfter popping the last element, ". "the array reduces to: \n");print_r($array);?> Output: Popped element is aakash After popping the last element, the array reduces to: Array ( [1] => ram [2] => krishna ) Example 2 <?php$arr = array(24, 48, 95, 100, 120); print_r("Popped element is ");echo array_pop($arr); print_r("\nAfter popping the last element, ". "the array reduces to: \n");print_r($arr);?> Output: Popped element is 120 After popping the last element, the array reduces to: Array ( [0] => 24 [1] => 48 [2] => 95 [3] => 10 ) Exception: An E_WARNING exception is thrown if a non-array is passed which is a runtime error or warning. This warning will not stop the execution of script. Reference:http://php.net/manual/en/function.array-pop.php Akanksha_Rai PHP-array PHP-function PHP 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 ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24053, "s": 24025, "text": "\n18 Nov, 2019" }, { "code": null, "e": 24270, "s": 24053, "text": "This inbuilt function of PHP is used to delete or pop out and return the last element from an array passed to it as parameter. It reduces the size of the array by one since the last element is removed from the array." }, { "code": null, "e": 24278, "s": 24270, "text": "Syntax:" }, { "code": null, "e": 24296, "s": 24278, "text": "array_pop($array)" }, { "code": null, "e": 24443, "s": 24296, "text": "Parameters: The function takes only one parameter $array, that is the input array and pops out the last element from it, reducing the size by one." }, { "code": null, "e": 24595, "s": 24443, "text": "Return Value: This function returns the last element of the array. If the array is empty or the input parameter is not an array, then NULL is returned." }, { "code": null, "e": 24684, "s": 24595, "text": "Note: This function resets the (reset()) the array pointer of the input array after use." }, { "code": null, "e": 24694, "s": 24684, "text": "Examples:" }, { "code": null, "e": 24822, "s": 24694, "text": "Input : $array = (1=>\"ram\", 2=>\"krishna\", 3=>\"aakash\");\nOutput : aakash\n\nInput : $array = (24, 48, 95, 100, 120);\nOutput : 120\n" }, { "code": null, "e": 24881, "s": 24822, "text": "Below programs illustrate the array_pop() function in PHP:" }, { "code": null, "e": 24891, "s": 24881, "text": "Example 1" }, { "code": "<?php// PHP code to illustrate the use of array_pop() $array = array(1=>\"ram\", 2=>\"krishna\", 3=>\"aakash\"); print_r(\"Popped element is \");echo array_pop($array); print_r(\"\\nAfter popping the last element, \". \"the array reduces to: \\n\");print_r($array);?>", "e": 25163, "s": 24891, "text": null }, { "code": null, "e": 25171, "s": 25163, "text": "Output:" }, { "code": null, "e": 25296, "s": 25171, "text": "Popped element is aakash\nAfter popping the last element, the array reduces to: \nArray\n(\n [1] => ram\n [2] => krishna\n)\n" }, { "code": null, "e": 25306, "s": 25296, "text": "Example 2" }, { "code": "<?php$arr = array(24, 48, 95, 100, 120); print_r(\"Popped element is \");echo array_pop($arr); print_r(\"\\nAfter popping the last element, \". \"the array reduces to: \\n\");print_r($arr);?>", "e": 25507, "s": 25306, "text": null }, { "code": null, "e": 25515, "s": 25507, "text": "Output:" }, { "code": null, "e": 25660, "s": 25515, "text": "Popped element is 120\nAfter popping the last element, the array reduces to: \nArray\n(\n [0] => 24\n [1] => 48\n [2] => 95\n [3] => 10\n)\n\n" }, { "code": null, "e": 25818, "s": 25660, "text": "Exception: An E_WARNING exception is thrown if a non-array is passed which is a runtime error or warning. This warning will not stop the execution of script." }, { "code": null, "e": 25876, "s": 25818, "text": "Reference:http://php.net/manual/en/function.array-pop.php" }, { "code": null, "e": 25889, "s": 25876, "text": "Akanksha_Rai" }, { "code": null, "e": 25899, "s": 25889, "text": "PHP-array" }, { "code": null, "e": 25912, "s": 25899, "text": "PHP-function" }, { "code": null, "e": 25916, "s": 25912, "text": "PHP" }, { "code": null, "e": 25933, "s": 25916, "text": "Web Technologies" }, { "code": null, "e": 25937, "s": 25933, "text": "PHP" }, { "code": null, "e": 26035, "s": 25937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26044, "s": 26035, "text": "Comments" }, { "code": null, "e": 26057, "s": 26044, "text": "Old Comments" }, { "code": null, "e": 26107, "s": 26057, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 26147, "s": 26107, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 26192, "s": 26147, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 26225, "s": 26192, "text": "Download file from URL using PHP" }, { "code": null, "e": 26307, "s": 26225, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 26363, "s": 26307, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26396, "s": 26363, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26458, "s": 26396, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26501, "s": 26458, "text": "How to fetch data from an API in ReactJS ?" } ]
Protected vs Private Access Modifiers in Java - GeeksforGeeks
28 Apr, 2021 Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. Access Modifier 1: Protected The methods or variables declared as protected are accessible within the same package or different packages. By using protected keywords, we can declare the methods/variables protected. Syntax: protected void method_name(){ ......code goes here.......... } Example: Java // Java Program to illustrate Protected Access Modifier // Importing input output classesimport java.io.*; // Main class public class Main { // Input custom string protected String name = "Geeks for Geeks"; // Main driver method public static void main(String[] args) { // Creating an object of Main class Main obj1 = new Main(); // Displaying the object content as created // above of Main class itself System.out.println( obj1.name ); }} Geeks for Geeks Access Modifier 2: Private The methods or variables that are declared as private are accessible only within the class in which they are declared. By using private keyword we can set methods/variables private. Syntax: private void method_name(){ ......code goes here.......... } Example: Java // Java Program to illustrate Private Access Modifier // Importing input output classesimport java.io.*; // Main classpublic class Main { // Input custom string private String name = "Geeks for Geeks"; // Main driver method public static void main(String[] args) { // Creating an object of Main class Main obj1 = new Main(); // Displaying the object content as created // above of Main class itself System.out.println(obj1.name); }} Geeks for Geeks Now after having an understanding of the internal working of both of them let us come to conclude targeted major differences between these access modifiers. Java-Modifier Picked Difference Between Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Difference Between Spark DataFrame and Pandas DataFrame Difference between Internal and External fragmentation Difference between Top down parsing and Bottom up parsing Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java HashMap in Java with Examples
[ { "code": null, "e": 24778, "s": 24750, "text": "\n28 Apr, 2021" }, { "code": null, "e": 25035, "s": 24778, "text": "Access modifiers are those elements in code that determine the scope for that variable. As we know there are three access modifiers available namely public, protected, and private. Let us see the differences between Protected and Private access modifiers. " }, { "code": null, "e": 25064, "s": 25035, "text": "Access Modifier 1: Protected" }, { "code": null, "e": 25250, "s": 25064, "text": "The methods or variables declared as protected are accessible within the same package or different packages. By using protected keywords, we can declare the methods/variables protected." }, { "code": null, "e": 25258, "s": 25250, "text": "Syntax:" }, { "code": null, "e": 25323, "s": 25258, "text": "protected void method_name(){\n\n......code goes here..........\n\n}" }, { "code": null, "e": 25332, "s": 25323, "text": "Example:" }, { "code": null, "e": 25337, "s": 25332, "text": "Java" }, { "code": "// Java Program to illustrate Protected Access Modifier // Importing input output classesimport java.io.*; // Main class public class Main { // Input custom string protected String name = \"Geeks for Geeks\"; // Main driver method public static void main(String[] args) { // Creating an object of Main class Main obj1 = new Main(); // Displaying the object content as created // above of Main class itself System.out.println( obj1.name ); }}", "e": 25826, "s": 25337, "text": null }, { "code": null, "e": 25842, "s": 25826, "text": "Geeks for Geeks" }, { "code": null, "e": 25870, "s": 25842, "text": "Access Modifier 2: Private " }, { "code": null, "e": 26052, "s": 25870, "text": "The methods or variables that are declared as private are accessible only within the class in which they are declared. By using private keyword we can set methods/variables private." }, { "code": null, "e": 26061, "s": 26052, "text": "Syntax: " }, { "code": null, "e": 26124, "s": 26061, "text": "private void method_name(){\n\n......code goes here..........\n\n}" }, { "code": null, "e": 26133, "s": 26124, "text": "Example:" }, { "code": null, "e": 26138, "s": 26133, "text": "Java" }, { "code": "// Java Program to illustrate Private Access Modifier // Importing input output classesimport java.io.*; // Main classpublic class Main { // Input custom string private String name = \"Geeks for Geeks\"; // Main driver method public static void main(String[] args) { // Creating an object of Main class Main obj1 = new Main(); // Displaying the object content as created // above of Main class itself System.out.println(obj1.name); }}", "e": 26634, "s": 26138, "text": null }, { "code": null, "e": 26650, "s": 26634, "text": "Geeks for Geeks" }, { "code": null, "e": 26808, "s": 26650, "text": "Now after having an understanding of the internal working of both of them let us come to conclude targeted major differences between these access modifiers. " }, { "code": null, "e": 26822, "s": 26808, "text": "Java-Modifier" }, { "code": null, "e": 26829, "s": 26822, "text": "Picked" }, { "code": null, "e": 26848, "s": 26829, "text": "Difference Between" }, { "code": null, "e": 26853, "s": 26848, "text": "Java" }, { "code": null, "e": 26858, "s": 26853, "text": "Java" }, { "code": null, "e": 26956, "s": 26858, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26965, "s": 26956, "text": "Comments" }, { "code": null, "e": 26978, "s": 26965, "text": "Old Comments" }, { "code": null, "e": 27039, "s": 26978, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27107, "s": 27039, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 27163, "s": 27107, "text": "Difference Between Spark DataFrame and Pandas DataFrame" }, { "code": null, "e": 27218, "s": 27163, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 27276, "s": 27218, "text": "Difference between Top down parsing and Bottom up parsing" }, { "code": null, "e": 27291, "s": 27276, "text": "Arrays in Java" }, { "code": null, "e": 27335, "s": 27291, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27357, "s": 27335, "text": "For-each loop in Java" }, { "code": null, "e": 27382, "s": 27357, "text": "Reverse a string in Java" } ]
How to use data version control (dvc) in a machine learning project | by Matthias Bitzer | Towards Data Science
When working in a productive machine learning project you probably deal with a tone of data and several models. To keep track of which models were trained with which data, you should use a system to version the data, similar to versioning and tracking your code. One way to solve this problem is dvc (Data Version Control, https://dvc.org/), which approaches data versioning in a similar way to Git. To illustrate the use of dvc in a machine learning context, we assume that our data is divided into train, test and validation folders by default, with the amount of data increasing over time either through an active learning cycle or by manually adding new data. An example could be the following structure, whereby the labels were omitted here for simplification purposes: ├── train│ ├── image1.jpg│ ├── image2.jpg│ └── image3.jpg├── val│ └── image4.jpg└──test └── image5.jpg Normally, a minimal versioning system should have the following two capabilities: Tag a new set of data with a new version e.g. vx.y.z Return to old data versions or switch between different data versions very easy Among other features, dvc is capable of doing these tasks. For this purpose it works closely together with Git. First you need to install dvc which can be done using pip pip install dvc To start the versioning process you have to create a git repository in the base folder of your data and initialize dvc afterwards through git initdvc init Through the init command dvc has now created a .dvc folder containing its cache in order to save differences between different data versions and the config file which stores meta information. In the case you are wondering how git fits into this concept: The task of git in this case is not to version the data itself but to version the dvc files which save the meta informations of the version like the location of files corresponding to a special version or the information which file of your data belongs to the current data version. In order for git to ignore the data itself dvc also automatically writes to the .gitignore file. To commit the config file of dvc and the .gitignore file we need to do a initial commit git commit -m “Initial commit” Each data version is associated with their own .dvc files which again are associated with one commit or one head of Git. The dvc files define and track the data for a given version whereby the dvc files themself are tracked by Git. For me a good way to associate a new data version with a head of Git is to make a new branch for a new data version. To do this, before we define our first version we create a new branch with the name of the version and checkout to this branch: git checkout -b v0.0.1 Now we can define our first version by telling dvc which data should be tracked, which are in our case the train, val and test folders. This can be done by the dvc add command: dvc add train test val After that we now see new .dvc files for each folder like train.dvc inside our base folder. The folders themselves have been added to the .gitignore so that git doesn`t track the data itself which in our case is the task of dvc. In order to track the new .dvc files with Git we make the standard Git procedure for a commit with git add .git commit -m "Data versioning files added to Git" Now we have created our first version of our data by having stored which data belongs to the version in our .dvc files and referenced the .dvc themself by the current commit. Please note that you can also connect the git to a remote git to save and version the .dvc files remotely. The data in this case stays in the current folder and is not stored remotely (this can be also changed using dvc push and pull). We now have associated one state of our data with a version, but of course you don’t need data versioning for one fix data set. Therefore we now assume that two new images (image6.jpg and image7.jpg) are added to the train and test folders, so that the structure now looks like this: ├── train│ ├── image1.jpg│ ├── image2.jpg│ ├── image3.jpg│ └── image6.jpg├── val│ └── image5.jpg└── test ├── image4.jpg └── image7.jpg In order to create a new data version we repeat the previous steps. We therefore create a new branch corresponding to the new data version git checkout -b v0.0.2 As we already know, a new data version is always associated with their own .dvc files which store the meta information of the version. In order to update the .dvc files we need to tell dvc that it should track again the train and test folder as there is new data in these folders: dvc add train test The train.dvc and test.dvc files changed and dvc now tracks which files belongs to the current version. In order to track the new .dvc files inside the git branch we have to do a commit: git add .git commit -m "Data versioning files added to Git" Now the cool part is coming. When checking your git branches you see two different branches (master excluded) where each branch corresponds to one data version: masterv0.0.1* v0.0.2 You are now able to get back to an older data version and update your data directory directly in order to recreate the old data version. In order to get back to the previous version we need to do two things. First we need to checkout to the corresponding head of the data version which is in this case the branch v0.0.1: git checkout v0.0.1 In this head the .dvc files are different compared to v0.0.2 but out current data directory still looks the same and the data inside the directory still corresponds to v0.0.2. This is because dvc has not yet aligned the data directory with its .dvc files. To align your data directory to the correct data version, which again is persistent in the .dvc files, one need to perform the dvc checkout command: dvc checkout This command restores the old data version (in this case v0.0.1) using its cache. When you now look into your data repository you see again the following structure: ├── train│ ├── image1.jpg│ ├── image2.jpg│ └── image3.jpg├── val│ └── image4.jpg└──test └── image5.jpg The files image6.jpg and image7.jpg were removed from the data directories and stored into the cache of dvc. You can now work with the old data version just as usual with the three folders. This procedure also works for data versions containing a lot more data than currently persistent in the data folder as dvc stores differences of arbitrary size between different versions in its cache and can therefore recreate older or newer states of the data directories by its checkout command. The checkout is of course also possible in the other direction. You could checkout the git to branch v0.0.2 and perform a dvc checkout in order to set the data directory to the state of version v0.0.2. Besides the init, add and checkout command dvc has a lot more features in order to make the machine learning/big data workflow more easy. For example can data versions be shared between multiple machines using a remote bucket like Amazon’s S3 Bucket and interacting with the bucket using dvc push and pull (for Details see. https://dvc.org/). I hope this article can help to better organize the data in a Machine Learning project and to keep a better overview. For more blog posts about Machine Learning, Data Science and Statistics checkout www.matthias-bitzer.de
[ { "code": null, "e": 572, "s": 172, "text": "When working in a productive machine learning project you probably deal with a tone of data and several models. To keep track of which models were trained with which data, you should use a system to version the data, similar to versioning and tracking your code. One way to solve this problem is dvc (Data Version Control, https://dvc.org/), which approaches data versioning in a similar way to Git." }, { "code": null, "e": 947, "s": 572, "text": "To illustrate the use of dvc in a machine learning context, we assume that our data is divided into train, test and validation folders by default, with the amount of data increasing over time either through an active learning cycle or by manually adding new data. An example could be the following structure, whereby the labels were omitted here for simplification purposes:" }, { "code": null, "e": 1066, "s": 947, "text": "├── train│ ├── image1.jpg│ ├── image2.jpg│ └── image3.jpg├── val│ └── image4.jpg└──test └── image5.jpg" }, { "code": null, "e": 1148, "s": 1066, "text": "Normally, a minimal versioning system should have the following two capabilities:" }, { "code": null, "e": 1201, "s": 1148, "text": "Tag a new set of data with a new version e.g. vx.y.z" }, { "code": null, "e": 1281, "s": 1201, "text": "Return to old data versions or switch between different data versions very easy" }, { "code": null, "e": 1451, "s": 1281, "text": "Among other features, dvc is capable of doing these tasks. For this purpose it works closely together with Git. First you need to install dvc which can be done using pip" }, { "code": null, "e": 1468, "s": 1451, "text": "pip install dvc " }, { "code": null, "e": 1606, "s": 1468, "text": "To start the versioning process you have to create a git repository in the base folder of your data and initialize dvc afterwards through" }, { "code": null, "e": 1623, "s": 1606, "text": "git initdvc init" }, { "code": null, "e": 1815, "s": 1623, "text": "Through the init command dvc has now created a .dvc folder containing its cache in order to save differences between different data versions and the config file which stores meta information." }, { "code": null, "e": 2159, "s": 1815, "text": "In the case you are wondering how git fits into this concept: The task of git in this case is not to version the data itself but to version the dvc files which save the meta informations of the version like the location of files corresponding to a special version or the information which file of your data belongs to the current data version." }, { "code": null, "e": 2344, "s": 2159, "text": "In order for git to ignore the data itself dvc also automatically writes to the .gitignore file. To commit the config file of dvc and the .gitignore file we need to do a initial commit" }, { "code": null, "e": 2375, "s": 2344, "text": "git commit -m “Initial commit”" }, { "code": null, "e": 2852, "s": 2375, "text": "Each data version is associated with their own .dvc files which again are associated with one commit or one head of Git. The dvc files define and track the data for a given version whereby the dvc files themself are tracked by Git. For me a good way to associate a new data version with a head of Git is to make a new branch for a new data version. To do this, before we define our first version we create a new branch with the name of the version and checkout to this branch:" }, { "code": null, "e": 2875, "s": 2852, "text": "git checkout -b v0.0.1" }, { "code": null, "e": 3052, "s": 2875, "text": "Now we can define our first version by telling dvc which data should be tracked, which are in our case the train, val and test folders. This can be done by the dvc add command:" }, { "code": null, "e": 3075, "s": 3052, "text": "dvc add train test val" }, { "code": null, "e": 3403, "s": 3075, "text": "After that we now see new .dvc files for each folder like train.dvc inside our base folder. The folders themselves have been added to the .gitignore so that git doesn`t track the data itself which in our case is the task of dvc. In order to track the new .dvc files with Git we make the standard Git procedure for a commit with" }, { "code": null, "e": 3463, "s": 3403, "text": "git add .git commit -m \"Data versioning files added to Git\"" }, { "code": null, "e": 3874, "s": 3463, "text": "Now we have created our first version of our data by having stored which data belongs to the version in our .dvc files and referenced the .dvc themself by the current commit. Please note that you can also connect the git to a remote git to save and version the .dvc files remotely. The data in this case stays in the current folder and is not stored remotely (this can be also changed using dvc push and pull)." }, { "code": null, "e": 4158, "s": 3874, "text": "We now have associated one state of our data with a version, but of course you don’t need data versioning for one fix data set. Therefore we now assume that two new images (image6.jpg and image7.jpg) are added to the train and test folders, so that the structure now looks like this:" }, { "code": null, "e": 4318, "s": 4158, "text": "├── train│ ├── image1.jpg│ ├── image2.jpg│ ├── image3.jpg│ └── image6.jpg├── val│ └── image5.jpg└── test ├── image4.jpg └── image7.jpg" }, { "code": null, "e": 4457, "s": 4318, "text": "In order to create a new data version we repeat the previous steps. We therefore create a new branch corresponding to the new data version" }, { "code": null, "e": 4480, "s": 4457, "text": "git checkout -b v0.0.2" }, { "code": null, "e": 4761, "s": 4480, "text": "As we already know, a new data version is always associated with their own .dvc files which store the meta information of the version. In order to update the .dvc files we need to tell dvc that it should track again the train and test folder as there is new data in these folders:" }, { "code": null, "e": 4780, "s": 4761, "text": "dvc add train test" }, { "code": null, "e": 4967, "s": 4780, "text": "The train.dvc and test.dvc files changed and dvc now tracks which files belongs to the current version. In order to track the new .dvc files inside the git branch we have to do a commit:" }, { "code": null, "e": 5027, "s": 4967, "text": "git add .git commit -m \"Data versioning files added to Git\"" }, { "code": null, "e": 5188, "s": 5027, "text": "Now the cool part is coming. When checking your git branches you see two different branches (master excluded) where each branch corresponds to one data version:" }, { "code": null, "e": 5209, "s": 5188, "text": "masterv0.0.1* v0.0.2" }, { "code": null, "e": 5530, "s": 5209, "text": "You are now able to get back to an older data version and update your data directory directly in order to recreate the old data version. In order to get back to the previous version we need to do two things. First we need to checkout to the corresponding head of the data version which is in this case the branch v0.0.1:" }, { "code": null, "e": 5550, "s": 5530, "text": "git checkout v0.0.1" }, { "code": null, "e": 5955, "s": 5550, "text": "In this head the .dvc files are different compared to v0.0.2 but out current data directory still looks the same and the data inside the directory still corresponds to v0.0.2. This is because dvc has not yet aligned the data directory with its .dvc files. To align your data directory to the correct data version, which again is persistent in the .dvc files, one need to perform the dvc checkout command:" }, { "code": null, "e": 5968, "s": 5955, "text": "dvc checkout" }, { "code": null, "e": 6133, "s": 5968, "text": "This command restores the old data version (in this case v0.0.1) using its cache. When you now look into your data repository you see again the following structure:" }, { "code": null, "e": 6252, "s": 6133, "text": "├── train│ ├── image1.jpg│ ├── image2.jpg│ └── image3.jpg├── val│ └── image4.jpg└──test └── image5.jpg" }, { "code": null, "e": 6442, "s": 6252, "text": "The files image6.jpg and image7.jpg were removed from the data directories and stored into the cache of dvc. You can now work with the old data version just as usual with the three folders." }, { "code": null, "e": 6942, "s": 6442, "text": "This procedure also works for data versions containing a lot more data than currently persistent in the data folder as dvc stores differences of arbitrary size between different versions in its cache and can therefore recreate older or newer states of the data directories by its checkout command. The checkout is of course also possible in the other direction. You could checkout the git to branch v0.0.2 and perform a dvc checkout in order to set the data directory to the state of version v0.0.2." }, { "code": null, "e": 7285, "s": 6942, "text": "Besides the init, add and checkout command dvc has a lot more features in order to make the machine learning/big data workflow more easy. For example can data versions be shared between multiple machines using a remote bucket like Amazon’s S3 Bucket and interacting with the bucket using dvc push and pull (for Details see. https://dvc.org/)." }, { "code": null, "e": 7403, "s": 7285, "text": "I hope this article can help to better organize the data in a Machine Learning project and to keep a better overview." } ]
Data Structures | Heap | Question 4 - GeeksforGeeks
28 Jun, 2021 Suppose the elements 7, 2, 10 and 4 are inserted, in that order, into the valid 3- ary max heap found in the above question, Which one of the following is the sequence of items in the array representing the resultant heap? (A) 10, 7, 9, 8, 3, 1, 5, 2, 6, 4(B) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1(C) 10, 9, 4, 5, 7, 6, 8, 2, 1, 3(D) 10, 8, 6, 9, 7, 2, 3, 4, 1, 5Answer: (A)Explanation: After insertion of 7 9 / | \ / | \ 7 6 8 / | \ / | \ 3 1 5 After insertion of 2 9 / | \ / | \ 7 6 8 / | \ / / | \ / 3 1 5 2 After insertion of 10 10 / | \ / | \ 7 9 8 / | \ / | / | \ / | 3 1 5 2 6 After insertion of 4 10 / | \ / | \ 7 9 8 / | \ / | \ / | \ / | \ 3 1 5 2 6 4 Quiz of this Question Data Structures Data Structures-Heap Heap Quizzes Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C program to implement Adjacency Matrix of a given Graph Advantages and Disadvantages of Linked List Difference between Singly linked list and Doubly linked list Data Structures | Array | Question 2 Multilevel Linked List Introduction to Data Structures | 10 most commonly used Data Structures Data Structures | Linked List | Question 6 FIFO vs LIFO approach in Programming Difference between data type and data structure Count of triplets in an Array (i, j, k) such that i < j < k and a[k] < a[i] < a[j]
[ { "code": null, "e": 24762, "s": 24734, "text": "\n28 Jun, 2021" }, { "code": null, "e": 24985, "s": 24762, "text": "Suppose the elements 7, 2, 10 and 4 are inserted, in that order, into the valid 3- ary max heap found in the above question, Which one of the following is the sequence of items in the array representing the resultant heap?" }, { "code": null, "e": 25162, "s": 24985, "text": "(A) 10, 7, 9, 8, 3, 1, 5, 2, 6, 4(B) 10, 9, 8, 7, 6, 5, 4, 3, 2, 1(C) 10, 9, 4, 5, 7, 6, 8, 2, 1, 3(D) 10, 8, 6, 9, 7, 2, 3, 4, 1, 5Answer: (A)Explanation: After insertion of 7" }, { "code": null, "e": 25476, "s": 25162, "text": " 9\n / | \\\n / | \\\n 7 6 8\n / | \\\n / | \\\n 3 1 5 \n" }, { "code": null, "e": 25497, "s": 25476, "text": "After insertion of 2" }, { "code": null, "e": 25828, "s": 25497, "text": " 9\n / | \\\n / | \\\n 7 6 8\n / | \\ /\n / | \\ /\n 3 1 5 2\n" }, { "code": null, "e": 25850, "s": 25828, "text": "After insertion of 10" }, { "code": null, "e": 26121, "s": 25850, "text": " 10\n / | \\\n / | \\\n 7 9 8\n / | \\ / |\n / | \\ / |\n 3 1 5 2 6\n" }, { "code": null, "e": 26142, "s": 26121, "text": "After insertion of 4" }, { "code": null, "e": 26425, "s": 26142, "text": " 10\n / | \\\n / | \\\n 7 9 8\n / | \\ / | \\\n / | \\ / | \\\n 3 1 5 2 6 4\n" }, { "code": null, "e": 26447, "s": 26425, "text": "Quiz of this Question" }, { "code": null, "e": 26463, "s": 26447, "text": "Data Structures" }, { "code": null, "e": 26484, "s": 26463, "text": "Data Structures-Heap" }, { "code": null, "e": 26497, "s": 26484, "text": "Heap Quizzes" }, { "code": null, "e": 26513, "s": 26497, "text": "Data Structures" }, { "code": null, "e": 26529, "s": 26513, "text": "Data Structures" }, { "code": null, "e": 26627, "s": 26529, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26636, "s": 26627, "text": "Comments" }, { "code": null, "e": 26649, "s": 26636, "text": "Old Comments" }, { "code": null, "e": 26706, "s": 26649, "text": "C program to implement Adjacency Matrix of a given Graph" }, { "code": null, "e": 26750, "s": 26706, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 26811, "s": 26750, "text": "Difference between Singly linked list and Doubly linked list" }, { "code": null, "e": 26848, "s": 26811, "text": "Data Structures | Array | Question 2" }, { "code": null, "e": 26871, "s": 26848, "text": "Multilevel Linked List" }, { "code": null, "e": 26943, "s": 26871, "text": "Introduction to Data Structures | 10 most commonly used Data Structures" }, { "code": null, "e": 26986, "s": 26943, "text": "Data Structures | Linked List | Question 6" }, { "code": null, "e": 27023, "s": 26986, "text": "FIFO vs LIFO approach in Programming" }, { "code": null, "e": 27071, "s": 27023, "text": "Difference between data type and data structure" } ]
Introduction to Interactive Time Series Visualizations with Plotly in Python | by Will Koehrsen | Towards Data Science
There comes a time when it’s necessary to move on from even the most beloved tools. Matplotlib has served its purpose of quickly creating simple charts, but I’ve grown frustrated with how much code is required to customize plots or do seemingly easy things like get the x-axis to correctly show dates. For a while, I’ve been looking for an alternative — not a complete replacement as Matplotlib is still useful for exploration — ideally, a library that has interactive elements and lets me focus on what I want to show instead of getting caught in the how to show it details. Enter plotly, a declarative visualization tool with an easy-to-use Python library for interactive graphs. In this article, we’ll get an introduction to the plotly library by walking through making basic time series visualizations. These graphs, though easy to make, will be fully interactive figures ready for presentation. Along the way, we’ll learn the basic ideas of the library which will later allow us to rapidly build stunning visualizations. If you have been looking for an alternative to matplotlib, then as we’ll see, plotly is an effective choice. The full code for this article is available on GitHub. You can also view the notebook with interactive elements on nbviewer. The data used in this article is anonymized building energy time-series data from my job at Cortex Building Intelligence. If you want to use your web dev skills to help buildings save energy, then get in touch because we’re hiring! Plotly is a company that makes visualization tools including a Python API library. (Plotly also makes Dash, a framework for building interactive web-based applications with Python code). For this article, we’ll stick to working with the plotly Python library in a Jupyter Notebook and touching up images in the online plotly editor. When we make a plotly graph, it’s published online by default which makes sharing visualizations easy. You will need to create a free plotly account which gives you 25 public charts and 1 private chart. Once you hit your quota, you’ll have to delete some of the old charts to make new ones (or you can run in an offline mode where images only appear in the notebook). Install plotly ( pip install plotly ) and run the following to authenticate the library, replacing the username and API key: import plotly# Authenticate with your accountplotly.tools.set_credentials_file(username='########', api_key='******') The standard plotly imports along with the settings to run offline are: import plotly.plotly as pyimport plotly.graph_objs as go# Offline modefrom plotly.offline import init_notebook_mode, iplotinit_notebook_mode(connected=True) When we make plots in offline mode, we’ll get a link in the bottom right of the image to export to the plotly online editor to make touch-ups and share. Plotly (the Python library) uses declarative programming which means we write code describing what we want to make rather than how to make it. We provide the basic framework and end goals and let plotly figure out the implementation details. In practice, this means less effort spent building up a figure, allowing us to focus on what to present and how to interpret it. If you don’t believe in the benefits of this method, then go check out the dozens of examples such as the one below made with 50 lines of code. For this project, we’ll be using real-world building data from my job at Cortex Building Intelligence (data has been anonymized). Building energy data presents intriguing challenges for time-series analysis because of seasonal, daily, and weekly patterns and drastic effects from weather conditions. Effectively visualizing this data can help us understand the response of a building and where there are chances for energy savings. (As a note, I use the terms “Power” and “Energy” interchangeably even though energy is the ability to do work while power is the rate of energy consumption. Technically, power is measured in kilowatts (KW) and electrical energy is measured in KiloWatt Hours (KWh). The more you know!) Our data is in a dataframe with a multi-index on the columns to keep track of the sensor type and the sensor number. The index is a datetime: Working with multi-index dataframes is an entirely different article (here are the docs), but we won’t do anything too complicated. To access a single column and plot it, we can do the following. import pandas as pd# Read in data with two headersdf = pd.read_csv('building_one.csv', header=[0,1], index_col=0)# Extract energy series from multi-indexenergy_series = df.loc[:, ('Energy', '3')]# Plotenergy_series.plot() The default plot (provided by matplotlib) looks like: This isn’t terrible, especially for one line of code. However, there is no interactivity, and it’s not visually appealing. Time to get into plotly. Much like Bokeh (articles), making a basic plot requires a little more work in plotly, but in return, we get much more, like built-in interactivity. We build up a graph starting with a data object. Even though we want a line chart, we use go.Scatter() . Plotly is smart enough to automatically give us a line graph if we pass in more than 20 points! For the most basic graph, all we need is the x and y values: energy_data = go.Scatter(x=energy_series.index, y=energy_series.values) Then, we create a layout using the default settings along with some titles: layout = go.Layout(title='Energy Plot', xaxis=dict(title='Date'), yaxis=dict(title='(kWh)')) (We use dict(x = 'value') syntax which is the same as {'x': 'value'} ). Finally, we can create our figure and display it interactively in the notebook: fig = go.Figure(data=[energy_data], layout=layout)py.iplot(fig, sharing='public') Right away, we have a fully interactive graph. We can explore patterns, inspect individual points, and download the plot as an image. Notice that we didn’t even need to specify the axis types or ranges, plotly got that completely right for us. We even get nicely formatted hover messages with no extra work. What’s more, this plot is automatically exported to plotly which means we can share the chart with anyone. We can also click Edit Chart and open it up in the online editor to make any changes we want in an easy-to-use interface: If you edit the chart in the online editor you can then automatically generate the Python code for the exact graph and style you have created! Even a basic time-series plot in Plotly is impressive but we can improve it with a few more lines of code. For example, let’s say we want to compare the steam usage of the building with the energy. These two quantities have vastly different units, so if we show them on the same scale it won’t work out. This is a case where we have to use a secondary y-axis. In matplotlib, this requires a large amount of formatting work, but we can do it quite easily in Plotly. The first step is to add another data source, but this time specify yaxis='y2'. # Get the steam datasteam_series = df.loc[:, ("Steam", "4")]# Create the steam data objectsteam_data = go.Scatter(x=steam_series.index, y=steam_series.values, # Specify axis yaxis='y2') (We also add in a few other parameters to improve the styling which can be seen in the notebook). Then, when we create the layout, we need to add a second y-axis. layout = go.Layout(height=600, width=800, title='Energy and Steam Plot', # Same x and first y xaxis=dict(title='Date'), yaxis=dict(title='Energy', color='red'), # Add a second yaxis to the right of the plot yaxis2=dict(title='Steam', color='blue', overlaying='y', side='right') )fig = go.Figure(data=[energy_data, steam_data], layout=layout)py.iplot(fig, sharing='public') When we display the graph, we get both steam and energy on the same graph with properly scaled axes. With a little online editing, we get a finished product: Plot annotations are used to call out aspects of a visualization for attention. As one example, we can highlight the daily high consumption of steam while looking at a week’s worth of data. First, we’ll subset the steam sensor into one week (called steam_series_four) and create a formatted data object: # Data objectsteam_data_four = go.Scatter( x=steam_series_four.index, y=steam_series_four.values, line=dict(color='blue', width=1.1), opacity=0.8, name='Steam: Sensor 4', hoverinfo = 'text', text = [f'Sensor 4: {x:.1f} Mlbs/hr' for x in steam_series_four.values]) Then, we’ll find the daily max values for this sensor (see notebook for code): To build the annotations, we’ll use a list comprehension adding an annotation for each of the daily maximum values ( four_highs is the above series). Each annotation needs a position ( x , y) and text: # Create a list of annotationsfour_annotations = [dict(x = date, y = value, xref = 'x', yref = 'y', font=dict(color = 'blue'), text = f'{format_date(date)}<br> {value[0]:.1f} Mlbs/hr') for date, value in zip(four_highs.index, four_highs.values)]four_annotations[:1]{'x': Timestamp('2018-02-05 06:30:00'), 'y': 17.98865890412107, 'xref': 'x', 'yref': 'y', 'font': {'color': 'blue'}, 'text': 'Mon <br> 06:30 AM<br> 18.0 Mlbs/hr'}} (The <br> in the text is html which is read by plotly for displaying). There are other parameters of an annotation that we can modify, but we’ll let plotly take care of the details. Adding the annotations to the plot is as simple as passing them to the layout : layout = go.Layout(height=800, width=1000, title='Steam Sensor with Daily High Annotations', annotations=four_annotations) After a little post-processing in the online editor, our final plot is: The extra annotations can give us insights into our data by showing when the daily peak in steam usage occurs. In turn, this will allow us to make steam start time recommendations to building engineers. The best part about plotly is we can get a basic plot quickly and extend the capabilities with a little more code. The upfront investment for a basic plot pays off when we want to add increased functionality. We have only scratched the surface of what we can do in plotly. I’ll explore some of these functions in a future article, and refer to the notebook for how to add even more interactivity such as selection menus. Eventually, we can build deployable web applications in Dash with Python code. For now, we know how to create basic — yet effective — time-series visualizations in plotly. These charts give us a lot for the small code investment and by touching up and sharing the plots online, we can build a finished, presentable product. Although I’m not abandoning matplotlib — one-line bar and line charts are hard to beat — it’s clear that using matplotlib for custom charts is not a good time investment. Instead, we can use other libraries, including plotly, to efficiently build full-featured interactive visualizations. Seeing your data in a graph is one of the joys of data science, but writing the code is often painful. Fortunately, with plotly, visualizations in Python are intuitive, even enjoyable to create and achieve the goal of graphs: visually understand our data. As always, I welcome feedback and constructive criticism. I can be reached on Twitter @koehrsen_will or through my personal website willk.online.
[ { "code": null, "e": 474, "s": 172, "text": "There comes a time when it’s necessary to move on from even the most beloved tools. Matplotlib has served its purpose of quickly creating simple charts, but I’ve grown frustrated with how much code is required to customize plots or do seemingly easy things like get the x-axis to correctly show dates." }, { "code": null, "e": 854, "s": 474, "text": "For a while, I’ve been looking for an alternative — not a complete replacement as Matplotlib is still useful for exploration — ideally, a library that has interactive elements and lets me focus on what I want to show instead of getting caught in the how to show it details. Enter plotly, a declarative visualization tool with an easy-to-use Python library for interactive graphs." }, { "code": null, "e": 1307, "s": 854, "text": "In this article, we’ll get an introduction to the plotly library by walking through making basic time series visualizations. These graphs, though easy to make, will be fully interactive figures ready for presentation. Along the way, we’ll learn the basic ideas of the library which will later allow us to rapidly build stunning visualizations. If you have been looking for an alternative to matplotlib, then as we’ll see, plotly is an effective choice." }, { "code": null, "e": 1664, "s": 1307, "text": "The full code for this article is available on GitHub. You can also view the notebook with interactive elements on nbviewer. The data used in this article is anonymized building energy time-series data from my job at Cortex Building Intelligence. If you want to use your web dev skills to help buildings save energy, then get in touch because we’re hiring!" }, { "code": null, "e": 2100, "s": 1664, "text": "Plotly is a company that makes visualization tools including a Python API library. (Plotly also makes Dash, a framework for building interactive web-based applications with Python code). For this article, we’ll stick to working with the plotly Python library in a Jupyter Notebook and touching up images in the online plotly editor. When we make a plotly graph, it’s published online by default which makes sharing visualizations easy." }, { "code": null, "e": 2490, "s": 2100, "text": "You will need to create a free plotly account which gives you 25 public charts and 1 private chart. Once you hit your quota, you’ll have to delete some of the old charts to make new ones (or you can run in an offline mode where images only appear in the notebook). Install plotly ( pip install plotly ) and run the following to authenticate the library, replacing the username and API key:" }, { "code": null, "e": 2687, "s": 2490, "text": "import plotly# Authenticate with your accountplotly.tools.set_credentials_file(username='########', api_key='******')" }, { "code": null, "e": 2759, "s": 2687, "text": "The standard plotly imports along with the settings to run offline are:" }, { "code": null, "e": 2916, "s": 2759, "text": "import plotly.plotly as pyimport plotly.graph_objs as go# Offline modefrom plotly.offline import init_notebook_mode, iplotinit_notebook_mode(connected=True)" }, { "code": null, "e": 3069, "s": 2916, "text": "When we make plots in offline mode, we’ll get a link in the bottom right of the image to export to the plotly online editor to make touch-ups and share." }, { "code": null, "e": 3440, "s": 3069, "text": "Plotly (the Python library) uses declarative programming which means we write code describing what we want to make rather than how to make it. We provide the basic framework and end goals and let plotly figure out the implementation details. In practice, this means less effort spent building up a figure, allowing us to focus on what to present and how to interpret it." }, { "code": null, "e": 3584, "s": 3440, "text": "If you don’t believe in the benefits of this method, then go check out the dozens of examples such as the one below made with 50 lines of code." }, { "code": null, "e": 4016, "s": 3584, "text": "For this project, we’ll be using real-world building data from my job at Cortex Building Intelligence (data has been anonymized). Building energy data presents intriguing challenges for time-series analysis because of seasonal, daily, and weekly patterns and drastic effects from weather conditions. Effectively visualizing this data can help us understand the response of a building and where there are chances for energy savings." }, { "code": null, "e": 4301, "s": 4016, "text": "(As a note, I use the terms “Power” and “Energy” interchangeably even though energy is the ability to do work while power is the rate of energy consumption. Technically, power is measured in kilowatts (KW) and electrical energy is measured in KiloWatt Hours (KWh). The more you know!)" }, { "code": null, "e": 4443, "s": 4301, "text": "Our data is in a dataframe with a multi-index on the columns to keep track of the sensor type and the sensor number. The index is a datetime:" }, { "code": null, "e": 4639, "s": 4443, "text": "Working with multi-index dataframes is an entirely different article (here are the docs), but we won’t do anything too complicated. To access a single column and plot it, we can do the following." }, { "code": null, "e": 4861, "s": 4639, "text": "import pandas as pd# Read in data with two headersdf = pd.read_csv('building_one.csv', header=[0,1], index_col=0)# Extract energy series from multi-indexenergy_series = df.loc[:, ('Energy', '3')]# Plotenergy_series.plot()" }, { "code": null, "e": 4915, "s": 4861, "text": "The default plot (provided by matplotlib) looks like:" }, { "code": null, "e": 5063, "s": 4915, "text": "This isn’t terrible, especially for one line of code. However, there is no interactivity, and it’s not visually appealing. Time to get into plotly." }, { "code": null, "e": 5212, "s": 5063, "text": "Much like Bokeh (articles), making a basic plot requires a little more work in plotly, but in return, we get much more, like built-in interactivity." }, { "code": null, "e": 5474, "s": 5212, "text": "We build up a graph starting with a data object. Even though we want a line chart, we use go.Scatter() . Plotly is smart enough to automatically give us a line graph if we pass in more than 20 points! For the most basic graph, all we need is the x and y values:" }, { "code": null, "e": 5570, "s": 5474, "text": "energy_data = go.Scatter(x=energy_series.index, y=energy_series.values)" }, { "code": null, "e": 5646, "s": 5570, "text": "Then, we create a layout using the default settings along with some titles:" }, { "code": null, "e": 5757, "s": 5646, "text": "layout = go.Layout(title='Energy Plot', xaxis=dict(title='Date'), yaxis=dict(title='(kWh)'))" }, { "code": null, "e": 5829, "s": 5757, "text": "(We use dict(x = 'value') syntax which is the same as {'x': 'value'} )." }, { "code": null, "e": 5909, "s": 5829, "text": "Finally, we can create our figure and display it interactively in the notebook:" }, { "code": null, "e": 5991, "s": 5909, "text": "fig = go.Figure(data=[energy_data], layout=layout)py.iplot(fig, sharing='public')" }, { "code": null, "e": 6299, "s": 5991, "text": "Right away, we have a fully interactive graph. We can explore patterns, inspect individual points, and download the plot as an image. Notice that we didn’t even need to specify the axis types or ranges, plotly got that completely right for us. We even get nicely formatted hover messages with no extra work." }, { "code": null, "e": 6528, "s": 6299, "text": "What’s more, this plot is automatically exported to plotly which means we can share the chart with anyone. We can also click Edit Chart and open it up in the online editor to make any changes we want in an easy-to-use interface:" }, { "code": null, "e": 6671, "s": 6528, "text": "If you edit the chart in the online editor you can then automatically generate the Python code for the exact graph and style you have created!" }, { "code": null, "e": 7136, "s": 6671, "text": "Even a basic time-series plot in Plotly is impressive but we can improve it with a few more lines of code. For example, let’s say we want to compare the steam usage of the building with the energy. These two quantities have vastly different units, so if we show them on the same scale it won’t work out. This is a case where we have to use a secondary y-axis. In matplotlib, this requires a large amount of formatting work, but we can do it quite easily in Plotly." }, { "code": null, "e": 7216, "s": 7136, "text": "The first step is to add another data source, but this time specify yaxis='y2'." }, { "code": null, "e": 7471, "s": 7216, "text": "# Get the steam datasteam_series = df.loc[:, (\"Steam\", \"4\")]# Create the steam data objectsteam_data = go.Scatter(x=steam_series.index, y=steam_series.values, # Specify axis yaxis='y2')" }, { "code": null, "e": 7569, "s": 7471, "text": "(We also add in a few other parameters to improve the styling which can be seen in the notebook)." }, { "code": null, "e": 7634, "s": 7569, "text": "Then, when we create the layout, we need to add a second y-axis." }, { "code": null, "e": 8163, "s": 7634, "text": "layout = go.Layout(height=600, width=800, title='Energy and Steam Plot', # Same x and first y xaxis=dict(title='Date'), yaxis=dict(title='Energy', color='red'), # Add a second yaxis to the right of the plot yaxis2=dict(title='Steam', color='blue', overlaying='y', side='right') )fig = go.Figure(data=[energy_data, steam_data], layout=layout)py.iplot(fig, sharing='public')" }, { "code": null, "e": 8264, "s": 8163, "text": "When we display the graph, we get both steam and energy on the same graph with properly scaled axes." }, { "code": null, "e": 8321, "s": 8264, "text": "With a little online editing, we get a finished product:" }, { "code": null, "e": 8625, "s": 8321, "text": "Plot annotations are used to call out aspects of a visualization for attention. As one example, we can highlight the daily high consumption of steam while looking at a week’s worth of data. First, we’ll subset the steam sensor into one week (called steam_series_four) and create a formatted data object:" }, { "code": null, "e": 9057, "s": 8625, "text": "# Data objectsteam_data_four = go.Scatter( x=steam_series_four.index, y=steam_series_four.values, line=dict(color='blue', width=1.1), opacity=0.8, name='Steam: Sensor 4', hoverinfo = 'text', text = [f'Sensor 4: {x:.1f} Mlbs/hr' for x in steam_series_four.values])" }, { "code": null, "e": 9136, "s": 9057, "text": "Then, we’ll find the daily max values for this sensor (see notebook for code):" }, { "code": null, "e": 9338, "s": 9136, "text": "To build the annotations, we’ll use a list comprehension adding an annotation for each of the daily maximum values ( four_highs is the above series). Each annotation needs a position ( x , y) and text:" }, { "code": null, "e": 9866, "s": 9338, "text": "# Create a list of annotationsfour_annotations = [dict(x = date, y = value, xref = 'x', yref = 'y', font=dict(color = 'blue'), text = f'{format_date(date)}<br> {value[0]:.1f} Mlbs/hr') for date, value in zip(four_highs.index, four_highs.values)]four_annotations[:1]{'x': Timestamp('2018-02-05 06:30:00'), 'y': 17.98865890412107, 'xref': 'x', 'yref': 'y', 'font': {'color': 'blue'}, 'text': 'Mon <br> 06:30 AM<br> 18.0 Mlbs/hr'}}" }, { "code": null, "e": 9937, "s": 9866, "text": "(The <br> in the text is html which is read by plotly for displaying)." }, { "code": null, "e": 10128, "s": 9937, "text": "There are other parameters of an annotation that we can modify, but we’ll let plotly take care of the details. Adding the annotations to the plot is as simple as passing them to the layout :" }, { "code": null, "e": 10288, "s": 10128, "text": "layout = go.Layout(height=800, width=1000, title='Steam Sensor with Daily High Annotations', annotations=four_annotations)" }, { "code": null, "e": 10360, "s": 10288, "text": "After a little post-processing in the online editor, our final plot is:" }, { "code": null, "e": 10563, "s": 10360, "text": "The extra annotations can give us insights into our data by showing when the daily peak in steam usage occurs. In turn, this will allow us to make steam start time recommendations to building engineers." }, { "code": null, "e": 10772, "s": 10563, "text": "The best part about plotly is we can get a basic plot quickly and extend the capabilities with a little more code. The upfront investment for a basic plot pays off when we want to add increased functionality." }, { "code": null, "e": 11156, "s": 10772, "text": "We have only scratched the surface of what we can do in plotly. I’ll explore some of these functions in a future article, and refer to the notebook for how to add even more interactivity such as selection menus. Eventually, we can build deployable web applications in Dash with Python code. For now, we know how to create basic — yet effective — time-series visualizations in plotly." }, { "code": null, "e": 11308, "s": 11156, "text": "These charts give us a lot for the small code investment and by touching up and sharing the plots online, we can build a finished, presentable product." }, { "code": null, "e": 11853, "s": 11308, "text": "Although I’m not abandoning matplotlib — one-line bar and line charts are hard to beat — it’s clear that using matplotlib for custom charts is not a good time investment. Instead, we can use other libraries, including plotly, to efficiently build full-featured interactive visualizations. Seeing your data in a graph is one of the joys of data science, but writing the code is often painful. Fortunately, with plotly, visualizations in Python are intuitive, even enjoyable to create and achieve the goal of graphs: visually understand our data." } ]
Python Program for Rabin-Karp Algorithm for Pattern Searching - GeeksforGeeks
30 Dec, 2020 Examples: Input: txt[] = "THIS IS A TEST TEXT" pat[] = "TEST" Output: Pattern found at index 10 Input: txt[] = "AABAACAADAABAABA" pat[] = "AABA" Output: Pattern found at index 0 Pattern found at index 9 Pattern found at index 12 The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings. 1) Pattern itself.2) All the substrings of text of length m. Python # Following program is the python implementation of# Rabin Karp Algorithm given in CLRS book # d is the number of characters in the input alphabetd = 256 # pat -> pattern# txt -> text# q -> A prime number def search(pat, txt, q): M = len(pat) N = len(txt) i = 0 j = 0 p = 0 # hash value for pattern t = 0 # hash value for txt h = 1 # The value of h would be "pow(d, M-1)% q" for i in xrange(M-1): h = (h * d)% q # Calculate the hash value of pattern and first window # of text for i in xrange(M): p = (d * p + ord(pat[i]))% q t = (d * t + ord(txt[i]))% q # Slide the pattern over text one by one for i in xrange(N-M + 1): # Check the hash values of current window of text and # pattern if the hash values match then only check # for characters on by one if p == t: # Check for characters one by one for j in xrange(M): if txt[i + j] != pat[j]: break j+= 1 # if p == t and pat[0...M-1] = txt[i, i + 1, ...i + M-1] if j == M: print "Pattern found at index " + str(i) # Calculate hash value for next window of text: Remove # leading digit, add trailing digit if i < N-M: t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q # We might get negative values of t, converting it to # positive if t < 0: t = t + q # Driver program to test the above functiontxt = "GEEKS FOR GEEKS"pat = "GEEK"q = 101 # A prime numbersearch(pat, txt, q) # This code is contributed by Bhavya Jain Pattern found at index 0 Pattern found at index 10 Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details! python searching-exercises Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python program to check whether a number is Prime or not Python Program for Binary Search (Recursive and Iterative) Python Program for Fibonacci numbers Iterate over characters of a string in Python Python Program for factorial of a number Python | Convert a list into a tuple Python | Check if a variable is string Python | Convert set into a list
[ { "code": null, "e": 26153, "s": 26125, "text": "\n30 Dec, 2020" }, { "code": null, "e": 26163, "s": 26153, "text": "Examples:" }, { "code": null, "e": 26421, "s": 26163, "text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12\n\n" }, { "code": null, "e": 26992, "s": 26421, "text": "The Naive String Matching algorithm slides the pattern one by one. After each slide, it one by one checks characters at the current shift and if all characters match then prints the match.Like the Naive Algorithm, Rabin-Karp algorithm also slides the pattern one by one. But unlike the Naive algorithm, Rabin Karp algorithm matches the hash value of the pattern with the hash value of current substring of text, and if the hash values match then only it starts matching individual characters. So Rabin Karp algorithm needs to calculate hash values for following strings." }, { "code": null, "e": 27053, "s": 26992, "text": "1) Pattern itself.2) All the substrings of text of length m." }, { "code": null, "e": 27060, "s": 27053, "text": "Python" }, { "code": "# Following program is the python implementation of# Rabin Karp Algorithm given in CLRS book # d is the number of characters in the input alphabetd = 256 # pat -> pattern# txt -> text# q -> A prime number def search(pat, txt, q): M = len(pat) N = len(txt) i = 0 j = 0 p = 0 # hash value for pattern t = 0 # hash value for txt h = 1 # The value of h would be \"pow(d, M-1)% q\" for i in xrange(M-1): h = (h * d)% q # Calculate the hash value of pattern and first window # of text for i in xrange(M): p = (d * p + ord(pat[i]))% q t = (d * t + ord(txt[i]))% q # Slide the pattern over text one by one for i in xrange(N-M + 1): # Check the hash values of current window of text and # pattern if the hash values match then only check # for characters on by one if p == t: # Check for characters one by one for j in xrange(M): if txt[i + j] != pat[j]: break j+= 1 # if p == t and pat[0...M-1] = txt[i, i + 1, ...i + M-1] if j == M: print \"Pattern found at index \" + str(i) # Calculate hash value for next window of text: Remove # leading digit, add trailing digit if i < N-M: t = (d*(t-ord(txt[i])*h) + ord(txt[i + M]))% q # We might get negative values of t, converting it to # positive if t < 0: t = t + q # Driver program to test the above functiontxt = \"GEEKS FOR GEEKS\"pat = \"GEEK\"q = 101 # A prime numbersearch(pat, txt, q) # This code is contributed by Bhavya Jain", "e": 28727, "s": 27060, "text": null }, { "code": null, "e": 28779, "s": 28727, "text": "Pattern found at index 0\nPattern found at index 10\n" }, { "code": null, "e": 28873, "s": 28779, "text": "Please refer complete article on Rabin-Karp Algorithm for Pattern Searching for more details!" }, { "code": null, "e": 28900, "s": 28873, "text": "python searching-exercises" }, { "code": null, "e": 28916, "s": 28900, "text": "Python Programs" }, { "code": null, "e": 29014, "s": 28916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29052, "s": 29014, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 29101, "s": 29052, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 29158, "s": 29101, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 29217, "s": 29158, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 29254, "s": 29217, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 29300, "s": 29254, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 29341, "s": 29300, "text": "Python Program for factorial of a number" }, { "code": null, "e": 29378, "s": 29341, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 29417, "s": 29378, "text": "Python | Check if a variable is string" } ]
DecimalFormat setMaximumFractionDigits() method in Java - GeeksforGeeks
01 Apr, 2019 The setMaximumFractionDigits() method is a built-in method of the java.text.DecimalFomrat class in Java and is used to set the maximum number of digits allowed in the fractional part of a number. The fractional part of a number is the part displayed after the decimal(.) symbol. Syntax: public void setMaximumFractionDigits(int newVal) Parameters: The function accepts a single parameter newVal which is the new value for the maximum number of fractional digits allowed to be set for this DecimalFormat instance. Return Value: The function does not returns any value. Below is the implementation of the above function: Program 1: // Java program to illustrate the// setMaximumFractionDigits() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); deciFormat.setMaximumFractionDigits(6); System.out.println(deciFormat.format(12.3456789)); }} 12.345679 Program 2: // Java program to illustrate the// setMaximumFractionDigits() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); deciFormat.setMaximumFractionDigits(1); System.out.println(deciFormat.format(12.3456789)); }} 12.3 Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int) Java-DecimalFormat Java-Functions Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java How to iterate any Map in Java ArrayList in Java Object Oriented Programming (OOPs) Concept in Java Multidimensional Arrays in Java Stack Class in Java LinkedList in Java Overriding in Java
[ { "code": null, "e": 24308, "s": 24280, "text": "\n01 Apr, 2019" }, { "code": null, "e": 24587, "s": 24308, "text": "The setMaximumFractionDigits() method is a built-in method of the java.text.DecimalFomrat class in Java and is used to set the maximum number of digits allowed in the fractional part of a number. The fractional part of a number is the part displayed after the decimal(.) symbol." }, { "code": null, "e": 24595, "s": 24587, "text": "Syntax:" }, { "code": null, "e": 24645, "s": 24595, "text": "public void setMaximumFractionDigits(int newVal)\n" }, { "code": null, "e": 24822, "s": 24645, "text": "Parameters: The function accepts a single parameter newVal which is the new value for the maximum number of fractional digits allowed to be set for this DecimalFormat instance." }, { "code": null, "e": 24877, "s": 24822, "text": "Return Value: The function does not returns any value." }, { "code": null, "e": 24928, "s": 24877, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 24939, "s": 24928, "text": "Program 1:" }, { "code": "// Java program to illustrate the// setMaximumFractionDigits() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); deciFormat.setMaximumFractionDigits(6); System.out.println(deciFormat.format(12.3456789)); }}", "e": 25414, "s": 24939, "text": null }, { "code": null, "e": 25425, "s": 25414, "text": "12.345679\n" }, { "code": null, "e": 25436, "s": 25425, "text": "Program 2:" }, { "code": "// Java program to illustrate the// setMaximumFractionDigits() method import java.text.DecimalFormat;import java.text.DecimalFormatSymbols;import java.util.Currency;import java.util.Locale; public class Main { public static void main(String[] args) { // Create the DecimalFormat Instance DecimalFormat deciFormat = new DecimalFormat(); deciFormat.setMaximumFractionDigits(1); System.out.println(deciFormat.format(12.3456789)); }}", "e": 25911, "s": 25436, "text": null }, { "code": null, "e": 25917, "s": 25911, "text": "12.3\n" }, { "code": null, "e": 26029, "s": 25917, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html#setMaximumFractionDigits(int)" }, { "code": null, "e": 26048, "s": 26029, "text": "Java-DecimalFormat" }, { "code": null, "e": 26063, "s": 26048, "text": "Java-Functions" }, { "code": null, "e": 26081, "s": 26063, "text": "Java-text package" }, { "code": null, "e": 26086, "s": 26081, "text": "Java" }, { "code": null, "e": 26091, "s": 26086, "text": "Java" }, { "code": null, "e": 26189, "s": 26091, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26198, "s": 26189, "text": "Comments" }, { "code": null, "e": 26211, "s": 26198, "text": "Old Comments" }, { "code": null, "e": 26243, "s": 26211, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 26273, "s": 26243, "text": "HashMap in Java with Examples" }, { "code": null, "e": 26292, "s": 26273, "text": "Interfaces in Java" }, { "code": null, "e": 26323, "s": 26292, "text": "How to iterate any Map in Java" }, { "code": null, "e": 26341, "s": 26323, "text": "ArrayList in Java" }, { "code": null, "e": 26392, "s": 26341, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 26424, "s": 26392, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 26444, "s": 26424, "text": "Stack Class in Java" }, { "code": null, "e": 26463, "s": 26444, "text": "LinkedList in Java" } ]
Graph Shortest Paths - GeeksforGeeks
19 Nov, 2018 * Time Comlexity of the Dijkstra’s algorithm is O(|V|^2 + E) * Time Comlexity of the Warshall’s algorithm is O(|V|^3) * DFS cannot be used for finding shortest paths * BFS can be used for unweighted graphs. Time Complexity for BFS is O(|E| + |V|) 1 1 1 s-----a-----b-----t \ / \ / \______/ 4 If we make following changes to Dijkstra, then it can be used to find the longest simple path, assume that the graph is acyclic. 1) Initialize all distances as minus infinite instead of plus infinite. 2) Modify the relax condition in Dijkstra's algorithm to update distance of an adjacent v of the currently considered vertex u only if "dist[u]+graph[u][v] > dist[v]". In shortest path algo, the sign is opposite. Given a directed graph where weight of every edge is same, we can efficiently find shortest path from a given source to destination using? Breadth First Traversal Dijkstra's Shortest Path Algorithm Neither Breadth First Traversal nor Dijkstra's algorithm can be used Depth First Search With BFS, we first find explore vertices at one edge distance, then all vertices at 2 edge distance, and so on. Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Coding Questions for Product Based Companies How to Replace Values in Column Based on Condition in Pandas? How to Fix: SyntaxError: positional argument follows keyword argument in Python C Program to read contents of Whole File How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? How to Replace Values in a List in Python? How to Select Data Between Two Dates and Times in SQL Server? Spring - REST Controller How to Read Text Files with Pandas? How to Calculate Moving Averages in Python?
[ { "code": null, "e": 27708, "s": 27680, "text": "\n19 Nov, 2018" }, { "code": null, "e": 27961, "s": 27708, "text": " * Time Comlexity of the Dijkstra’s algorithm is O(|V|^2 + E) \n * Time Comlexity of the Warshall’s algorithm is O(|V|^3)\n * DFS cannot be used for finding shortest paths\n * BFS can be used for unweighted graphs. Time Complexity for BFS is O(|E| + |V|)" }, { "code": null, "e": 28058, "s": 27961, "text": "\n 1 1 1\ns-----a-----b-----t\n \\ /\n \\ /\n \\______/\n 4" }, { "code": null, "e": 28485, "s": 28058, "text": "If we make following changes to Dijkstra, then it can be used to find \nthe longest simple path, assume that the graph is acyclic.\n\n1) Initialize all distances as minus infinite instead of plus infinite.\n\n2) Modify the relax condition in Dijkstra's algorithm to update distance\n of an adjacent v of the currently considered vertex u only\n if \"dist[u]+graph[u][v] > dist[v]\". In shortest path algo, \n the sign is opposite. " }, { "code": null, "e": 28625, "s": 28485, "text": "Given a directed graph where weight of every edge is same, we can efficiently find shortest path from a given source to destination using? " }, { "code": null, "e": 28649, "s": 28625, "text": "Breadth First Traversal" }, { "code": null, "e": 28684, "s": 28649, "text": "Dijkstra's Shortest Path Algorithm" }, { "code": null, "e": 28753, "s": 28684, "text": "Neither Breadth First Traversal nor Dijkstra's algorithm can be used" }, { "code": null, "e": 28772, "s": 28753, "text": "Depth First Search" }, { "code": null, "e": 28885, "s": 28772, "text": "With BFS, we first find explore vertices at one edge distance, then all vertices at 2 edge distance, and so on. " }, { "code": null, "e": 28983, "s": 28885, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 29036, "s": 28983, "text": "Must Do Coding Questions for Product Based Companies" }, { "code": null, "e": 29098, "s": 29036, "text": "How to Replace Values in Column Based on Condition in Pandas?" }, { "code": null, "e": 29178, "s": 29098, "text": "How to Fix: SyntaxError: positional argument follows keyword argument in Python" }, { "code": null, "e": 29219, "s": 29178, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 29299, "s": 29219, "text": "How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?" }, { "code": null, "e": 29342, "s": 29299, "text": "How to Replace Values in a List in Python?" }, { "code": null, "e": 29404, "s": 29342, "text": "How to Select Data Between Two Dates and Times in SQL Server?" }, { "code": null, "e": 29429, "s": 29404, "text": "Spring - REST Controller" }, { "code": null, "e": 29465, "s": 29429, "text": "How to Read Text Files with Pandas?" } ]
Monty Hall Problem using Python. We have all heard the probability brain... | by Siddhartha Pachhai | Towards Data Science
We have all heard the probability brain teaser for the three door game show. Each contestant guesses whats behind the door, the show host reveals one of the three doors that didn’t have the prize and gives an opportunity to the contestant to switch doors. It is hypothesized and in fact proven using conditional probability that switching doors increases your chances to an amazing 66%. But wait hold on, when I entered the game and had no clue which door had the prize i had a 33% chance of winning and when the host revealed one of the doors with no prizes, doesn’t that mean two doors remain and its a 50–50 chance of winning? Why should I switch? Well if you are the type of person who doesn’t believe what you hear on TV or what you read in a fun facts column of a magazine, but have curiosity in mathematical proofs, here is your answer. Below are the initial probabilities when you walk in to the game show. Now comes the tricky part and this is where the mathematics starts getting very confusing. Lets say the contestant chooses the 1st door, now what is the probability that the host will open Door 3, given that the prize is behind either door 1,2 or 3. This is a important concept to understand as this is used later on to derive the probabilities. The first probability(left) answers the question: if you chose door 1, and the prize was behind 1, what is the probability that the host will reveal door 3? The answer is 50%, the host can either open door 3 or door 2 because both of them don’t have the prizes. But the key concept here is that the probability exists because you started with door 1. If you choose door 1, and the prize is in door 2(middle), It is highly likely that the host will reveal door 3, because door 1 was already chosen by the contestant and door 2 has the prize so the host can only open the remaining door with no prize which is 3. Now if the prize was in door 3, there is no chance that the host will open door 3, after the contestant chooses door 1. Like the previous scenario the host will always open door 2, when this is the case. So given we start with door 1, the probability of opening door 3 if door 3 has the prize is 0. Now that we have understood the reasoning, lets suppose that in this example the host opens door 3. Door 3 doesn’t have the prize, now how sure can we be that door 2 has the prize? The probabilities are based on Bayes theorem. So far our logic and deduction have created information that we are going to plug in to this equation to obtain probabilities of a conditioned event. The main concept that should be understood here is the probability statement in the far left. It calculates probability of success for door 2 given that door 3 is revealed as not having prizes and our initial choice was door 1. So the chances of success are 2/3 when we switch! The alternative; if we had remained with door 1 in this scenario, the chances of winning would be as follows. The same probabilities should follow regardless of what door you start from. The conditions are created in such a way that the given outcomes are always produced. Now for the fun part. Lets see if this really is true! %matplotlib inlineimport matplotlibimport numpy as npimport matplotlib.pyplot as pltfrom time import time as TTfrom random import choice as chimport numpy as npac = []tc = []N = []st = TT()for M in range(1,10000): #Outer loop from 1 to 10000 st1 = TT() score = [] runs = 0 cards = [1,2,3] for K in range(1,M): # sub loop that simulates 1 to M(outerloop) games aset = [] host = cards.copy() hbk = ch(host) #Randomly choose as answer which host knows aset.append(hbk) #print("The host knows the answer",hbk) player = cards.copy() px = ch(player) # Contestanrs random guess aset.append(px) #print ("Players first choice",px) chance = 0 for i in host: # The computation....host will eliminate P(X|DOOR) = 0 if i not in aset: chance = i #print ("The elimination",chance) #print (player) player.pop(player.index(chance)) player.pop(player.index(px)) #print ("final answe",player) if player[0] == hbk: score.append(1) else: score.append(0) runs = K #print ("\n\n") ac.append(np.mean(score)) N.append(M) en1 = TT() tc.append(en1-st1)en = TT() print ("Total time for Loop ", en - st ) The above code simulates the gameshow 10,000 times, where each itteration is a loop of increasing amounts of games. This process can be done in different ways, but the outcome should be the same but it was interesting to use the loop described above to get a variation of the number of games being played, which does effect the final outcome. The main logic in this program is that, after contestant picks the first door, the host will eliminate the door that was not picked by the contestant or the door that was the right answer. If the contestants first guess was the correct guess, the door chosen to reveal is a random process. But the way my computation works it will be the last element of the list(1,2,3) given the element is not the correct answer. After doing this, for simulation purposes the contestant will always switch his answers after revealing. So thus going through this simulation we have the following results. The X-Axis is the number of sub games that were played. The Y-Axis is the average sub-games won. Between 0–100 sub-games, you can see there is a lot of variation but after the 2000 mark and close to 10,000 the average number of sub-games won converges to around 64%-68%(maximum 70). Which supports our initial reasoning of that was derived through Bayes Theorem. This theory might scale differently if we had more than 3 options or less.
[ { "code": null, "e": 1016, "s": 172, "text": "We have all heard the probability brain teaser for the three door game show. Each contestant guesses whats behind the door, the show host reveals one of the three doors that didn’t have the prize and gives an opportunity to the contestant to switch doors. It is hypothesized and in fact proven using conditional probability that switching doors increases your chances to an amazing 66%. But wait hold on, when I entered the game and had no clue which door had the prize i had a 33% chance of winning and when the host revealed one of the doors with no prizes, doesn’t that mean two doors remain and its a 50–50 chance of winning? Why should I switch? Well if you are the type of person who doesn’t believe what you hear on TV or what you read in a fun facts column of a magazine, but have curiosity in mathematical proofs, here is your answer." }, { "code": null, "e": 1087, "s": 1016, "text": "Below are the initial probabilities when you walk in to the game show." }, { "code": null, "e": 1433, "s": 1087, "text": "Now comes the tricky part and this is where the mathematics starts getting very confusing. Lets say the contestant chooses the 1st door, now what is the probability that the host will open Door 3, given that the prize is behind either door 1,2 or 3. This is a important concept to understand as this is used later on to derive the probabilities." }, { "code": null, "e": 1784, "s": 1433, "text": "The first probability(left) answers the question: if you chose door 1, and the prize was behind 1, what is the probability that the host will reveal door 3? The answer is 50%, the host can either open door 3 or door 2 because both of them don’t have the prizes. But the key concept here is that the probability exists because you started with door 1." }, { "code": null, "e": 2044, "s": 1784, "text": "If you choose door 1, and the prize is in door 2(middle), It is highly likely that the host will reveal door 3, because door 1 was already chosen by the contestant and door 2 has the prize so the host can only open the remaining door with no prize which is 3." }, { "code": null, "e": 2343, "s": 2044, "text": "Now if the prize was in door 3, there is no chance that the host will open door 3, after the contestant chooses door 1. Like the previous scenario the host will always open door 2, when this is the case. So given we start with door 1, the probability of opening door 3 if door 3 has the prize is 0." }, { "code": null, "e": 2524, "s": 2343, "text": "Now that we have understood the reasoning, lets suppose that in this example the host opens door 3. Door 3 doesn’t have the prize, now how sure can we be that door 2 has the prize?" }, { "code": null, "e": 2720, "s": 2524, "text": "The probabilities are based on Bayes theorem. So far our logic and deduction have created information that we are going to plug in to this equation to obtain probabilities of a conditioned event." }, { "code": null, "e": 3108, "s": 2720, "text": "The main concept that should be understood here is the probability statement in the far left. It calculates probability of success for door 2 given that door 3 is revealed as not having prizes and our initial choice was door 1. So the chances of success are 2/3 when we switch! The alternative; if we had remained with door 1 in this scenario, the chances of winning would be as follows." }, { "code": null, "e": 3271, "s": 3108, "text": "The same probabilities should follow regardless of what door you start from. The conditions are created in such a way that the given outcomes are always produced." }, { "code": null, "e": 3326, "s": 3271, "text": "Now for the fun part. Lets see if this really is true!" }, { "code": null, "e": 4621, "s": 3326, "text": "%matplotlib inlineimport matplotlibimport numpy as npimport matplotlib.pyplot as pltfrom time import time as TTfrom random import choice as chimport numpy as npac = []tc = []N = []st = TT()for M in range(1,10000): #Outer loop from 1 to 10000 st1 = TT() score = [] runs = 0 cards = [1,2,3] for K in range(1,M): # sub loop that simulates 1 to M(outerloop) games aset = [] host = cards.copy() hbk = ch(host) #Randomly choose as answer which host knows aset.append(hbk) #print(\"The host knows the answer\",hbk) player = cards.copy() px = ch(player) # Contestanrs random guess aset.append(px) #print (\"Players first choice\",px) chance = 0 for i in host: # The computation....host will eliminate P(X|DOOR) = 0 if i not in aset: chance = i #print (\"The elimination\",chance) #print (player) player.pop(player.index(chance)) player.pop(player.index(px)) #print (\"final answe\",player) if player[0] == hbk: score.append(1) else: score.append(0) runs = K #print (\"\\n\\n\") ac.append(np.mean(score)) N.append(M) en1 = TT() tc.append(en1-st1)en = TT() print (\"Total time for Loop \", en - st )" }, { "code": null, "e": 4964, "s": 4621, "text": "The above code simulates the gameshow 10,000 times, where each itteration is a loop of increasing amounts of games. This process can be done in different ways, but the outcome should be the same but it was interesting to use the loop described above to get a variation of the number of games being played, which does effect the final outcome." }, { "code": null, "e": 5553, "s": 4964, "text": "The main logic in this program is that, after contestant picks the first door, the host will eliminate the door that was not picked by the contestant or the door that was the right answer. If the contestants first guess was the correct guess, the door chosen to reveal is a random process. But the way my computation works it will be the last element of the list(1,2,3) given the element is not the correct answer. After doing this, for simulation purposes the contestant will always switch his answers after revealing. So thus going through this simulation we have the following results." }, { "code": null, "e": 5916, "s": 5553, "text": "The X-Axis is the number of sub games that were played. The Y-Axis is the average sub-games won. Between 0–100 sub-games, you can see there is a lot of variation but after the 2000 mark and close to 10,000 the average number of sub-games won converges to around 64%-68%(maximum 70). Which supports our initial reasoning of that was derived through Bayes Theorem." } ]
DAX Date & Time - YEAR function
Returns the year of a date as a four-digit integer in the range 1900-9999. YEAR (<date>) date A date in datetime or text format, containing the year you want to find. An integer in the range 1900-9999. DAX uses datetime data type to work with dates and times. YEAR function takes the parameter date in one of the following ways − By using the DATE function. As a result of other DAX formulas or DAX functions. As an accepted text representation of date. The function uses the locale and date time settings of the client computer to understand the text value in order to perform the conversion. For example, If the current date/time settings represent dates in the format of Month/Day/Year, then the string "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016. If the current date/time settings represent dates in the format of Month/Day/Year, then the string "1/8/2016" is understood as a datetime value equivalent to 8th January, 2016. If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016. If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016. If the format of the string is incompatible with the current locale settings, YEAR function might return an error. For example, if your locale defines dates to be formatted as month/day/year, and the date is provided as day/month/year, then 25/1/2009 will not be interpreted as January 25th of 2009 but as an invalid date. = YEAR (DATE (2016,9,15)) returns 2016. = YEAR (TODAY ()) returns 2016 if TODAY () returns 12/16/2016 12:00:00 AM. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2076, "s": 2001, "text": "Returns the year of a date as a four-digit integer in the range 1900-9999." }, { "code": null, "e": 2092, "s": 2076, "text": "YEAR (<date>) \n" }, { "code": null, "e": 2097, "s": 2092, "text": "date" }, { "code": null, "e": 2170, "s": 2097, "text": "A date in datetime or text format, containing the year you want to find." }, { "code": null, "e": 2205, "s": 2170, "text": "An integer in the range 1900-9999." }, { "code": null, "e": 2263, "s": 2205, "text": "DAX uses datetime data type to work with dates and times." }, { "code": null, "e": 2333, "s": 2263, "text": "YEAR function takes the parameter date in one of the following ways −" }, { "code": null, "e": 2361, "s": 2333, "text": "By using the DATE function." }, { "code": null, "e": 2413, "s": 2361, "text": "As a result of other DAX formulas or DAX functions." }, { "code": null, "e": 2457, "s": 2413, "text": "As an accepted text representation of date." }, { "code": null, "e": 2610, "s": 2457, "text": "The function uses the locale and date time settings of the client computer to understand the text value in order to perform the conversion. For example," }, { "code": null, "e": 2787, "s": 2610, "text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016." }, { "code": null, "e": 2964, "s": 2787, "text": "If the current date/time settings represent dates in the format of Month/Day/Year, then the string \"1/8/2016\" is understood as a datetime value equivalent to 8th January, 2016." }, { "code": null, "e": 3135, "s": 2964, "text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016." }, { "code": null, "e": 3306, "s": 3135, "text": "If the current date/time settings represent dates in the format of Day/Month/Year, the same string would be understood as a datetime value equivalent to 1st August, 2016." }, { "code": null, "e": 3629, "s": 3306, "text": "If the format of the string is incompatible with the current locale settings, YEAR function might return an error. For example, if your locale defines dates to be formatted as month/day/year, and the date is provided as day/month/year, then 25/1/2009 will not be interpreted as January 25th of 2009 but as an invalid date." }, { "code": null, "e": 3746, "s": 3629, "text": "= YEAR (DATE (2016,9,15)) returns 2016. \n= YEAR (TODAY ()) returns 2016 if TODAY () returns 12/16/2016 12:00:00 AM. " }, { "code": null, "e": 3781, "s": 3746, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3795, "s": 3781, "text": " Abhay Gadiya" }, { "code": null, "e": 3828, "s": 3795, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3842, "s": 3828, "text": " Randy Minder" }, { "code": null, "e": 3877, "s": 3842, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3891, "s": 3877, "text": " Randy Minder" }, { "code": null, "e": 3898, "s": 3891, "text": " Print" }, { "code": null, "e": 3909, "s": 3898, "text": " Add Notes" } ]
An Introduction to Perceptron Algorithm | by Yang S | Towards Data Science
This blog will cover following questions and topics 1. What is Perceptron? 2. Stochastic Gradient Descent for Perceptron 3. Implementation in Python 1. What is Perceptron? Perceptron set the foundations for Neural Network models in 1980s. The algorithm was developed by Frank Rosenblatt and was encapsulated in the paper “Principles of Neuro-dynamics: Perceptrons and the Theory of Brain Mechanisms” published in 1962. At that time, Rosenblatt’s work was criticized by Marvin Minksy and Seymour Papert, arguing that neural networks were flawed and could only solve linear separation problem. However, such limitation only occurs in the single layer neural network. Perceptron can be used to solve two-class classification problem. The generalized form of algorithm can be written as: Nonlinear activation sign function is: While logistic regression is targeting on the probability of events happen or not, so the range of target value is [0, 1]. Perceptron uses more convenient target values t=+1 for first class and t=-1 for second class. Therefore, the algorithm does not provide probabilistic outputs, nor does it handle K>2 classification problem. Another limitation arises from the fact that the algorithm can only handle linear combinations of fixed basis function. 2. Stochastic Gradient Descent for Perceptron According to previous two formulas, if a record is classified correctly, then: Otherwise, Therefore, to minimize cost function for Perceptron, we can write: M means the set of misclassified records. By taking partial derivative, we can get gradient of cost function: Unlike logistic regression, which can apply Batch Gradient Descent, Mini-Batch Gradient Descent and Stochastic Gradient Descent to calculate parameters, Perceptron can only use Stochastic Gradient Descent. We need to initialize parameters w and b, and then randomly select one misclassified record and use Stochastic Gradient Descent to iteratively update parameters w and b until all records are classified correctly: Note that learning rate a ranges from 0 to 1. For example, we have 3 records, Y1 = (3, 3), Y2 = (4, 3), Y3 = (1, 1). Y1 and Y2 are labeled as +1 and Y3 is labeled as -1. Given that initial parameters are all 0. Therefore, all points will be classified as class 1. Stochastic Gradient Descent cycles through all training data. In the initial round, by applying first two formulas, Y1 and Y2 can be classified correctly. However, Y3 will be misclassified. Assuming learning rate equals to 1, by applying gradient descent shown above, we can get: Then linear classifier can be written as: That is 1 round of gradient descent iteration. Table above shows the whole procedure of Stochastic Gradient Descent for Perceptron. If a record is classified correctly, then weight vector w and b remain unchanged; otherwise, we add vector x onto current weight vector when y=1 and minus vector x from current weight vector w when y=-1. Note that last 3 columns are predicted value and misclassified records are highlighted in red. If we carry out gradient descent over and over, in round 7, all 3 records are labeled correctly. Then the algorithm will stop. Final formula for linear classifier is: Note that there is always converge issue with this algorithm. When the data is separable, there are many solutions, and which solution is chosen depends on the starting values. When the data is not separable, the algorithm will not converge. For details, please see corresponding paragraph in reference below. 3. Implementation in Python from sklearn import datasetsimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.lines as mlinesnp.random.seed(10)# Load datairis=datasets.load_iris()X = iris.data[0:99,:2]y = iris.target[0:99] First, load the Iris data. # Plot figureplt.plot(X[:50, 0], X[:50, 1], 'bo', color='blue', label='0')plt.plot(X[50:99, 0], X[50:99, 1], 'bo', color='orange', label='1')plt.xlabel('sepal length')plt.ylabel('sepal width')plt.legend() Then visualize data # Update y into -1 and 1y=np.array([1 if i==1 else -1 for i in y]) Update y=0 to y=-1 ################################## Gradient Descent################################## Initialize parametersw=np.ones((X.shape[1],1));b=1;learning_rate=0.1;Round=0;All_Correct=False;# Start Gradient Descentwhile not All_Correct: misclassified_count=0 for i in range(X.shape[0]): XX=X[i,] yy=y[i] if yy * (np.dot(w.T,XX.T)+b)<0: w+=learning_rate * np.dot(XX,yy).reshape(2,1) b+=learning_rate * yy misclassified_count +=1 if misclassified_count==0: All_Correct=True else: All_Correct=False Round += 1 print(Round)print(w)print(b) After applying Stochastic Gradient Descent, we get w=(7.9, -10.07) and b=-12.39 x_points = np.linspace(4,7,10)y_ = -(w[0]*x_points + b)/w[1]plt.plot(x_points, y_)plt.plot(X[:50, 0], X[:50, 1], 'bo', color='blue', label='0')plt.plot(X[50:99, 0], X[50:99, 1], 'bo', color='orange', label='1')plt.xlabel('sepal length')plt.ylabel('sepal width')plt.legend() Figure above shows the final result of Perceptron. We can see that the linear classifier (blue line) can classify all training dataset correctly. In this case, the iris dataset only contains 2 dimensions, so the decision boundary is a line. In the case when the dataset contains 3 or more dimensions, the decision boundary will be a hyperplane. Conclusion In this blog, I explain the theory and mathematics behind Perceptron, compare this algorithm with logistic regression, and finally implement the algorithm in Python. Hope after reading this blog, you can have a better understanding of this algorithm. If you have interests in other blogs, please click on the following link: medium.com Reference [1] Christopher M. Bishop, (2009), Pattern Recognition and Machine Leaning [2] Trevor Hastie, Robert Tibshirani, Jerome Friedman, (2008), The Elements of Statistical Learning
[ { "code": null, "e": 224, "s": 172, "text": "This blog will cover following questions and topics" }, { "code": null, "e": 247, "s": 224, "text": "1. What is Perceptron?" }, { "code": null, "e": 293, "s": 247, "text": "2. Stochastic Gradient Descent for Perceptron" }, { "code": null, "e": 321, "s": 293, "text": "3. Implementation in Python" }, { "code": null, "e": 344, "s": 321, "text": "1. What is Perceptron?" }, { "code": null, "e": 837, "s": 344, "text": "Perceptron set the foundations for Neural Network models in 1980s. The algorithm was developed by Frank Rosenblatt and was encapsulated in the paper “Principles of Neuro-dynamics: Perceptrons and the Theory of Brain Mechanisms” published in 1962. At that time, Rosenblatt’s work was criticized by Marvin Minksy and Seymour Papert, arguing that neural networks were flawed and could only solve linear separation problem. However, such limitation only occurs in the single layer neural network." }, { "code": null, "e": 956, "s": 837, "text": "Perceptron can be used to solve two-class classification problem. The generalized form of algorithm can be written as:" }, { "code": null, "e": 995, "s": 956, "text": "Nonlinear activation sign function is:" }, { "code": null, "e": 1444, "s": 995, "text": "While logistic regression is targeting on the probability of events happen or not, so the range of target value is [0, 1]. Perceptron uses more convenient target values t=+1 for first class and t=-1 for second class. Therefore, the algorithm does not provide probabilistic outputs, nor does it handle K>2 classification problem. Another limitation arises from the fact that the algorithm can only handle linear combinations of fixed basis function." }, { "code": null, "e": 1490, "s": 1444, "text": "2. Stochastic Gradient Descent for Perceptron" }, { "code": null, "e": 1569, "s": 1490, "text": "According to previous two formulas, if a record is classified correctly, then:" }, { "code": null, "e": 1580, "s": 1569, "text": "Otherwise," }, { "code": null, "e": 1647, "s": 1580, "text": "Therefore, to minimize cost function for Perceptron, we can write:" }, { "code": null, "e": 1689, "s": 1647, "text": "M means the set of misclassified records." }, { "code": null, "e": 1757, "s": 1689, "text": "By taking partial derivative, we can get gradient of cost function:" }, { "code": null, "e": 2176, "s": 1757, "text": "Unlike logistic regression, which can apply Batch Gradient Descent, Mini-Batch Gradient Descent and Stochastic Gradient Descent to calculate parameters, Perceptron can only use Stochastic Gradient Descent. We need to initialize parameters w and b, and then randomly select one misclassified record and use Stochastic Gradient Descent to iteratively update parameters w and b until all records are classified correctly:" }, { "code": null, "e": 2222, "s": 2176, "text": "Note that learning rate a ranges from 0 to 1." }, { "code": null, "e": 2440, "s": 2222, "text": "For example, we have 3 records, Y1 = (3, 3), Y2 = (4, 3), Y3 = (1, 1). Y1 and Y2 are labeled as +1 and Y3 is labeled as -1. Given that initial parameters are all 0. Therefore, all points will be classified as class 1." }, { "code": null, "e": 2720, "s": 2440, "text": "Stochastic Gradient Descent cycles through all training data. In the initial round, by applying first two formulas, Y1 and Y2 can be classified correctly. However, Y3 will be misclassified. Assuming learning rate equals to 1, by applying gradient descent shown above, we can get:" }, { "code": null, "e": 2762, "s": 2720, "text": "Then linear classifier can be written as:" }, { "code": null, "e": 2809, "s": 2762, "text": "That is 1 round of gradient descent iteration." }, { "code": null, "e": 3360, "s": 2809, "text": "Table above shows the whole procedure of Stochastic Gradient Descent for Perceptron. If a record is classified correctly, then weight vector w and b remain unchanged; otherwise, we add vector x onto current weight vector when y=1 and minus vector x from current weight vector w when y=-1. Note that last 3 columns are predicted value and misclassified records are highlighted in red. If we carry out gradient descent over and over, in round 7, all 3 records are labeled correctly. Then the algorithm will stop. Final formula for linear classifier is:" }, { "code": null, "e": 3670, "s": 3360, "text": "Note that there is always converge issue with this algorithm. When the data is separable, there are many solutions, and which solution is chosen depends on the starting values. When the data is not separable, the algorithm will not converge. For details, please see corresponding paragraph in reference below." }, { "code": null, "e": 3698, "s": 3670, "text": "3. Implementation in Python" }, { "code": null, "e": 3925, "s": 3698, "text": "from sklearn import datasetsimport numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport matplotlib.lines as mlinesnp.random.seed(10)# Load datairis=datasets.load_iris()X = iris.data[0:99,:2]y = iris.target[0:99]" }, { "code": null, "e": 3952, "s": 3925, "text": "First, load the Iris data." }, { "code": null, "e": 4157, "s": 3952, "text": "# Plot figureplt.plot(X[:50, 0], X[:50, 1], 'bo', color='blue', label='0')plt.plot(X[50:99, 0], X[50:99, 1], 'bo', color='orange', label='1')plt.xlabel('sepal length')plt.ylabel('sepal width')plt.legend()" }, { "code": null, "e": 4177, "s": 4157, "text": "Then visualize data" }, { "code": null, "e": 4244, "s": 4177, "text": "# Update y into -1 and 1y=np.array([1 if i==1 else -1 for i in y])" }, { "code": null, "e": 4263, "s": 4244, "text": "Update y=0 to y=-1" }, { "code": null, "e": 4876, "s": 4263, "text": "################################## Gradient Descent################################## Initialize parametersw=np.ones((X.shape[1],1));b=1;learning_rate=0.1;Round=0;All_Correct=False;# Start Gradient Descentwhile not All_Correct: misclassified_count=0 for i in range(X.shape[0]): XX=X[i,] yy=y[i] if yy * (np.dot(w.T,XX.T)+b)<0: w+=learning_rate * np.dot(XX,yy).reshape(2,1) b+=learning_rate * yy misclassified_count +=1 if misclassified_count==0: All_Correct=True else: All_Correct=False Round += 1 print(Round)print(w)print(b)" }, { "code": null, "e": 4956, "s": 4876, "text": "After applying Stochastic Gradient Descent, we get w=(7.9, -10.07) and b=-12.39" }, { "code": null, "e": 5230, "s": 4956, "text": "x_points = np.linspace(4,7,10)y_ = -(w[0]*x_points + b)/w[1]plt.plot(x_points, y_)plt.plot(X[:50, 0], X[:50, 1], 'bo', color='blue', label='0')plt.plot(X[50:99, 0], X[50:99, 1], 'bo', color='orange', label='1')plt.xlabel('sepal length')plt.ylabel('sepal width')plt.legend()" }, { "code": null, "e": 5575, "s": 5230, "text": "Figure above shows the final result of Perceptron. We can see that the linear classifier (blue line) can classify all training dataset correctly. In this case, the iris dataset only contains 2 dimensions, so the decision boundary is a line. In the case when the dataset contains 3 or more dimensions, the decision boundary will be a hyperplane." }, { "code": null, "e": 5586, "s": 5575, "text": "Conclusion" }, { "code": null, "e": 5911, "s": 5586, "text": "In this blog, I explain the theory and mathematics behind Perceptron, compare this algorithm with logistic regression, and finally implement the algorithm in Python. Hope after reading this blog, you can have a better understanding of this algorithm. If you have interests in other blogs, please click on the following link:" }, { "code": null, "e": 5922, "s": 5911, "text": "medium.com" }, { "code": null, "e": 5932, "s": 5922, "text": "Reference" }, { "code": null, "e": 6007, "s": 5932, "text": "[1] Christopher M. Bishop, (2009), Pattern Recognition and Machine Leaning" } ]
Extract properties from an object in JavaScript
We have to write a JavaScript function, say extract() that extracts properties from an object to another object and then deletes them from the original object. For example − If obj1 and obj2 are two objects, then obj1 = {color:"red", age:"23", name:"cindy"} obj2 = extract(obj1, ["color","name"]) After passing through the extract function, they should become like − obj1 = { age:23 } obj2 = {color:"red", name:"cindy"} Therefore, let’s write the code for this function − const obj = { name: "Rahul", job: "Software Engineer", age: 23, city: "Mumbai", hobby: "Reading books" }; const extract = (obj, ...keys) => { const newObject = Object.assign({}); Object.keys(obj).forEach((key) => { if(keys.includes(key)){ newObject[key] = obj[key]; delete obj[key]; }; }); return newObject; }; console.log(extract(obj, 'name', 'job', 'hobby')); console.log(obj); The output in the console will be − { name: 'Rahul', job: 'Software Engineer', hobby: 'Reading books' } { age: 23, city: 'Mumbai' }
[ { "code": null, "e": 1222, "s": 1062, "text": "We have to write a JavaScript function, say extract() that extracts properties from an object to\nanother object and then deletes them from the original object." }, { "code": null, "e": 1236, "s": 1222, "text": "For example −" }, { "code": null, "e": 1275, "s": 1236, "text": "If obj1 and obj2 are two objects, then" }, { "code": null, "e": 1359, "s": 1275, "text": "obj1 = {color:\"red\", age:\"23\", name:\"cindy\"}\nobj2 = extract(obj1, [\"color\",\"name\"])" }, { "code": null, "e": 1429, "s": 1359, "text": "After passing through the extract function, they should become like −" }, { "code": null, "e": 1482, "s": 1429, "text": "obj1 = { age:23 }\nobj2 = {color:\"red\", name:\"cindy\"}" }, { "code": null, "e": 1534, "s": 1482, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 1971, "s": 1534, "text": "const obj = {\n name: \"Rahul\",\n job: \"Software Engineer\",\n age: 23,\n city: \"Mumbai\",\n hobby: \"Reading books\"\n};\nconst extract = (obj, ...keys) => {\n const newObject = Object.assign({});\n Object.keys(obj).forEach((key) => {\n if(keys.includes(key)){\n newObject[key] = obj[key];\n delete obj[key];\n };\n });\n return newObject;\n};\nconsole.log(extract(obj, 'name', 'job', 'hobby'));\nconsole.log(obj);" }, { "code": null, "e": 2007, "s": 1971, "text": "The output in the console will be −" }, { "code": null, "e": 2103, "s": 2007, "text": "{ name: 'Rahul', job: 'Software Engineer', hobby: 'Reading books' }\n{ age: 23, city: 'Mumbai' }" } ]
apropos command in Linux with Examples - GeeksforGeeks
17 Jul, 2019 Linux/Unix comes with a huge number of commands and thus it become quite difficult sometimes to remember each and every command. apropos command becomes useful in such cases. apropos command helps the user when they don’t remember the exact command but knows a few keywords related to the command that define its uses or functionality. It searches the Linux man page with the help of the keyword provided by the user to find the command and its functions. Syntax: apropos [OPTION..] KEYWORD... Example 1: Suppose you don’t know how to compress a file then you could type the following command in terminal and it will show all the related command and its short description or functionality. Input: After executing the above command you will observe a bunch of commands is listed on the terminal that deals with not only how to compress a file but also how to expand a compressed file, search a compressed file, comparing a compressed file etc. Output: Example 2: apropos also support multiple keywords if given as an argument i.e. we can also provide more than one keyword for a better search. Thus, if two keywords are provided the apropos command will display all the command’s list which contains either the first keyword in its man page description or the second keyword. Input 1 (With one keyword):Output: Output: Input 2 (With multiple keyword):Output: Output: Options: -d: This option is used to emit debugging messages. When this option is used then terminal returns man directories, global path, path directory, warnings, etc. of each command which is related to the search keyword. -v: This option is used to print verbose warning messages. -e, –exact: This option is used to search each keyword for exact match. If no option is used, the apropos command returns list of all the command whose description in the man page description matches with the keyword or which are somehow related to the keyword given in the argument. However, when the -e option is used, the apropos only returns the command whose description exactly matches with the keyword. -w, –wildcard: This option is used when the keyword(s) contain wildcards. apropos will independently search the page name and the description matching against the keyword(s).All the command related to sudo are listed when sudo is given as a wildcard. All the command related to sudo are listed when sudo is given as a wildcard. -a, –and: This option is used when we want all the keywords to match. It returns nothing if any one of the keywords supplied has no matching in the man page or description. In the below input, two keywords have been given and only two commands are displayed in the result since there is only one command that contains both the keyword. -l, –long: By default, the output is trimmed to the terminal width. This option becomes handy when we don’t want the result to be truncated. -C: This option is used when we don’t want to use the default(/manpath) but user configuration file. -L: Define the locale for this search. -m, –systems: This option use manual pages from other systems. This option is helpful when we want to search the man page description of other accessible operating system. -M, –manpath: Set search path for manual pages to PATH rather than the default $MANPATH. -s, –sections, –section: This option is used when we want to search only particular sections (colon-separated) that are given in the argument. -?, –help: This option displays the help list. -V, –version: Used to print program version. -r, –regex: This option interpret each keyword as a regex(regular expression). The keyword will be independently matched against the page name and description. Shivam_k Linux-basic-commands linux-command Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples UDP Server-Client implementation in C Conditional Statements | Shell Script Cat command in Linux with examples Tail command in Linux with examples touch command in Linux with Examples Mutex lock for Linux Thread Synchronization echo command in Linux with Examples
[ { "code": null, "e": 24004, "s": 23976, "text": "\n17 Jul, 2019" }, { "code": null, "e": 24460, "s": 24004, "text": "Linux/Unix comes with a huge number of commands and thus it become quite difficult sometimes to remember each and every command. apropos command becomes useful in such cases. apropos command helps the user when they don’t remember the exact command but knows a few keywords related to the command that define its uses or functionality. It searches the Linux man page with the help of the keyword provided by the user to find the command and its functions." }, { "code": null, "e": 24468, "s": 24460, "text": "Syntax:" }, { "code": null, "e": 24498, "s": 24468, "text": "apropos [OPTION..] KEYWORD..." }, { "code": null, "e": 24694, "s": 24498, "text": "Example 1: Suppose you don’t know how to compress a file then you could type the following command in terminal and it will show all the related command and its short description or functionality." }, { "code": null, "e": 24701, "s": 24694, "text": "Input:" }, { "code": null, "e": 24947, "s": 24701, "text": "After executing the above command you will observe a bunch of commands is listed on the terminal that deals with not only how to compress a file but also how to expand a compressed file, search a compressed file, comparing a compressed file etc." }, { "code": null, "e": 24955, "s": 24947, "text": "Output:" }, { "code": null, "e": 25279, "s": 24955, "text": "Example 2: apropos also support multiple keywords if given as an argument i.e. we can also provide more than one keyword for a better search. Thus, if two keywords are provided the apropos command will display all the command’s list which contains either the first keyword in its man page description or the second keyword." }, { "code": null, "e": 25314, "s": 25279, "text": "Input 1 (With one keyword):Output:" }, { "code": null, "e": 25322, "s": 25314, "text": "Output:" }, { "code": null, "e": 25362, "s": 25322, "text": "Input 2 (With multiple keyword):Output:" }, { "code": null, "e": 25370, "s": 25362, "text": "Output:" }, { "code": null, "e": 25379, "s": 25370, "text": "Options:" }, { "code": null, "e": 25595, "s": 25379, "text": "-d: This option is used to emit debugging messages. When this option is used then terminal returns man directories, global path, path directory, warnings, etc. of each command which is related to the search keyword." }, { "code": null, "e": 25654, "s": 25595, "text": "-v: This option is used to print verbose warning messages." }, { "code": null, "e": 26064, "s": 25654, "text": "-e, –exact: This option is used to search each keyword for exact match. If no option is used, the apropos command returns list of all the command whose description in the man page description matches with the keyword or which are somehow related to the keyword given in the argument. However, when the -e option is used, the apropos only returns the command whose description exactly matches with the keyword." }, { "code": null, "e": 26315, "s": 26064, "text": "-w, –wildcard: This option is used when the keyword(s) contain wildcards. apropos will independently search the page name and the description matching against the keyword(s).All the command related to sudo are listed when sudo is given as a wildcard." }, { "code": null, "e": 26392, "s": 26315, "text": "All the command related to sudo are listed when sudo is given as a wildcard." }, { "code": null, "e": 26728, "s": 26392, "text": "-a, –and: This option is used when we want all the keywords to match. It returns nothing if any one of the keywords supplied has no matching in the man page or description. In the below input, two keywords have been given and only two commands are displayed in the result since there is only one command that contains both the keyword." }, { "code": null, "e": 26869, "s": 26728, "text": "-l, –long: By default, the output is trimmed to the terminal width. This option becomes handy when we don’t want the result to be truncated." }, { "code": null, "e": 26970, "s": 26869, "text": "-C: This option is used when we don’t want to use the default(/manpath) but user configuration file." }, { "code": null, "e": 27009, "s": 26970, "text": "-L: Define the locale for this search." }, { "code": null, "e": 27181, "s": 27009, "text": "-m, –systems: This option use manual pages from other systems. This option is helpful when we want to search the man page description of other accessible operating system." }, { "code": null, "e": 27270, "s": 27181, "text": "-M, –manpath: Set search path for manual pages to PATH rather than the default $MANPATH." }, { "code": null, "e": 27413, "s": 27270, "text": "-s, –sections, –section: This option is used when we want to search only particular sections (colon-separated) that are given in the argument." }, { "code": null, "e": 27460, "s": 27413, "text": "-?, –help: This option displays the help list." }, { "code": null, "e": 27505, "s": 27460, "text": "-V, –version: Used to print program version." }, { "code": null, "e": 27665, "s": 27505, "text": "-r, –regex: This option interpret each keyword as a regex(regular expression). The keyword will be independently matched against the page name and description." }, { "code": null, "e": 27674, "s": 27665, "text": "Shivam_k" }, { "code": null, "e": 27695, "s": 27674, "text": "Linux-basic-commands" }, { "code": null, "e": 27709, "s": 27695, "text": "linux-command" }, { "code": null, "e": 27716, "s": 27709, "text": "Picked" }, { "code": null, "e": 27727, "s": 27716, "text": "Linux-Unix" }, { "code": null, "e": 27825, "s": 27727, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27863, "s": 27825, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27898, "s": 27863, "text": "tar command in Linux with examples" }, { "code": null, "e": 27934, "s": 27898, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27972, "s": 27934, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 28010, "s": 27972, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 28045, "s": 28010, "text": "Cat command in Linux with examples" }, { "code": null, "e": 28081, "s": 28045, "text": "Tail command in Linux with examples" }, { "code": null, "e": 28118, "s": 28081, "text": "touch command in Linux with Examples" }, { "code": null, "e": 28162, "s": 28118, "text": "Mutex lock for Linux Thread Synchronization" } ]
NLP in Python- Vectorizing. Common vectorizing techniques employed... | by Divya Raghunathan | Towards Data Science
In this article, we will learn about vectorizing and different vectorizing techniques employed in an NLP model. Then, we will apply these concepts to the context of a problem. We will work with a dataset that classifies news as fake or real. The dataset is available on Kaggle, the link to the dataset is below: https://www.kaggle.com/clmentbisaillon/fake-and-real-news-dataset The initial step involved in a typical machine learning text pipeline is data cleaning. This step is covered in detailed in a previous article, linked below: towardsdatascience.com The raw news titles were transformed into a cleaned format containing only the essential information (last column of the above picture). The next step is to further transform the cleaned text into a form that the machine learning model can understand. This process is known as Vectorizing. In our context, each news title is converted to a numerical vector representative of that particular title. There are many vectorization techniques, but in this article, we will focus on the three widely used vectorization techniques- Count vectorization, N-Grams, TF-IDF, and their implementation in Python. Count vectorization Count vectorization As discussed above, vectorization is the process of converting text to numerical entries in a matrix form. In the count vectorization technique, a document term matrix is generated where each cell is the count corresponding to the news title indicating the number of times a word appears in a document, also known as the term frequency. The document term matrix is a set of dummy variables that indicates if a particular word appears in the document. A column is dedicated to each word in the corpus. The count is directly proportionate to the correlation of the category of the news title. This means, if a particular word appears many times in fake news titles or real news titles, then the particular word has a high predictive power of determining if the news title is fake or real. def clean_title(text): text = "".join([word.lower() for word in text if word not in string.punctuation]) title = re.split('\W+', text) text = [ps.stem(word) for word in title if word not in nltk.corpus.stopwords.words('english')] return textcount_vectorize = CountVectorizer(analyzer=clean_title) vectorized = count_vectorize.fit_transform(news['title']) Dissecting the above code, the function “clean_title”- joins the lowercase news titles without punctuation. Then, the text is split on any non-word character. Finally, the non-stop words are stemmed and presented as a list. A detailed description of the cleaning process is given in this article. Next, we have made use of the “CountVectorizer” package available in the sklearn library under sklearn.feature_extraction.text. The default values and the definition are available in the scikit-learn — Count Vectorizer documentation. In the above code, we have instantiated Count Vectorizer and defined one parameter — analyzer. The other parameters are its default values. The analyzer parameter calls for a string and we have passed a function, that takes in raw text and returns a cleaned string. The shape of the document term matrix is 44898,15824. There are 44898 news titles and 15824 unique words in all the titles. The vectorizer produces a sparse matrix output, as shown in the picture. Only the locations of the non-zero values will be stored to save space. So, an output of the vectorization will look something like this: <20x158 sparse matrix of type '<class 'numpy.int64'>' with 206 stored elements in Compressed Sparse Row format> but, converting the above to an array form yields the below result: As shown in the picture, most of the cells contain a 0 value, this is known as a sparse matrix. Many vectorized outputs would look similar to this, as naturally many titles wouldn’t contain a particular word. 2. N-Grams Similar to the count vectorization technique, in the N-Gram method, a document term matrix is generated and each cell represents the count. The difference in the N-grams method is that the count represents the combination of adjacent words of length n in the title. Count vectorization is N-Gram where n=1. For example, “I love this article” has four words and n=4. if n=2, i.e bigram, then the columns would be — [“I love”, “love this”, ‘this article”] if n=3, i.e trigram, then the columns would be — [“I love this”, ”love this article”] if n=4,i.e four-gram, then the column would be -[‘“I love this article”] The n value is chosen based on performance. For the python code, the cleaning process is performed similarly to the count vectorization technique, but the words are not in a tokenized list form. The tokenized words are joined to form a string, so the adjacent words can be gathered to effectively perform N-Grams. The cleaned title text is shown below: The remaining vectorization technique is the same as the Count Vectorization method we did above. The trade-off is between the number of N values. Choosing a smaller N value, may not be sufficient enough to provide the most useful information. Whereas choosing a high N value, will yield a huge matrix with loads of features. N-gram may be powerful, but it needs a little more care. 3. Term Frequency-Inverse Document Frequency (TF-IDF) Similar to the count vectorization method, in the TF-IDF method, a document term matrix is generated and each column represents a single unique word. The difference in the TF-IDF method is that each cell doesn’t indicate the term frequency, but the cell value represents a weighting that highlights the importance of that particular word to the document. TF-IDF formula: The second term of the equation helps in pulling out the rare words. What does that mean? If a word appeared multiple times across many documents, then the denominator df will increase, reducing the value of the second term. Term frequency or tf is the percentage of the number of times a word (x) occurs in the document (y) divided by the total number of words in y. For the python code, we will use the same cleaning process as the Count Vectorizer method. Sklearn’s TfidfVectorizer can be used for the vectorization portion in Python. The sparse matrix output for this method displays decimals representing the weight of the word in the document. High weight means that the word occurs many times within a few documents and low weight means that the word occurs fewer times in a lot of documents or repeats across multiple documents. Concluding thoughts There is no rule of thumb in choosing a vectorization method. I often decide based on the business problem at hand. If there are no constraints, I often start with the easiest method (usually fastest). ... I’d love to hear your thoughts and feedback on my articles. Please do leave them in the comment section below.
[ { "code": null, "e": 347, "s": 171, "text": "In this article, we will learn about vectorizing and different vectorizing techniques employed in an NLP model. Then, we will apply these concepts to the context of a problem." }, { "code": null, "e": 483, "s": 347, "text": "We will work with a dataset that classifies news as fake or real. The dataset is available on Kaggle, the link to the dataset is below:" }, { "code": null, "e": 549, "s": 483, "text": "https://www.kaggle.com/clmentbisaillon/fake-and-real-news-dataset" }, { "code": null, "e": 707, "s": 549, "text": "The initial step involved in a typical machine learning text pipeline is data cleaning. This step is covered in detailed in a previous article, linked below:" }, { "code": null, "e": 730, "s": 707, "text": "towardsdatascience.com" }, { "code": null, "e": 1329, "s": 730, "text": "The raw news titles were transformed into a cleaned format containing only the essential information (last column of the above picture). The next step is to further transform the cleaned text into a form that the machine learning model can understand. This process is known as Vectorizing. In our context, each news title is converted to a numerical vector representative of that particular title. There are many vectorization techniques, but in this article, we will focus on the three widely used vectorization techniques- Count vectorization, N-Grams, TF-IDF, and their implementation in Python." }, { "code": null, "e": 1349, "s": 1329, "text": "Count vectorization" }, { "code": null, "e": 1369, "s": 1349, "text": "Count vectorization" }, { "code": null, "e": 2156, "s": 1369, "text": "As discussed above, vectorization is the process of converting text to numerical entries in a matrix form. In the count vectorization technique, a document term matrix is generated where each cell is the count corresponding to the news title indicating the number of times a word appears in a document, also known as the term frequency. The document term matrix is a set of dummy variables that indicates if a particular word appears in the document. A column is dedicated to each word in the corpus. The count is directly proportionate to the correlation of the category of the news title. This means, if a particular word appears many times in fake news titles or real news titles, then the particular word has a high predictive power of determining if the news title is fake or real." }, { "code": null, "e": 2530, "s": 2156, "text": "def clean_title(text): text = \"\".join([word.lower() for word in text if word not in string.punctuation]) title = re.split('\\W+', text) text = [ps.stem(word) for word in title if word not in nltk.corpus.stopwords.words('english')] return textcount_vectorize = CountVectorizer(analyzer=clean_title) vectorized = count_vectorize.fit_transform(news['title'])" }, { "code": null, "e": 2827, "s": 2530, "text": "Dissecting the above code, the function “clean_title”- joins the lowercase news titles without punctuation. Then, the text is split on any non-word character. Finally, the non-stop words are stemmed and presented as a list. A detailed description of the cleaning process is given in this article." }, { "code": null, "e": 3327, "s": 2827, "text": "Next, we have made use of the “CountVectorizer” package available in the sklearn library under sklearn.feature_extraction.text. The default values and the definition are available in the scikit-learn — Count Vectorizer documentation. In the above code, we have instantiated Count Vectorizer and defined one parameter — analyzer. The other parameters are its default values. The analyzer parameter calls for a string and we have passed a function, that takes in raw text and returns a cleaned string." }, { "code": null, "e": 3451, "s": 3327, "text": "The shape of the document term matrix is 44898,15824. There are 44898 news titles and 15824 unique words in all the titles." }, { "code": null, "e": 3662, "s": 3451, "text": "The vectorizer produces a sparse matrix output, as shown in the picture. Only the locations of the non-zero values will be stored to save space. So, an output of the vectorization will look something like this:" }, { "code": null, "e": 3774, "s": 3662, "text": "<20x158 sparse matrix of type '<class 'numpy.int64'>'\twith 206 stored elements in Compressed Sparse Row format>" }, { "code": null, "e": 3842, "s": 3774, "text": "but, converting the above to an array form yields the below result:" }, { "code": null, "e": 4051, "s": 3842, "text": "As shown in the picture, most of the cells contain a 0 value, this is known as a sparse matrix. Many vectorized outputs would look similar to this, as naturally many titles wouldn’t contain a particular word." }, { "code": null, "e": 4062, "s": 4051, "text": "2. N-Grams" }, { "code": null, "e": 4428, "s": 4062, "text": "Similar to the count vectorization technique, in the N-Gram method, a document term matrix is generated and each cell represents the count. The difference in the N-grams method is that the count represents the combination of adjacent words of length n in the title. Count vectorization is N-Gram where n=1. For example, “I love this article” has four words and n=4." }, { "code": null, "e": 4516, "s": 4428, "text": "if n=2, i.e bigram, then the columns would be — [“I love”, “love this”, ‘this article”]" }, { "code": null, "e": 4602, "s": 4516, "text": "if n=3, i.e trigram, then the columns would be — [“I love this”, ”love this article”]" }, { "code": null, "e": 4675, "s": 4602, "text": "if n=4,i.e four-gram, then the column would be -[‘“I love this article”]" }, { "code": null, "e": 4719, "s": 4675, "text": "The n value is chosen based on performance." }, { "code": null, "e": 4989, "s": 4719, "text": "For the python code, the cleaning process is performed similarly to the count vectorization technique, but the words are not in a tokenized list form. The tokenized words are joined to form a string, so the adjacent words can be gathered to effectively perform N-Grams." }, { "code": null, "e": 5028, "s": 4989, "text": "The cleaned title text is shown below:" }, { "code": null, "e": 5126, "s": 5028, "text": "The remaining vectorization technique is the same as the Count Vectorization method we did above." }, { "code": null, "e": 5411, "s": 5126, "text": "The trade-off is between the number of N values. Choosing a smaller N value, may not be sufficient enough to provide the most useful information. Whereas choosing a high N value, will yield a huge matrix with loads of features. N-gram may be powerful, but it needs a little more care." }, { "code": null, "e": 5465, "s": 5411, "text": "3. Term Frequency-Inverse Document Frequency (TF-IDF)" }, { "code": null, "e": 5820, "s": 5465, "text": "Similar to the count vectorization method, in the TF-IDF method, a document term matrix is generated and each column represents a single unique word. The difference in the TF-IDF method is that each cell doesn’t indicate the term frequency, but the cell value represents a weighting that highlights the importance of that particular word to the document." }, { "code": null, "e": 5836, "s": 5820, "text": "TF-IDF formula:" }, { "code": null, "e": 6204, "s": 5836, "text": "The second term of the equation helps in pulling out the rare words. What does that mean? If a word appeared multiple times across many documents, then the denominator df will increase, reducing the value of the second term. Term frequency or tf is the percentage of the number of times a word (x) occurs in the document (y) divided by the total number of words in y." }, { "code": null, "e": 6374, "s": 6204, "text": "For the python code, we will use the same cleaning process as the Count Vectorizer method. Sklearn’s TfidfVectorizer can be used for the vectorization portion in Python." }, { "code": null, "e": 6673, "s": 6374, "text": "The sparse matrix output for this method displays decimals representing the weight of the word in the document. High weight means that the word occurs many times within a few documents and low weight means that the word occurs fewer times in a lot of documents or repeats across multiple documents." }, { "code": null, "e": 6693, "s": 6673, "text": "Concluding thoughts" }, { "code": null, "e": 6895, "s": 6693, "text": "There is no rule of thumb in choosing a vectorization method. I often decide based on the business problem at hand. If there are no constraints, I often start with the easiest method (usually fastest)." }, { "code": null, "e": 6899, "s": 6895, "text": "..." } ]
Why is method overloading not possible by changing the return type of the method only in java?
Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. If you observe the following example, it contains two methods with same name, different parameters and if you call the method by passing two integer values the first method will be executed and, if you call by passing 3 integer values then the second method will be executed.It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method. Live Demo public class Sample{ public int add(int a, int b){ int c = a+b; return c; } public void add(int a, int b, int c){ int z = a+b+c; System.out.println(z); } public static void main(String args[] ){ Sample obj = new Sample(); System.out.println(obj.add(40, 50)); obj.add(40, 50, 60); } } 90 150
[ { "code": null, "e": 1202, "s": 1062, "text": "Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call." }, { "code": null, "e": 1643, "s": 1202, "text": "If you observe the following example, it contains two methods with same name, different parameters and if you call the method by passing two integer values the first method will be executed and, if you call by passing 3 integer values then the second method will be executed.It is not possible to decide to execute which method based on the return type, therefore, overloading is not possible just by changing the return type of the method." }, { "code": null, "e": 1654, "s": 1643, "text": " Live Demo" }, { "code": null, "e": 1998, "s": 1654, "text": "public class Sample{\n public int add(int a, int b){\n int c = a+b;\n return c;\n }\n public void add(int a, int b, int c){\n int z = a+b+c;\n System.out.println(z);\n }\n public static void main(String args[] ){\n Sample obj = new Sample();\n System.out.println(obj.add(40, 50));\n obj.add(40, 50, 60);\n }\n}" }, { "code": null, "e": 2006, "s": 1998, "text": "90\n150\n" } ]
Order of execution of Initialization blocks and Constructors in Java - GeeksforGeeks
04 Apr, 2018 Prerequisite : Static blocks, Initializer block, ConstructorIn a Java program, operations can be performed on methods, constructors and initialization blocks.Instance Initialization Blocks : IIB are used to initialize instance variables. IIBs are executed before constructors. They run each time when object of the class is created.Initializer block : contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class.Constructors : are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation. Order of execution of Initialization blocks and constructor in Java Static initialization blocks will run whenever the class is loaded first time in JVMInitialization blocks run in the same order in which they appear in the program.Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. Static initialization blocks will run whenever the class is loaded first time in JVM Initialization blocks run in the same order in which they appear in the program. Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces. // Java code to illustrate order of// execution of constructors, static// and initialization blocksclass GFG { GFG(int x) { System.out.println("ONE argument constructor"); } GFG() { System.out.println("No argument constructor"); } static { System.out.println("1st static init"); } { System.out.println("1st instance init"); } { System.out.println("2nd instance init"); } static { System.out.println("2nd static init"); } public static void main(String[] args) { new GFG(); new GFG(8); }} Output 1st static init 2nd static init 1st instance init 2nd instance init No argument constructor 1st instance init 2nd instance init ONE argument constructor Note : If there are two or more static/initializer blocks then they are executed in the order in which they appear in the source code. Now, predict the output of the following program- // A tricky Java code to predict the output// based on order of // execution of constructors, static // and initialization blocksclass MyTest { static { initialize(); } private static int sum; public static int getSum() { initialize(); return sum; } private static boolean initialized = false; private static void initialize() { if (!initialized) { for (int i = 0; i < 100; i++) sum += i; initialized = true; } }} public class GFG { public static void main(String[] args) { System.out.println(MyTest.getSum()); }} Output: 9900 Explanation: Loop in initialize function goes from 0 to 99. With that in mind, you might think that the program prints the sum of the numbers from 0 to 99. Thus sum is 99 × 100 / 2, or 4, 950. The program, however, thinks otherwise. It prints 9900, fully twice this value. To understand its behavior, let’s trace its execution.The GFG.main method invokes MyTest.getSum. Before the getSum method can be executed, the VM must initialize the class MyTest. Class initialization executes static initializers in the order they appear in the source. The MyTest class has two static initializers: the static block at the top of the class and the initialization of the static field initialized. The block appears first. It invokes the method initialize, which tests the field initialized. Because no value has been assigned to this field, it has the default boolean value of false. Similarly, sum has the default int value of 0. Therefore, the initialize method does what you’d expect, adding 4, 950 to sum and setting initialized to true. After the static block executes, the static initializer for the initialized field sets it back to false, completing the class initialization of MyTest. Unfortunately, sum now contains the 4950, but initialized contains false. The main method in the GFG class then invokes MyTest.getSum, which in turn invokes initialize method. Because the initialized flag is false, the initializeIf method enters its loop, which adds another 4, 950 to the value of sum, increasing its value to 9, 900. The getSum method returns this value, and the program prints itThis article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes arrow_drop_upSave This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. aakashkumarjee Java-Constructors Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Reverse a string in Java Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples How to iterate any Map in Java Interfaces in Java Initialize an ArrayList in Java
[ { "code": null, "e": 22791, "s": 22763, "text": "\n04 Apr, 2018" }, { "code": null, "e": 23492, "s": 22791, "text": "Prerequisite : Static blocks, Initializer block, ConstructorIn a Java program, operations can be performed on methods, constructors and initialization blocks.Instance Initialization Blocks : IIB are used to initialize instance variables. IIBs are executed before constructors. They run each time when object of the class is created.Initializer block : contains the code that is always executed whenever an instance is created. It is used to declare/initialize the common part of various constructors of a class.Constructors : are used to initialize the object’s state. Like methods, a constructor also contains collection of statements(i.e. instructions) that are executed at time of Object creation." }, { "code": null, "e": 23560, "s": 23492, "text": "Order of execution of Initialization blocks and constructor in Java" }, { "code": null, "e": 23903, "s": 23560, "text": "Static initialization blocks will run whenever the class is loaded first time in JVMInitialization blocks run in the same order in which they appear in the program.Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces." }, { "code": null, "e": 23988, "s": 23903, "text": "Static initialization blocks will run whenever the class is loaded first time in JVM" }, { "code": null, "e": 24069, "s": 23988, "text": "Initialization blocks run in the same order in which they appear in the program." }, { "code": null, "e": 24248, "s": 24069, "text": "Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked. They are typically placed above the constructors within braces." }, { "code": "// Java code to illustrate order of// execution of constructors, static// and initialization blocksclass GFG { GFG(int x) { System.out.println(\"ONE argument constructor\"); } GFG() { System.out.println(\"No argument constructor\"); } static { System.out.println(\"1st static init\"); } { System.out.println(\"1st instance init\"); } { System.out.println(\"2nd instance init\"); } static { System.out.println(\"2nd static init\"); } public static void main(String[] args) { new GFG(); new GFG(8); }}", "e": 24864, "s": 24248, "text": null }, { "code": null, "e": 24871, "s": 24864, "text": "Output" }, { "code": null, "e": 25025, "s": 24871, "text": "1st static init\n2nd static init\n1st instance init\n2nd instance init\nNo argument constructor\n1st instance init\n2nd instance init\nONE argument constructor" }, { "code": null, "e": 25160, "s": 25025, "text": "Note : If there are two or more static/initializer blocks then they are executed in the order in which they appear in the source code." }, { "code": null, "e": 25210, "s": 25160, "text": "Now, predict the output of the following program-" }, { "code": "// A tricky Java code to predict the output// based on order of // execution of constructors, static // and initialization blocksclass MyTest { static { initialize(); } private static int sum; public static int getSum() { initialize(); return sum; } private static boolean initialized = false; private static void initialize() { if (!initialized) { for (int i = 0; i < 100; i++) sum += i; initialized = true; } }} public class GFG { public static void main(String[] args) { System.out.println(MyTest.getSum()); }}", "e": 25862, "s": 25210, "text": null }, { "code": null, "e": 25870, "s": 25862, "text": "Output:" }, { "code": null, "e": 25876, "s": 25870, "text": "9900\n" }, { "code": null, "e": 25889, "s": 25876, "text": "Explanation:" }, { "code": null, "e": 26149, "s": 25889, "text": "Loop in initialize function goes from 0 to 99. With that in mind, you might think that the program prints the sum of the numbers from 0 to 99. Thus sum is 99 × 100 / 2, or 4, 950. The program, however, thinks otherwise. It prints 9900, fully twice this value." }, { "code": null, "e": 26419, "s": 26149, "text": "To understand its behavior, let’s trace its execution.The GFG.main method invokes MyTest.getSum. Before the getSum method can be executed, the VM must initialize the class MyTest. Class initialization executes static initializers in the order they appear in the source." }, { "code": null, "e": 26749, "s": 26419, "text": "The MyTest class has two static initializers: the static block at the top of the class and the initialization of the static field initialized. The block appears first. It invokes the method initialize, which tests the field initialized. Because no value has been assigned to this field, it has the default boolean value of false." }, { "code": null, "e": 27133, "s": 26749, "text": "Similarly, sum has the default int value of 0. Therefore, the initialize method does what you’d expect, adding 4, 950 to sum and setting initialized to true. After the static block executes, the static initializer for the initialized field sets it back to false, completing the class initialization of MyTest. Unfortunately, sum now contains the 4950, but initialized contains false." }, { "code": null, "e": 27918, "s": 27133, "text": "The main method in the GFG class then invokes MyTest.getSum, which in turn invokes initialize method. Because the initialized flag is false, the initializeIf method enters its loop, which adds another 4, 950 to the value of sum, increasing its value to 9, 900. The getSum method returns this value, and the program prints itThis article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 28220, "s": 27918, "text": "This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 28345, "s": 28220, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 28360, "s": 28345, "text": "aakashkumarjee" }, { "code": null, "e": 28378, "s": 28360, "text": "Java-Constructors" }, { "code": null, "e": 28383, "s": 28378, "text": "Java" }, { "code": null, "e": 28388, "s": 28383, "text": "Java" }, { "code": null, "e": 28486, "s": 28388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28495, "s": 28486, "text": "Comments" }, { "code": null, "e": 28508, "s": 28495, "text": "Old Comments" }, { "code": null, "e": 28523, "s": 28508, "text": "Arrays in Java" }, { "code": null, "e": 28567, "s": 28523, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28589, "s": 28567, "text": "For-each loop in Java" }, { "code": null, "e": 28614, "s": 28589, "text": "Reverse a string in Java" }, { "code": null, "e": 28650, "s": 28614, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 28701, "s": 28650, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 28731, "s": 28701, "text": "HashMap in Java with Examples" }, { "code": null, "e": 28762, "s": 28731, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28781, "s": 28762, "text": "Interfaces in Java" } ]
Scraping a table in a PDF and then test the data quality in Python | by Ash Smith | Towards Data Science
Suppose you need to ingest some data into your data warehouse and after further discussions with your stakeholders the source of this data is a PDF document. Fortunately, this is pretty easy to do using a Python package called tabula-py. In this article I’m going to walk you through how you can scrape a table embedded in a PDF file, unit test that data using Great Expectations and then if valid, save the file in S3 on AWS. You can find the full source code to this article on Github or a working example on Google Colab. Before writing any code, let’s install all required packages. pip install tabula-pypip install great_expectationspip install boto3 from tabula import read_pdfimport great_expectations as geimport boto3from io import StringIO Below I have two PDF files which include some data related to some SpaceX launches. One is a clean and the expected format and the other has intentional errors which we’ll use when we unit test our date output. clean = "https://raw.githubusercontent.com/AshHimself/etl-pipeline-from-pdf/master/spacex_launch_data.pdf"messy = "https://raw.githubusercontent.com/AshHimself/etl-pipeline-from-pdf/master/spacex_launch_mess_data.pdf"source_pdf = read_pdf(clean, lattice=True, pages=”all”)df = source_pdf[0] Let’s take a look at our data to see how well tabula-py worked using only a single line of code! df.head() Pretty impressive! The only noticeable issue is that those headings won’t work very well in a database so let’s clean them up a little. #Rename the headersfields = {‘Flight Numb’: ‘flight_number’, ‘Dr ate’: ‘date’,’Time (UTC)’: ‘time_utc’,’Booster Ver’:’booster_version’,’iLoanunch Site’:’launch_site’}df = df.rename(columns=fields) #rename columnsdf.columns = map(str.lower, df.columns) ##lower case is nicer So far we have scraped the table from the PDF, saved it within a Pandas data frame and if we wanted to, we could save the data frame to a CSV on S3. However, what if the format of this PDF changes, what if someone changes a field name, how can we guarantee the data will be saved in S3 reliably? To test our data we are going to use an amazing package called Great Expectations. I’m not even going to be touching the surface of what this package can do so I highly suggest checking it out!. If we ran the code now we now, using our expected pdf, it should pass all assertions. However, take a look at the messy pdf. I have intentially added some duplicate flight_number rows and renamed the output column. If we ran it again (updating the PDF source from section 2) using the messy PDF the above code should return “Some assertions have failed :(“. The output of validation_results is also fairly verbose but you can view the full output here. {“Expected Column Position”: 7,”Expected”: “outcome”,”Found”: “mission outcome”} Having some basic tests in your ETL pipeline like this can easily help in ensuring the quality of your data is consistant and reliable. Its beyond the scope of this article to teach you how to setup an S3 bucket with correct permissions, so i’m going to assume you know how to do that or know how to figure it out. AWSAccessKeyId=’your_access_key_id’AWSSecretKey=’your_secret_key’bucket = ‘scrape-pdf-example’ # your S3 bucketcsv_buffer = StringIO()s3 = boto3.client(‘s3’, aws_access_key_id=AWSAccessKeyId, aws_secret_access_key=AWSSecretKey)df.to_csv(csv_buffer) #save our dataframe into memorys3_resource = boto3.resource(‘s3’)s3_resource.Object(bucket, ‘df.csv’).put(Body=csv_buffer.getvalue()) #push CSV to S3 Code snippet from Stefan! Done! you should now have a CSV file in your S3 bucket, which if you wanted could be ingested into other AWS service (Glue, Redshift etc). Do you test the quality of your data in production? The above code could have been easily achieved using the AWS Service Textract service or other Python packages, but for me, Tabula worked great on simple and more complex PDF documents with multiple tables and more complex table structures. Data Quality and testing data in general is critical and often neglected. Solutions like DBT and Matillion offer functionality to test/assert your data and make this process extremely easy to do. What tools do you use? Saving the final output to S3 is obviously optional. I only chose to do this as a future article will be making use of the CSV file in S3 as a starting point. About me: Passionate about all things data and live at the intersection between business, data, and machine learning. You can connect with me on LinkedIn if you want to chat!
[ { "code": null, "e": 697, "s": 172, "text": "Suppose you need to ingest some data into your data warehouse and after further discussions with your stakeholders the source of this data is a PDF document. Fortunately, this is pretty easy to do using a Python package called tabula-py. In this article I’m going to walk you through how you can scrape a table embedded in a PDF file, unit test that data using Great Expectations and then if valid, save the file in S3 on AWS. You can find the full source code to this article on Github or a working example on Google Colab." }, { "code": null, "e": 759, "s": 697, "text": "Before writing any code, let’s install all required packages." }, { "code": null, "e": 828, "s": 759, "text": "pip install tabula-pypip install great_expectationspip install boto3" }, { "code": null, "e": 922, "s": 828, "text": "from tabula import read_pdfimport great_expectations as geimport boto3from io import StringIO" }, { "code": null, "e": 1133, "s": 922, "text": "Below I have two PDF files which include some data related to some SpaceX launches. One is a clean and the expected format and the other has intentional errors which we’ll use when we unit test our date output." }, { "code": null, "e": 1424, "s": 1133, "text": "clean = \"https://raw.githubusercontent.com/AshHimself/etl-pipeline-from-pdf/master/spacex_launch_data.pdf\"messy = \"https://raw.githubusercontent.com/AshHimself/etl-pipeline-from-pdf/master/spacex_launch_mess_data.pdf\"source_pdf = read_pdf(clean, lattice=True, pages=”all”)df = source_pdf[0]" }, { "code": null, "e": 1521, "s": 1424, "text": "Let’s take a look at our data to see how well tabula-py worked using only a single line of code!" }, { "code": null, "e": 1531, "s": 1521, "text": "df.head()" }, { "code": null, "e": 1667, "s": 1531, "text": "Pretty impressive! The only noticeable issue is that those headings won’t work very well in a database so let’s clean them up a little." }, { "code": null, "e": 1941, "s": 1667, "text": "#Rename the headersfields = {‘Flight Numb’: ‘flight_number’, ‘Dr ate’: ‘date’,’Time (UTC)’: ‘time_utc’,’Booster Ver’:’booster_version’,’iLoanunch Site’:’launch_site’}df = df.rename(columns=fields) #rename columnsdf.columns = map(str.lower, df.columns) ##lower case is nicer" }, { "code": null, "e": 2237, "s": 1941, "text": "So far we have scraped the table from the PDF, saved it within a Pandas data frame and if we wanted to, we could save the data frame to a CSV on S3. However, what if the format of this PDF changes, what if someone changes a field name, how can we guarantee the data will be saved in S3 reliably?" }, { "code": null, "e": 2432, "s": 2237, "text": "To test our data we are going to use an amazing package called Great Expectations. I’m not even going to be touching the surface of what this package can do so I highly suggest checking it out!." }, { "code": null, "e": 2885, "s": 2432, "text": "If we ran the code now we now, using our expected pdf, it should pass all assertions. However, take a look at the messy pdf. I have intentially added some duplicate flight_number rows and renamed the output column. If we ran it again (updating the PDF source from section 2) using the messy PDF the above code should return “Some assertions have failed :(“. The output of validation_results is also fairly verbose but you can view the full output here." }, { "code": null, "e": 2966, "s": 2885, "text": "{“Expected Column Position”: 7,”Expected”: “outcome”,”Found”: “mission outcome”}" }, { "code": null, "e": 3102, "s": 2966, "text": "Having some basic tests in your ETL pipeline like this can easily help in ensuring the quality of your data is consistant and reliable." }, { "code": null, "e": 3281, "s": 3102, "text": "Its beyond the scope of this article to teach you how to setup an S3 bucket with correct permissions, so i’m going to assume you know how to do that or know how to figure it out." }, { "code": null, "e": 3680, "s": 3281, "text": "AWSAccessKeyId=’your_access_key_id’AWSSecretKey=’your_secret_key’bucket = ‘scrape-pdf-example’ # your S3 bucketcsv_buffer = StringIO()s3 = boto3.client(‘s3’, aws_access_key_id=AWSAccessKeyId, aws_secret_access_key=AWSSecretKey)df.to_csv(csv_buffer) #save our dataframe into memorys3_resource = boto3.resource(‘s3’)s3_resource.Object(bucket, ‘df.csv’).put(Body=csv_buffer.getvalue()) #push CSV to S3" }, { "code": null, "e": 3706, "s": 3680, "text": "Code snippet from Stefan!" }, { "code": null, "e": 3845, "s": 3706, "text": "Done! you should now have a CSV file in your S3 bucket, which if you wanted could be ingested into other AWS service (Glue, Redshift etc)." }, { "code": null, "e": 3897, "s": 3845, "text": "Do you test the quality of your data in production?" }, { "code": null, "e": 4138, "s": 3897, "text": "The above code could have been easily achieved using the AWS Service Textract service or other Python packages, but for me, Tabula worked great on simple and more complex PDF documents with multiple tables and more complex table structures." }, { "code": null, "e": 4357, "s": 4138, "text": "Data Quality and testing data in general is critical and often neglected. Solutions like DBT and Matillion offer functionality to test/assert your data and make this process extremely easy to do. What tools do you use?" }, { "code": null, "e": 4516, "s": 4357, "text": "Saving the final output to S3 is obviously optional. I only chose to do this as a future article will be making use of the CSV file in S3 as a starting point." } ]
Sentiment Analysis with Deep Learning | by Edwin Tan | Towards Data Science
Sentiment analysis is a technique in natural language processing used to identify emotions associated with the text. Common use cases of sentiment analysis include monitoring customers’ feedbacks on social media, brand and campaign monitoring. In this article, we examine how you can train your own sentiment analysis model on a custom dataset by leveraging on a pre-trained HuggingFace model. We will also examine how to efficiently perform single and batch prediction on the fine-tuned model in both CPU and GPU environments. If you are looking to for an out-of-the-box sentiment analysis model, check out my previous article on how to perform sentiment analysis in python with just 3 lines of code. pip install transformerspip install fast_ml==3.68pip install datasets import numpy as npimport pandas as pdfrom fast_ml.model_development import train_valid_test_splitfrom transformers import Trainer, TrainingArguments, AutoConfig, AutoTokenizer, AutoModelForSequenceClassificationimport torchfrom torch import nnfrom torch.nn.functional import softmaxfrom sklearn.metrics import classification_reportfrom sklearn.preprocessing import LabelEncoderimport datasets Enable GPU accelerator if it is available. DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")print (f'Device Availble: {DEVICE}') We will be using an ecommerce dataset that contains text reviews and ratings for women’s clothes. df = pd.read_csv('/kaggle/input/womens-ecommerce-clothing-reviews/Womens Clothing E-Commerce Reviews.csv')df.drop(columns = ['Unnamed: 0'], inplace = True)df.head() We are only interested in the Review Text and Rating columns. The Review Text column serves as input variable to the model and the Rating column is our target variable it has values ranging from 1 (least favourable) to 5 (most favourable). For clarity, let’s append “Star” or “Stars” behind each integer rating. df_reviews = df.loc[:, ['Review Text', 'Rating']].dropna()df_reviews['Rating'] = df_reviews['Rating'].apply(lambda x: f'{x} Stars' if x != 1 else f'{x} Star') This is how the data looks like now, where 1,2,3,4,5 stars are our class labels. Let’s encode the ratings using Sklearn’s LabelEncoder. le = LabelEncoder()df_reviews['Rating'] = le.fit_transform(df_reviews['Rating'])df_reviews.head() Notice that the Rating column has been transformed from a text to an integer column. The numbers in the Rating column ranges from 0 to 4. These are the class id for the class labels which will be used to train the model. Each of the class id corresponds to a rating. print (le.classes_)>> ['1 Star' '2 Stars' '3 Stars' **'4 Stars'** '5 Stars'] The position index of the list is the class id (0 to 4) and the value at the position is the original rating. For example at position number 3, the class id is “3” and it corresponds to the class label of “4 stars”. Let’s split the data into train, validation and test in the ratio of 80%, 10% and 10% respectively. (train_texts, train_labels, val_texts, val_labels, test_texts, test_labels) = train_valid_test_split(df_reviews, target = 'Rating', train_size=0.8, valid_size=0.1, test_size=0.1) Convert the review text from pandas series to list of sentences. train_texts = train_texts['Review Text'].to_list()train_labels = train_labels.to_list()val_texts = val_texts['Review Text'].to_list()val_labels = val_labels.to_list()test_texts = test_texts['Review Text'].to_list()test_labels = test_labels.to_list() Create a DataLoader class for processing and loading of the data during training and inference phase. class DataLoader(torch.utils.data.Dataset): def __init__(self, sentences=None, labels=None): self.sentences = sentences self.labels = labels self.tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased') if bool(sentences): self.encodings = self.tokenizer(self.sentences, truncation = True, padding = True) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} if self.labels == None: item['labels'] = None else: item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.sentences) def encode(self, x): return self.tokenizer(x, return_tensors = 'pt').to(DEVICE) Let’s take a look at the DataLoader in action. train_dataset = DataLoader(train_texts, train_labels)val_dataset = DataLoader(val_texts, val_labels)test_dataset = DataLoader(test_texts, test_labels) The DataLoader initializes a pretrained tokenizer and encodes the input sentences. We can get a single record from the DataLoader by using the __getitem__ function. Below is the result after an input sentence is tokenized. print (train_dataset.__getitem__(0)) The output data is a dictionary consisting of 3 keys-value pairs input_ids: this contains a tensor of integers where each integer represents words from the original sentence. The tokenizer step has transformed the individuals words into tokens represented by the integers. The first token 101 is the start of sentence token and the102 token is the end of sentence token. Notice that there are many trailing zeros, this is due to padding that was applied to the sentences at the tokenizer step. attention_mask: this is an array of binary values. Each position of the attention_mask corresponds to a token in the same position in the input_ids. 1 indicates that the token at the given position should be attended to and 0 indicates that the token at the given position is a padded value. labels: this is the target label We would like the model performance to be evaluated at intervals during the training phase. For that we require a metrics computation function that accepts a tuple of (prediction, label) as argument and returns a dictionary of metrics: {'metric1':value1,metric2:value2}. f1 = datasets.load_metric('f1')accuracy = datasets.load_metric('accuracy')precision = datasets.load_metric('precision')recall = datasets.load_metric('recall')def compute_metrics(eval_pred): metrics_dict = {} predictions, labels = eval_pred predictions = np.argmax(predictions, axis=1) metrics_dict.update(f1.compute(predictions = predictions, references = labels, average = 'macro')) metrics_dict.update(accuracy.compute(predictions = predictions, references = labels)) metrics_dict.update(precision.compute(predictions = predictions, references = labels, average = 'macro')) metrics_dict.update(recall.compute(predictions = predictions, references = labels, average = 'macro')) return metrics_dict Next, we configure instantiate a distilbert-base-uncased model from pretrained checkpoint. id2label = {idx:label for idx, label in enumerate(le.classes_)}label2id = {label:idx for idx, label in enumerate(le.classes_)}config = AutoConfig.from_pretrained('distilbert-base-uncased', num_labels = 5, id2label = id2label, label2id = label2id)model = AutoModelForSequenceClassification.from_config(config) num_labels: number of classes id2label: dictionary that maps the class ids to class labels {0: '1 Star', 1: '2 Stars', 2: '3 Stars', 3: '4 Stars', 4: '5 Stars'} label2id:mapping dictionary that maps the class labels to class ids {'1 Star': 0, '2 Stars': 1, '3 Stars': 2, '4 Stars': 3, '5 Stars': 4} Let’s examine the model configuration. The id2label and label2id dictionaries has been incorporated into the configuration. We can retrieve these dictionaries from the model's configuration during inference to find out the corresponding class labels for the predicted class ids. print (config)>> DistilBertConfig { "activation": "gelu", "architectures": [ "DistilBertForMaskedLM" ], "attention_dropout": 0.1, "dim": 768, "dropout": 0.1, "hidden_dim": 3072, "id2label": { "0": "1 Star", "1": "2 Stars", "2": "3 Stars", "3": "4 Stars", "4": "5 Stars" }, "initializer_range": 0.02, "label2id": { "1 Star": 0, "2 Stars": 1, "3 Stars": 2, "4 Stars": 3, "5 Stars": 4 }, "max_position_embeddings": 512, "model_type": "distilbert", "n_heads": 12, "n_layers": 6, "pad_token_id": 0, "qa_dropout": 0.1, "seq_classif_dropout": 0.2, "sinusoidal_pos_embds": false, "tie_weights_": true, "transformers_version": "4.6.1", "vocab_size": 30522} We can also examine the model architecture using print (model) Set up the training arguments. training_args = TrainingArguments( output_dir='/kaggle/working/results', num_train_epochs=10, per_device_train_batch_size=64, per_device_eval_batch_size=64, warmup_steps=500, weight_decay=0.05, report_to='none', evaluation_strategy='steps', logging_dir='/kagge/working/logs', logging_steps=50) report_to enables logging of training artifacts and results to platforms such as mlflow, tensorboard, azure_ml etc per_device_train_batch_size is the batch size per TPU/GPU/CPU during training. Lower this if you face out of memory issues on your device per_device_eval_batch_size is the batch size per TPU/GPU/CPU during evaluation. Lower this if you face out of memory issues on your device logging_stepdetermines how frequently are the metrics evaluation done during training Instantiate the Trainer. Under the hood, the Trainer runs the training and evaluation loop based on the given training arguments, model, datasets and metrics. trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, compute_metrics=compute_metrics) Let’s start training! trainer.train() Evaluation is performed every 50 steps. We can change the interval of evaluation by changing the logging_steps argument in TrainingArguments. In addition to the default training and validation loss metrics, we also get additional metrics which we had defined in the compute_metric function earlier. Let’s evaluate our training on the test set. eval_results = trainer.predict(test_dataset) The Trainer's predict function returns 3 items: An array of raw prediction scores An array of raw prediction scores print (test_results.predictions) 2. The ground truth label ids print (test_results.label_ids)>> [1 1 4 ... 4 3 1] 3. Metrics print (test_results.metrics)>> {'test_loss': 0.9638910293579102, 'test_f1': 0.28503729426950286, 'test_accuracy': 0.5982339955849889, 'test_precision': 0.2740061405117546, 'test_recall': 0.30397183356136337, 'test_runtime': 5.7367, 'test_samples_per_second': 394.826, 'test_mem_cpu_alloc_delta': 0, 'test_mem_gpu_alloc_delta': 0, 'test_mem_cpu_peaked_delta': 0, 'test_mem_gpu_peaked_delta': 348141568} The model prediction function outputs unnormalized probability scores. To find the class probabilities we take a softmax across the unnormalized scores. The class with the highest class probabilities is taken to be the predicted class. we can find this by taking the argmax of the class probabilities. The id2label attribute which we stored in the model's configuration earlier on can be used to map the class id (0-4) to the class labels (1 star, 2 stars..). label2id_mapper = model.config.id2labelproba = softmax(torch.from_numpy(test_results.predictions))pred = [label2id_mapper[i] for i in torch.argmax(proba, dim = -1).numpy()]actual = [label2id_mapper[i] for i in test_results.label_ids] We use Sklearn’s classification_reportto obtain the precision, recall, f1 and accuracy scores. class_report = classification_report(actual, pred, output_dict = True)pd.DataFrame(class_report) trainer.save_model('/kaggle/working/sentiment_model') In this section, we look at how to load and perform predictions on the trained model. Let’s test out inference in a separate notebook. import pandas as pdimport numpy as npfrom transformers import Trainer, TrainingArguments, AutoConfig, AutoTokenizer, AutoModelForSequenceClassificationimport torchfrom torch import nnfrom torch.nn.functional import softmax The inference can work in both GPU or CPU environment. Enable GPU in your environment if it is available. DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")print (f'Device Availble: {DEVICE}') This is the same DataLoader as we have used in the training phase class DataLoader(torch.utils.data.Dataset): def __init__(self, sentences=None, labels=None): self.sentences = sentences self.labels = labels self.tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased') if bool(sentences): self.encodings = self.tokenizer(self.sentences, truncation = True, padding = True) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} if self.labels == None: item['labels'] = None else: item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.sentences) def encode(self, x): return self.tokenizer(x, return_tensors = 'pt').to(DEVICE) The SentimentModel class helps to initialize the model and contains the predict_proba and batch_predict_proba methods for single and batch prediction respectively. The batch_predict_proba uses HuggingFace's Trainer to perform batch scoring. class SentimentModel(): def __init__(self, model_path): self.model = AutoModelForSequenceClassification.from_pretrained(model_path).to(DEVICE) args = TrainingArguments(output_dir='/kaggle/working/results', per_device_eval_batch_size=64) self.batch_model = Trainer(model = self.model, args= args) self.single_dataloader = DataLoader() def batch_predict_proba(self, x): predictions = self.batch_model.predict(DataLoader(x)) logits = torch.from_numpy(predictions.predictions) if DEVICE == 'cpu': proba = torch.nn.functional.softmax(logits, dim = 1).detach().numpy() else: proba = torch.nn.functional.softmax(logits, dim = 1).to('cpu').detach().numpy() return proba def predict_proba(self, x): x = self.single_dataloader.encode(x).to(DEVICE) predictions = self.model(**x) logits = predictions.logits if DEVICE == 'cpu': proba = torch.nn.functional.softmax(logits, dim = 1).detach().numpy() else: proba = torch.nn.functional.softmax(logits, dim = 1).to('cpu').detach().numpy() return proba Let’s load some sample data df = pd.read_csv('/kaggle/input/womens-ecommerce-clothing-reviews/Womens Clothing E-Commerce Reviews.csv')df.drop(columns = ['Unnamed: 0'], inplace = True)df_reviews = df.loc[:, ['Review Text', 'Rating']].dropna()df_reviews['Rating'] = df_reviews['Rating'].apply(lambda x: f'{x} Stars' if x != 1 else f'{x} Star')df_reviews.head() We will create two sets of data. One for batch scoring and the other for single scoring. batch_sentences = df_reviews.sample(n = 10000, random_state = 1)['Review Text'].to_list()single_sentence = df_reviews.sample(n = 1, random_state = 1)['Review Text'].to_list()[0] Instantiate the model sentiment_model = SentimentModel('../input/fine-tune-huggingface-sentiment-analysis/sentiment_model') Predict on a single sentence using the predict_proba method. single_sentence_probas = sentiment_model.predict_proba(single_sentence)id2label = sentiment_model.model.config.id2labelpredicted_class_label = id2label[np.argmax(single_sentence_probas)]print (predicted_class_label)>> 5 Stars Predict on a batch of sentences using the batch_predict_proba method. batch_sentence_probas = sentiment_model.batch_predict_proba(batch_sentences)predicted_class_labels = [id2label[i] for i in np.argmax(batch_sentence_probas, axis = -1)] Let’s compare the inference speed for between predict_proba and batch_predict_proba method for 10k sample data in a CPU and GPU environment. We will iterate through 10k samples for predict_proba make a single prediction at a time while scoring all 10k without iteration using the batch_predict_proa method. %%timefor sentence in batch_sentences: single_sentence_probas = sentiment_model.predict_proba(sentence)%%timebatch_sentence_probas = sentiment_model.batch_predict_proba(batch_sentences) GPU environment Iterating through predict_proba takes ~2 minutes while batch_predict_proba takes ~30 seconds for 10k sample data. Batch prediction is almost 4 times faster than using single prediction in GPU environment. CPU Environment In CPU environment, predict_proba took ~14 minutes while batch_predict_proba took ~40 minutes, that is almost 3 times longer. Therefore for large set of data, use batch_predict_proba if you have GPU. if you do not have access to a GPU, you are better off with iterating through the dataset using predict_proba. In this article we examined: How to train your own deep learning sentiment analysis model by leveraging on a pretrained HuggingFace model How to create single and batch prediction methods for scoring Inference speed for single and batch scoring in both CPU and GPU environments The notebooks for this article can be found here: Training Inference Join Medium to read more stories like this.
[ { "code": null, "e": 416, "s": 172, "text": "Sentiment analysis is a technique in natural language processing used to identify emotions associated with the text. Common use cases of sentiment analysis include monitoring customers’ feedbacks on social media, brand and campaign monitoring." }, { "code": null, "e": 874, "s": 416, "text": "In this article, we examine how you can train your own sentiment analysis model on a custom dataset by leveraging on a pre-trained HuggingFace model. We will also examine how to efficiently perform single and batch prediction on the fine-tuned model in both CPU and GPU environments. If you are looking to for an out-of-the-box sentiment analysis model, check out my previous article on how to perform sentiment analysis in python with just 3 lines of code." }, { "code": null, "e": 944, "s": 874, "text": "pip install transformerspip install fast_ml==3.68pip install datasets" }, { "code": null, "e": 1337, "s": 944, "text": "import numpy as npimport pandas as pdfrom fast_ml.model_development import train_valid_test_splitfrom transformers import Trainer, TrainingArguments, AutoConfig, AutoTokenizer, AutoModelForSequenceClassificationimport torchfrom torch import nnfrom torch.nn.functional import softmaxfrom sklearn.metrics import classification_reportfrom sklearn.preprocessing import LabelEncoderimport datasets" }, { "code": null, "e": 1380, "s": 1337, "text": "Enable GPU accelerator if it is available." }, { "code": null, "e": 1486, "s": 1380, "text": "DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")print (f'Device Availble: {DEVICE}')" }, { "code": null, "e": 1584, "s": 1486, "text": "We will be using an ecommerce dataset that contains text reviews and ratings for women’s clothes." }, { "code": null, "e": 1749, "s": 1584, "text": "df = pd.read_csv('/kaggle/input/womens-ecommerce-clothing-reviews/Womens Clothing E-Commerce Reviews.csv')df.drop(columns = ['Unnamed: 0'], inplace = True)df.head()" }, { "code": null, "e": 1989, "s": 1749, "text": "We are only interested in the Review Text and Rating columns. The Review Text column serves as input variable to the model and the Rating column is our target variable it has values ranging from 1 (least favourable) to 5 (most favourable)." }, { "code": null, "e": 2061, "s": 1989, "text": "For clarity, let’s append “Star” or “Stars” behind each integer rating." }, { "code": null, "e": 2220, "s": 2061, "text": "df_reviews = df.loc[:, ['Review Text', 'Rating']].dropna()df_reviews['Rating'] = df_reviews['Rating'].apply(lambda x: f'{x} Stars' if x != 1 else f'{x} Star')" }, { "code": null, "e": 2301, "s": 2220, "text": "This is how the data looks like now, where 1,2,3,4,5 stars are our class labels." }, { "code": null, "e": 2356, "s": 2301, "text": "Let’s encode the ratings using Sklearn’s LabelEncoder." }, { "code": null, "e": 2454, "s": 2356, "text": "le = LabelEncoder()df_reviews['Rating'] = le.fit_transform(df_reviews['Rating'])df_reviews.head()" }, { "code": null, "e": 2539, "s": 2454, "text": "Notice that the Rating column has been transformed from a text to an integer column." }, { "code": null, "e": 2721, "s": 2539, "text": "The numbers in the Rating column ranges from 0 to 4. These are the class id for the class labels which will be used to train the model. Each of the class id corresponds to a rating." }, { "code": null, "e": 2798, "s": 2721, "text": "print (le.classes_)>> ['1 Star' '2 Stars' '3 Stars' **'4 Stars'** '5 Stars']" }, { "code": null, "e": 3014, "s": 2798, "text": "The position index of the list is the class id (0 to 4) and the value at the position is the original rating. For example at position number 3, the class id is “3” and it corresponds to the class label of “4 stars”." }, { "code": null, "e": 3114, "s": 3014, "text": "Let’s split the data into train, validation and test in the ratio of 80%, 10% and 10% respectively." }, { "code": null, "e": 3293, "s": 3114, "text": "(train_texts, train_labels, val_texts, val_labels, test_texts, test_labels) = train_valid_test_split(df_reviews, target = 'Rating', train_size=0.8, valid_size=0.1, test_size=0.1)" }, { "code": null, "e": 3358, "s": 3293, "text": "Convert the review text from pandas series to list of sentences." }, { "code": null, "e": 3608, "s": 3358, "text": "train_texts = train_texts['Review Text'].to_list()train_labels = train_labels.to_list()val_texts = val_texts['Review Text'].to_list()val_labels = val_labels.to_list()test_texts = test_texts['Review Text'].to_list()test_labels = test_labels.to_list()" }, { "code": null, "e": 3710, "s": 3608, "text": "Create a DataLoader class for processing and loading of the data during training and inference phase." }, { "code": null, "e": 4603, "s": 3710, "text": "class DataLoader(torch.utils.data.Dataset): def __init__(self, sentences=None, labels=None): self.sentences = sentences self.labels = labels self.tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased') if bool(sentences): self.encodings = self.tokenizer(self.sentences, truncation = True, padding = True) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} if self.labels == None: item['labels'] = None else: item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.sentences) def encode(self, x): return self.tokenizer(x, return_tensors = 'pt').to(DEVICE)" }, { "code": null, "e": 4650, "s": 4603, "text": "Let’s take a look at the DataLoader in action." }, { "code": null, "e": 4801, "s": 4650, "text": "train_dataset = DataLoader(train_texts, train_labels)val_dataset = DataLoader(val_texts, val_labels)test_dataset = DataLoader(test_texts, test_labels)" }, { "code": null, "e": 5024, "s": 4801, "text": "The DataLoader initializes a pretrained tokenizer and encodes the input sentences. We can get a single record from the DataLoader by using the __getitem__ function. Below is the result after an input sentence is tokenized." }, { "code": null, "e": 5061, "s": 5024, "text": "print (train_dataset.__getitem__(0))" }, { "code": null, "e": 5126, "s": 5061, "text": "The output data is a dictionary consisting of 3 keys-value pairs" }, { "code": null, "e": 5555, "s": 5126, "text": "input_ids: this contains a tensor of integers where each integer represents words from the original sentence. The tokenizer step has transformed the individuals words into tokens represented by the integers. The first token 101 is the start of sentence token and the102 token is the end of sentence token. Notice that there are many trailing zeros, this is due to padding that was applied to the sentences at the tokenizer step." }, { "code": null, "e": 5847, "s": 5555, "text": "attention_mask: this is an array of binary values. Each position of the attention_mask corresponds to a token in the same position in the input_ids. 1 indicates that the token at the given position should be attended to and 0 indicates that the token at the given position is a padded value." }, { "code": null, "e": 5880, "s": 5847, "text": "labels: this is the target label" }, { "code": null, "e": 6151, "s": 5880, "text": "We would like the model performance to be evaluated at intervals during the training phase. For that we require a metrics computation function that accepts a tuple of (prediction, label) as argument and returns a dictionary of metrics: {'metric1':value1,metric2:value2}." }, { "code": null, "e": 6878, "s": 6151, "text": "f1 = datasets.load_metric('f1')accuracy = datasets.load_metric('accuracy')precision = datasets.load_metric('precision')recall = datasets.load_metric('recall')def compute_metrics(eval_pred): metrics_dict = {} predictions, labels = eval_pred predictions = np.argmax(predictions, axis=1) metrics_dict.update(f1.compute(predictions = predictions, references = labels, average = 'macro')) metrics_dict.update(accuracy.compute(predictions = predictions, references = labels)) metrics_dict.update(precision.compute(predictions = predictions, references = labels, average = 'macro')) metrics_dict.update(recall.compute(predictions = predictions, references = labels, average = 'macro')) return metrics_dict" }, { "code": null, "e": 6969, "s": 6878, "text": "Next, we configure instantiate a distilbert-base-uncased model from pretrained checkpoint." }, { "code": null, "e": 7383, "s": 6969, "text": "id2label = {idx:label for idx, label in enumerate(le.classes_)}label2id = {label:idx for idx, label in enumerate(le.classes_)}config = AutoConfig.from_pretrained('distilbert-base-uncased', num_labels = 5, id2label = id2label, label2id = label2id)model = AutoModelForSequenceClassification.from_config(config)" }, { "code": null, "e": 7413, "s": 7383, "text": "num_labels: number of classes" }, { "code": null, "e": 7544, "s": 7413, "text": "id2label: dictionary that maps the class ids to class labels {0: '1 Star', 1: '2 Stars', 2: '3 Stars', 3: '4 Stars', 4: '5 Stars'}" }, { "code": null, "e": 7682, "s": 7544, "text": "label2id:mapping dictionary that maps the class labels to class ids {'1 Star': 0, '2 Stars': 1, '3 Stars': 2, '4 Stars': 3, '5 Stars': 4}" }, { "code": null, "e": 7961, "s": 7682, "text": "Let’s examine the model configuration. The id2label and label2id dictionaries has been incorporated into the configuration. We can retrieve these dictionaries from the model's configuration during inference to find out the corresponding class labels for the predicted class ids." }, { "code": null, "e": 8665, "s": 7961, "text": "print (config)>> DistilBertConfig { \"activation\": \"gelu\", \"architectures\": [ \"DistilBertForMaskedLM\" ], \"attention_dropout\": 0.1, \"dim\": 768, \"dropout\": 0.1, \"hidden_dim\": 3072, \"id2label\": { \"0\": \"1 Star\", \"1\": \"2 Stars\", \"2\": \"3 Stars\", \"3\": \"4 Stars\", \"4\": \"5 Stars\" }, \"initializer_range\": 0.02, \"label2id\": { \"1 Star\": 0, \"2 Stars\": 1, \"3 Stars\": 2, \"4 Stars\": 3, \"5 Stars\": 4 }, \"max_position_embeddings\": 512, \"model_type\": \"distilbert\", \"n_heads\": 12, \"n_layers\": 6, \"pad_token_id\": 0, \"qa_dropout\": 0.1, \"seq_classif_dropout\": 0.2, \"sinusoidal_pos_embds\": false, \"tie_weights_\": true, \"transformers_version\": \"4.6.1\", \"vocab_size\": 30522}" }, { "code": null, "e": 8714, "s": 8665, "text": "We can also examine the model architecture using" }, { "code": null, "e": 8728, "s": 8714, "text": "print (model)" }, { "code": null, "e": 8759, "s": 8728, "text": "Set up the training arguments." }, { "code": null, "e": 9083, "s": 8759, "text": "training_args = TrainingArguments( output_dir='/kaggle/working/results', num_train_epochs=10, per_device_train_batch_size=64, per_device_eval_batch_size=64, warmup_steps=500, weight_decay=0.05, report_to='none', evaluation_strategy='steps', logging_dir='/kagge/working/logs', logging_steps=50)" }, { "code": null, "e": 9198, "s": 9083, "text": "report_to enables logging of training artifacts and results to platforms such as mlflow, tensorboard, azure_ml etc" }, { "code": null, "e": 9336, "s": 9198, "text": "per_device_train_batch_size is the batch size per TPU/GPU/CPU during training. Lower this if you face out of memory issues on your device" }, { "code": null, "e": 9475, "s": 9336, "text": "per_device_eval_batch_size is the batch size per TPU/GPU/CPU during evaluation. Lower this if you face out of memory issues on your device" }, { "code": null, "e": 9561, "s": 9475, "text": "logging_stepdetermines how frequently are the metrics evaluation done during training" }, { "code": null, "e": 9720, "s": 9561, "text": "Instantiate the Trainer. Under the hood, the Trainer runs the training and evaluation loop based on the given training arguments, model, datasets and metrics." }, { "code": null, "e": 9875, "s": 9720, "text": "trainer = Trainer( model=model, args=training_args, train_dataset=train_dataset, eval_dataset=val_dataset, compute_metrics=compute_metrics)" }, { "code": null, "e": 9897, "s": 9875, "text": "Let’s start training!" }, { "code": null, "e": 9913, "s": 9897, "text": "trainer.train()" }, { "code": null, "e": 10212, "s": 9913, "text": "Evaluation is performed every 50 steps. We can change the interval of evaluation by changing the logging_steps argument in TrainingArguments. In addition to the default training and validation loss metrics, we also get additional metrics which we had defined in the compute_metric function earlier." }, { "code": null, "e": 10257, "s": 10212, "text": "Let’s evaluate our training on the test set." }, { "code": null, "e": 10302, "s": 10257, "text": "eval_results = trainer.predict(test_dataset)" }, { "code": null, "e": 10350, "s": 10302, "text": "The Trainer's predict function returns 3 items:" }, { "code": null, "e": 10384, "s": 10350, "text": "An array of raw prediction scores" }, { "code": null, "e": 10418, "s": 10384, "text": "An array of raw prediction scores" }, { "code": null, "e": 10451, "s": 10418, "text": "print (test_results.predictions)" }, { "code": null, "e": 10481, "s": 10451, "text": "2. The ground truth label ids" }, { "code": null, "e": 10532, "s": 10481, "text": "print (test_results.label_ids)>> [1 1 4 ... 4 3 1]" }, { "code": null, "e": 10543, "s": 10532, "text": "3. Metrics" }, { "code": null, "e": 10955, "s": 10543, "text": "print (test_results.metrics)>> {'test_loss': 0.9638910293579102,\t\t'test_f1': 0.28503729426950286,\t\t'test_accuracy': 0.5982339955849889,\t\t'test_precision': 0.2740061405117546,\t\t'test_recall': 0.30397183356136337,\t\t'test_runtime': 5.7367,\t\t'test_samples_per_second': 394.826,\t\t'test_mem_cpu_alloc_delta': 0,\t\t'test_mem_gpu_alloc_delta': 0,\t\t'test_mem_cpu_peaked_delta': 0,\t\t'test_mem_gpu_peaked_delta': 348141568}" }, { "code": null, "e": 11415, "s": 10955, "text": "The model prediction function outputs unnormalized probability scores. To find the class probabilities we take a softmax across the unnormalized scores. The class with the highest class probabilities is taken to be the predicted class. we can find this by taking the argmax of the class probabilities. The id2label attribute which we stored in the model's configuration earlier on can be used to map the class id (0-4) to the class labels (1 star, 2 stars..)." }, { "code": null, "e": 11649, "s": 11415, "text": "label2id_mapper = model.config.id2labelproba = softmax(torch.from_numpy(test_results.predictions))pred = [label2id_mapper[i] for i in torch.argmax(proba, dim = -1).numpy()]actual = [label2id_mapper[i] for i in test_results.label_ids]" }, { "code": null, "e": 11744, "s": 11649, "text": "We use Sklearn’s classification_reportto obtain the precision, recall, f1 and accuracy scores." }, { "code": null, "e": 11841, "s": 11744, "text": "class_report = classification_report(actual, pred, output_dict = True)pd.DataFrame(class_report)" }, { "code": null, "e": 11895, "s": 11841, "text": "trainer.save_model('/kaggle/working/sentiment_model')" }, { "code": null, "e": 12030, "s": 11895, "text": "In this section, we look at how to load and perform predictions on the trained model. Let’s test out inference in a separate notebook." }, { "code": null, "e": 12253, "s": 12030, "text": "import pandas as pdimport numpy as npfrom transformers import Trainer, TrainingArguments, AutoConfig, AutoTokenizer, AutoModelForSequenceClassificationimport torchfrom torch import nnfrom torch.nn.functional import softmax" }, { "code": null, "e": 12359, "s": 12253, "text": "The inference can work in both GPU or CPU environment. Enable GPU in your environment if it is available." }, { "code": null, "e": 12465, "s": 12359, "text": "DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")print (f'Device Availble: {DEVICE}')" }, { "code": null, "e": 12531, "s": 12465, "text": "This is the same DataLoader as we have used in the training phase" }, { "code": null, "e": 13424, "s": 12531, "text": "class DataLoader(torch.utils.data.Dataset): def __init__(self, sentences=None, labels=None): self.sentences = sentences self.labels = labels self.tokenizer = AutoTokenizer.from_pretrained('distilbert-base-uncased') if bool(sentences): self.encodings = self.tokenizer(self.sentences, truncation = True, padding = True) def __getitem__(self, idx): item = {key: torch.tensor(val[idx]) for key, val in self.encodings.items()} if self.labels == None: item['labels'] = None else: item['labels'] = torch.tensor(self.labels[idx]) return item def __len__(self): return len(self.sentences) def encode(self, x): return self.tokenizer(x, return_tensors = 'pt').to(DEVICE)" }, { "code": null, "e": 13665, "s": 13424, "text": "The SentimentModel class helps to initialize the model and contains the predict_proba and batch_predict_proba methods for single and batch prediction respectively. The batch_predict_proba uses HuggingFace's Trainer to perform batch scoring." }, { "code": null, "e": 14877, "s": 13665, "text": "class SentimentModel(): def __init__(self, model_path): self.model = AutoModelForSequenceClassification.from_pretrained(model_path).to(DEVICE) args = TrainingArguments(output_dir='/kaggle/working/results', per_device_eval_batch_size=64) self.batch_model = Trainer(model = self.model, args= args) self.single_dataloader = DataLoader() def batch_predict_proba(self, x): predictions = self.batch_model.predict(DataLoader(x)) logits = torch.from_numpy(predictions.predictions) if DEVICE == 'cpu': proba = torch.nn.functional.softmax(logits, dim = 1).detach().numpy() else: proba = torch.nn.functional.softmax(logits, dim = 1).to('cpu').detach().numpy() return proba def predict_proba(self, x): x = self.single_dataloader.encode(x).to(DEVICE) predictions = self.model(**x) logits = predictions.logits if DEVICE == 'cpu': proba = torch.nn.functional.softmax(logits, dim = 1).detach().numpy() else: proba = torch.nn.functional.softmax(logits, dim = 1).to('cpu').detach().numpy() return proba" }, { "code": null, "e": 14905, "s": 14877, "text": "Let’s load some sample data" }, { "code": null, "e": 15236, "s": 14905, "text": "df = pd.read_csv('/kaggle/input/womens-ecommerce-clothing-reviews/Womens Clothing E-Commerce Reviews.csv')df.drop(columns = ['Unnamed: 0'], inplace = True)df_reviews = df.loc[:, ['Review Text', 'Rating']].dropna()df_reviews['Rating'] = df_reviews['Rating'].apply(lambda x: f'{x} Stars' if x != 1 else f'{x} Star')df_reviews.head()" }, { "code": null, "e": 15325, "s": 15236, "text": "We will create two sets of data. One for batch scoring and the other for single scoring." }, { "code": null, "e": 15503, "s": 15325, "text": "batch_sentences = df_reviews.sample(n = 10000, random_state = 1)['Review Text'].to_list()single_sentence = df_reviews.sample(n = 1, random_state = 1)['Review Text'].to_list()[0]" }, { "code": null, "e": 15525, "s": 15503, "text": "Instantiate the model" }, { "code": null, "e": 15627, "s": 15525, "text": "sentiment_model = SentimentModel('../input/fine-tune-huggingface-sentiment-analysis/sentiment_model')" }, { "code": null, "e": 15688, "s": 15627, "text": "Predict on a single sentence using the predict_proba method." }, { "code": null, "e": 15914, "s": 15688, "text": "single_sentence_probas = sentiment_model.predict_proba(single_sentence)id2label = sentiment_model.model.config.id2labelpredicted_class_label = id2label[np.argmax(single_sentence_probas)]print (predicted_class_label)>> 5 Stars" }, { "code": null, "e": 15984, "s": 15914, "text": "Predict on a batch of sentences using the batch_predict_proba method." }, { "code": null, "e": 16152, "s": 15984, "text": "batch_sentence_probas = sentiment_model.batch_predict_proba(batch_sentences)predicted_class_labels = [id2label[i] for i in np.argmax(batch_sentence_probas, axis = -1)]" }, { "code": null, "e": 16243, "s": 16152, "text": "Let’s compare the inference speed for between predict_proba and batch_predict_proba method" }, { "code": null, "e": 16459, "s": 16243, "text": "for 10k sample data in a CPU and GPU environment. We will iterate through 10k samples for predict_proba make a single prediction at a time while scoring all 10k without iteration using the batch_predict_proa method." }, { "code": null, "e": 16648, "s": 16459, "text": "%%timefor sentence in batch_sentences: single_sentence_probas = sentiment_model.predict_proba(sentence)%%timebatch_sentence_probas = sentiment_model.batch_predict_proba(batch_sentences)" }, { "code": null, "e": 16664, "s": 16648, "text": "GPU environment" }, { "code": null, "e": 16869, "s": 16664, "text": "Iterating through predict_proba takes ~2 minutes while batch_predict_proba takes ~30 seconds for 10k sample data. Batch prediction is almost 4 times faster than using single prediction in GPU environment." }, { "code": null, "e": 16885, "s": 16869, "text": "CPU Environment" }, { "code": null, "e": 17011, "s": 16885, "text": "In CPU environment, predict_proba took ~14 minutes while batch_predict_proba took ~40 minutes, that is almost 3 times longer." }, { "code": null, "e": 17196, "s": 17011, "text": "Therefore for large set of data, use batch_predict_proba if you have GPU. if you do not have access to a GPU, you are better off with iterating through the dataset using predict_proba." }, { "code": null, "e": 17225, "s": 17196, "text": "In this article we examined:" }, { "code": null, "e": 17334, "s": 17225, "text": "How to train your own deep learning sentiment analysis model by leveraging on a pretrained HuggingFace model" }, { "code": null, "e": 17396, "s": 17334, "text": "How to create single and batch prediction methods for scoring" }, { "code": null, "e": 17474, "s": 17396, "text": "Inference speed for single and batch scoring in both CPU and GPU environments" }, { "code": null, "e": 17524, "s": 17474, "text": "The notebooks for this article can be found here:" }, { "code": null, "e": 17533, "s": 17524, "text": "Training" }, { "code": null, "e": 17543, "s": 17533, "text": "Inference" } ]
Groovy - Switch Statement
Sometimes the nested if-else statement is so common and is used so often that an easier statement was designed called the switch statement. switch(expression) { case expression #1: statement #1 ... case expression #2: statement #2 ... case expression #N: statement #N ... default: statement #Default ... } The general working of this statement is as follows − The expression to be evaluated is placed in the switch statement. The expression to be evaluated is placed in the switch statement. There will be multiple case expressions defined to decide which set of statements should be executed based on the evaluation of the expression. There will be multiple case expressions defined to decide which set of statements should be executed based on the evaluation of the expression. A break statement is added to each case section of statements at the end. This is to ensure that the loop is exited as soon as the relevant set of statements gets executed. A break statement is added to each case section of statements at the end. This is to ensure that the loop is exited as soon as the relevant set of statements gets executed. There is also a default case statement which gets executed if none of the prior case expressions evaluate to true. There is also a default case statement which gets executed if none of the prior case expressions evaluate to true. The following diagram shows the flow of the switch-case statement. Following is an example of the switch statement − class Example { static void main(String[] args) { //initializing a local variable int a = 2 //Evaluating the expression value switch(a) { //There is case statement defined for 4 cases // Each case statement section has a break condition to exit the loop case 1: println("The value of a is One"); break; case 2: println("The value of a is Two"); break; case 3: println("The value of a is Three"); break; case 4: println("The value of a is Four"); break; default: println("The value is unknown"); break; } } } In the above example, we are first initializing a variable to a value of 2. We then have a switch statement which evaluates the value of the variable a. Based on the value of the variable it will execute the relevant case set of statements. The output of the above code would be − The value of a is Two 52 Lectures 8 hours Krishna Sakinala 49 Lectures 2.5 hours Packt Publishing Print Add Notes Bookmark this page
[ { "code": null, "e": 2378, "s": 2238, "text": "Sometimes the nested if-else statement is so common and is used so often that an easier statement was designed called the switch statement." }, { "code": null, "e": 2594, "s": 2378, "text": "switch(expression) { \n case expression #1: \n statement #1 \n ... \n case expression #2: \n statement #2 \n ... \n case expression #N: \n statement #N \n ... \n default:\n statement #Default \n ... \n} \n" }, { "code": null, "e": 2648, "s": 2594, "text": "The general working of this statement is as follows −" }, { "code": null, "e": 2714, "s": 2648, "text": "The expression to be evaluated is placed in the switch statement." }, { "code": null, "e": 2780, "s": 2714, "text": "The expression to be evaluated is placed in the switch statement." }, { "code": null, "e": 2924, "s": 2780, "text": "There will be multiple case expressions defined to decide which set of statements should be executed based on the evaluation of the expression." }, { "code": null, "e": 3068, "s": 2924, "text": "There will be multiple case expressions defined to decide which set of statements should be executed based on the evaluation of the expression." }, { "code": null, "e": 3241, "s": 3068, "text": "A break statement is added to each case section of statements at the end. This is to ensure that the loop is exited as soon as the relevant set of statements gets executed." }, { "code": null, "e": 3414, "s": 3241, "text": "A break statement is added to each case section of statements at the end. This is to ensure that the loop is exited as soon as the relevant set of statements gets executed." }, { "code": null, "e": 3529, "s": 3414, "text": "There is also a default case statement which gets executed if none of the prior case expressions evaluate to true." }, { "code": null, "e": 3644, "s": 3529, "text": "There is also a default case statement which gets executed if none of the prior case expressions evaluate to true." }, { "code": null, "e": 3711, "s": 3644, "text": "The following diagram shows the flow of the switch-case statement." }, { "code": null, "e": 3761, "s": 3711, "text": "Following is an example of the switch statement −" }, { "code": null, "e": 4528, "s": 3761, "text": "class Example { \n static void main(String[] args) { \n //initializing a local variable \n int a = 2\n\t\t\n //Evaluating the expression value \n switch(a) { \n //There is case statement defined for 4 cases \n // Each case statement section has a break condition to exit the loop \n\t\t\t\n case 1: \n println(\"The value of a is One\"); \n break; \n case 2: \n println(\"The value of a is Two\"); \n break; \n case 3: \n println(\"The value of a is Three\"); \n break; \n case 4: \n println(\"The value of a is Four\"); \n break; \n default: \n println(\"The value is unknown\"); \n break; \n }\n }\n}" }, { "code": null, "e": 4809, "s": 4528, "text": "In the above example, we are first initializing a variable to a value of 2. We then have a switch statement which evaluates the value of the variable a. Based on the value of the variable it will execute the relevant case set of statements. The output of the above code would be −" }, { "code": null, "e": 4832, "s": 4809, "text": "The value of a is Two\n" }, { "code": null, "e": 4865, "s": 4832, "text": "\n 52 Lectures \n 8 hours \n" }, { "code": null, "e": 4883, "s": 4865, "text": " Krishna Sakinala" }, { "code": null, "e": 4918, "s": 4883, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4936, "s": 4918, "text": " Packt Publishing" }, { "code": null, "e": 4943, "s": 4936, "text": " Print" }, { "code": null, "e": 4954, "s": 4943, "text": " Add Notes" } ]
Node.js Buffer.writeUInt16LE() Method - GeeksforGeeks
13 Oct, 2021 The Buffer.writeUInt16LE() method is used to write specified bytes in Little Endian format to the buffer object. Here, value should be a valid unsigned 16-bit integer. Syntax: Buffer.writeUInt16LE( value, offset ) Parameters: This method accept two parameters as mentioned above and described below: value: It is an integer value and that is to be written to the buffer. offset It is an integer value and it represents the number of bytes to skip before starting to write and the value of offset lies within the range 0 to buffer.length – 2 and its default value is 0. Return value: It returns an integer value the offset plus number of bytes written. Example 1: // Node.js program to demonstrate the//Buffer.writeUInt16LE() Methodconst buff = Buffer.allocUnsafe(4); buff.writeUInt16LE(0xdead, 0);console.log(buff); buff.writeUInt16LE(0xbeef, 2)console.log(buff); Output: <Buffer ad de 00 00> <Buffer ad de ef be> Example 2: // Node.js program to demonstrate the//Buffer.writeUInt16LE() Methodconst buff = Buffer.allocUnsafe(4); buff.writeUInt16LE(0xfeed, 0);console.log(buff); buff.writeUInt16LE(0xabcd, 2);console.log(buff); Output: <Buffer ed fe 00 00> <Buffer ed fe cd ab> Note: The above program will compile and run by using the node index.js command. Reference: https://nodejs.org/api/buffer.html#buffer_buf_writeuint16le_value_offset Node.js-Buffer-module Picked Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Node.js path.resolve() Method Node.js crypto.createCipheriv() Method Node.js CRUD Operations Using Mongoose and MongoDB Atlas Node.js fs.readdir() Method Express.js res.render() Function Express.js express.Router() Function Convert a string to an integer in JavaScript How to set the default value for an HTML <select> element ? Top 10 Angular Libraries For Web Developers How to create footer to stay at the bottom of a Web page?
[ { "code": null, "e": 24301, "s": 24273, "text": "\n13 Oct, 2021" }, { "code": null, "e": 24469, "s": 24301, "text": "The Buffer.writeUInt16LE() method is used to write specified bytes in Little Endian format to the buffer object. Here, value should be a valid unsigned 16-bit integer." }, { "code": null, "e": 24477, "s": 24469, "text": "Syntax:" }, { "code": null, "e": 24515, "s": 24477, "text": "Buffer.writeUInt16LE( value, offset )" }, { "code": null, "e": 24601, "s": 24515, "text": "Parameters: This method accept two parameters as mentioned above and described below:" }, { "code": null, "e": 24672, "s": 24601, "text": "value: It is an integer value and that is to be written to the buffer." }, { "code": null, "e": 24870, "s": 24672, "text": "offset It is an integer value and it represents the number of bytes to skip before starting to write and the value of offset lies within the range 0 to buffer.length – 2 and its default value is 0." }, { "code": null, "e": 24953, "s": 24870, "text": "Return value: It returns an integer value the offset plus number of bytes written." }, { "code": null, "e": 24964, "s": 24953, "text": "Example 1:" }, { "code": "// Node.js program to demonstrate the//Buffer.writeUInt16LE() Methodconst buff = Buffer.allocUnsafe(4); buff.writeUInt16LE(0xdead, 0);console.log(buff); buff.writeUInt16LE(0xbeef, 2)console.log(buff);", "e": 25167, "s": 24964, "text": null }, { "code": null, "e": 25175, "s": 25167, "text": "Output:" }, { "code": null, "e": 25219, "s": 25175, "text": "<Buffer ad de 00 00>\n<Buffer ad de ef be>\n\n" }, { "code": null, "e": 25230, "s": 25219, "text": "Example 2:" }, { "code": "// Node.js program to demonstrate the//Buffer.writeUInt16LE() Methodconst buff = Buffer.allocUnsafe(4); buff.writeUInt16LE(0xfeed, 0);console.log(buff); buff.writeUInt16LE(0xabcd, 2);console.log(buff);", "e": 25434, "s": 25230, "text": null }, { "code": null, "e": 25442, "s": 25434, "text": "Output:" }, { "code": null, "e": 25486, "s": 25442, "text": "<Buffer ed fe 00 00>\n<Buffer ed fe cd ab>\n " }, { "code": null, "e": 25567, "s": 25486, "text": "Note: The above program will compile and run by using the node index.js command." }, { "code": null, "e": 25651, "s": 25567, "text": "Reference: https://nodejs.org/api/buffer.html#buffer_buf_writeuint16le_value_offset" }, { "code": null, "e": 25673, "s": 25651, "text": "Node.js-Buffer-module" }, { "code": null, "e": 25680, "s": 25673, "text": "Picked" }, { "code": null, "e": 25688, "s": 25680, "text": "Node.js" }, { "code": null, "e": 25707, "s": 25688, "text": "Technical Scripter" }, { "code": null, "e": 25724, "s": 25707, "text": "Web Technologies" }, { "code": null, "e": 25822, "s": 25724, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25831, "s": 25822, "text": "Comments" }, { "code": null, "e": 25844, "s": 25831, "text": "Old Comments" }, { "code": null, "e": 25874, "s": 25844, "text": "Node.js path.resolve() Method" }, { "code": null, "e": 25913, "s": 25874, "text": "Node.js crypto.createCipheriv() Method" }, { "code": null, "e": 25970, "s": 25913, "text": "Node.js CRUD Operations Using Mongoose and MongoDB Atlas" }, { "code": null, "e": 25998, "s": 25970, "text": "Node.js fs.readdir() Method" }, { "code": null, "e": 26031, "s": 25998, "text": "Express.js res.render() Function" }, { "code": null, "e": 26068, "s": 26031, "text": "Express.js express.Router() Function" }, { "code": null, "e": 26113, "s": 26068, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26173, "s": 26113, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26217, "s": 26173, "text": "Top 10 Angular Libraries For Web Developers" } ]
Android | Creating a SeekBar - GeeksforGeeks
30 Nov, 2021 Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the right or left, the current value of the progress changes. SeekBar is used for forwarding or backwarding the songs, Video etc. In the setOnSeekBarChangeListener interface is used which provides three methods. onProgressChanged: In this method progress is changed and then according to this change the progress value can used in our logic.onStartTrackingTouch: In this method when the user has started dragging, then this method will be called automatically.onStopTrackingTouch: In this method, when the user stops dragging, then this method will called automatically. onProgressChanged: In this method progress is changed and then according to this change the progress value can used in our logic. onStartTrackingTouch: In this method when the user has started dragging, then this method will be called automatically. onStopTrackingTouch: In this method, when the user stops dragging, then this method will called automatically. Below are the steps for Creating SeekBar Android Application: Step1: Create a new project. After that, you will have java and XML file. Step2: Open your xml file and add a SeekBar and TextView for message as shown below, max attribute in SeekBar define the maximum it can take. Assign ID to SeekBar And TextView. Step3: Now, open up the activity java file and then define the SeekBar and TextView variable, use findViewById() to get the SeekBar and TextView. Step4: Performs seek bar change listener event which is used for getting the progress value. By using this event listener we get the value of Progress, and the progress is displayed by using a TextView, which will increase the size. Step5: Now run the app and touch the thumb and then Drag it, the Text size will increase automatically. The complete code of MainActivity.java or activity_main.xml of SeekBar is given below: activity_main.xml MainActivity.java <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/message_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="geeksforgeeks" android:textStyle="bold" android:textSize="20sp" android:layout_gravity="center"/> <SeekBar android:id="@+id/seekbar" android:layout_marginTop="400dp" android:layout_width="fill_parent" android:layout_height="wrap_content" android:max="150"/> </RelativeLayout> package org.geeksforgeeks.navedmalik.seekbar; // Import the librariesimport android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.SeekBar;import android.widget.TextView; public class MainActivity extends AppCompatActivity { // Define the global variable SeekBar seekbar; TextView Text_message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Binding the layout to the file setContentView(R.layout.activity_main); // use findViewById() to get the Button Text_message = (TextView)findViewById(R.id.message_id); seekbar = (SeekBar)findViewById(R.id.seekbar); // Get the progress value of the SeekBar // using setOnSeekBarChangeListener() method seekbar .setOnSeekBarChangeListener( new SeekBar .OnSeekBarChangeListener() { // When the progress value has changed @Override public void onProgressChanged( SeekBar seekBar, int progress, boolean fromUser) { // increment 1 in progress and // increase the textsize // with the value of progress message.setTextSize(progress + 1); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user touches the SeekBar } @Override public void onStopTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user // stops touching the SeekBar }Prograss }); }} vartika02 kalrap615 Android-Bars Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Broadcast Receiver in Android With Example Resource Raw Folder in Android Studio CardView in Android With Example Services in Android with Example Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java
[ { "code": null, "e": 26420, "s": 26392, "text": "\n30 Nov, 2021" }, { "code": null, "e": 26726, "s": 26420, "text": "Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the right or left, the current value of the progress changes. SeekBar is used for forwarding or backwarding the songs, Video etc. In the setOnSeekBarChangeListener interface is used which provides three methods." }, { "code": null, "e": 27085, "s": 26726, "text": "onProgressChanged: In this method progress is changed and then according to this change the progress value can used in our logic.onStartTrackingTouch: In this method when the user has started dragging, then this method will be called automatically.onStopTrackingTouch: In this method, when the user stops dragging, then this method will called automatically." }, { "code": null, "e": 27215, "s": 27085, "text": "onProgressChanged: In this method progress is changed and then according to this change the progress value can used in our logic." }, { "code": null, "e": 27335, "s": 27215, "text": "onStartTrackingTouch: In this method when the user has started dragging, then this method will be called automatically." }, { "code": null, "e": 27446, "s": 27335, "text": "onStopTrackingTouch: In this method, when the user stops dragging, then this method will called automatically." }, { "code": null, "e": 27508, "s": 27446, "text": "Below are the steps for Creating SeekBar Android Application:" }, { "code": null, "e": 27582, "s": 27508, "text": "Step1: Create a new project. After that, you will have java and XML file." }, { "code": null, "e": 27759, "s": 27582, "text": "Step2: Open your xml file and add a SeekBar and TextView for message as shown below, max attribute in SeekBar define the maximum it can take. Assign ID to SeekBar And TextView." }, { "code": null, "e": 27905, "s": 27759, "text": "Step3: Now, open up the activity java file and then define the SeekBar and TextView variable, use findViewById() to get the SeekBar and TextView." }, { "code": null, "e": 28138, "s": 27905, "text": "Step4: Performs seek bar change listener event which is used for getting the progress value. By using this event listener we get the value of Progress, and the progress is displayed by using a TextView, which will increase the size." }, { "code": null, "e": 28242, "s": 28138, "text": "Step5: Now run the app and touch the thumb and then Drag it, the Text size will increase automatically." }, { "code": null, "e": 28329, "s": 28242, "text": "The complete code of MainActivity.java or activity_main.xml of SeekBar is given below:" }, { "code": null, "e": 28347, "s": 28329, "text": "activity_main.xml" }, { "code": null, "e": 28365, "s": 28347, "text": "MainActivity.java" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:id=\"@+id/message_id\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:text=\"geeksforgeeks\" android:textStyle=\"bold\" android:textSize=\"20sp\" android:layout_gravity=\"center\"/> <SeekBar android:id=\"@+id/seekbar\" android:layout_marginTop=\"400dp\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:max=\"150\"/> </RelativeLayout>", "e": 29234, "s": 28365, "text": null }, { "code": "package org.geeksforgeeks.navedmalik.seekbar; // Import the librariesimport android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.widget.SeekBar;import android.widget.TextView; public class MainActivity extends AppCompatActivity { // Define the global variable SeekBar seekbar; TextView Text_message; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Binding the layout to the file setContentView(R.layout.activity_main); // use findViewById() to get the Button Text_message = (TextView)findViewById(R.id.message_id); seekbar = (SeekBar)findViewById(R.id.seekbar); // Get the progress value of the SeekBar // using setOnSeekBarChangeListener() method seekbar .setOnSeekBarChangeListener( new SeekBar .OnSeekBarChangeListener() { // When the progress value has changed @Override public void onProgressChanged( SeekBar seekBar, int progress, boolean fromUser) { // increment 1 in progress and // increase the textsize // with the value of progress message.setTextSize(progress + 1); } @Override public void onStartTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user touches the SeekBar } @Override public void onStopTrackingTouch(SeekBar seekBar) { // This method will automatically // called when the user // stops touching the SeekBar }Prograss }); }}", "e": 31421, "s": 29234, "text": null }, { "code": null, "e": 31431, "s": 31421, "text": "vartika02" }, { "code": null, "e": 31441, "s": 31431, "text": "kalrap615" }, { "code": null, "e": 31454, "s": 31441, "text": "Android-Bars" }, { "code": null, "e": 31462, "s": 31454, "text": "Android" }, { "code": null, "e": 31467, "s": 31462, "text": "Java" }, { "code": null, "e": 31472, "s": 31467, "text": "Java" }, { "code": null, "e": 31480, "s": 31472, "text": "Android" }, { "code": null, "e": 31578, "s": 31480, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31636, "s": 31578, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 31679, "s": 31636, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 31717, "s": 31679, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 31750, "s": 31717, "text": "CardView in Android With Example" }, { "code": null, "e": 31783, "s": 31750, "text": "Services in Android with Example" }, { "code": null, "e": 31798, "s": 31783, "text": "Arrays in Java" }, { "code": null, "e": 31842, "s": 31798, "text": "Split() String method in Java with examples" }, { "code": null, "e": 31864, "s": 31842, "text": "For-each loop in Java" }, { "code": null, "e": 31879, "s": 31864, "text": "Stream In Java" } ]
Sum of all differences between Maximum and Minimum of increasing Subarrays - GeeksforGeeks
01 Apr, 2021 Given an array arr[] consisting of N integers, the task is to find the sum of the differences between maximum and minimum element of all strictly increasing subarrays from the given array. All subarrays need to be in their longest possible form, i.e. if a subarray [i, j] form a strictly increasing subarray, then it should be considered as a whole and not [i, k] and [k+1, j] for some i <= k <= j. A subarray is said to be strictly increasing if for every ith index in the subarray, except the last index, arr[i+1] > arr[i] Examples: Input: arr[ ] = {7, 1, 5, 3, 6, 4} Output: 7 Explanation: All possible increasing subarrays are {7}, {1, 5}, {3, 6} and {4} Therefore, sum = (7 – 7) + (5 – 1) + (6 – 3) + (4 – 4) = 7 Input: arr[ ] = {1, 2, 3, 4, 5, 2} Output: 4 Explanation: All possible increasing subarrays are {1, 2, 3, 4, 5} and {2} Therefore, sum = (5 – 1) + (2 – 2) = 4 Approach: Follow the steps below to solve the problem: Traverse the array and for each iteration, find the rightmost element up to which the current subarray is strictly increasing. Let i be the starting element of the current subarray, and j index up to which the current subarray is strictly increasing. The maximum and minimum values of this subarray will be arr[j] and arr[i] respectively. So, add (arr[j] – arr[i]) to the sum. Continue iterating for the next subarray from (j+1)th index. After complete traversal of the array, print the final value of sum. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to find the sum of// differences of maximum and minimum// of strictly increasing subarrays #include <bits/stdc++.h>using namespace std; // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysint sum_of_differences(int arr[], int N){ // Stores the sum int sum = 0; int i, j, flag; // Traverse the array for (i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for (j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver Codeint main(){ int arr[] = { 6, 1, 2, 5, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << sum_of_differences(arr, N); return 0;} // Java program to find the sum of// differences of maximum and minimum// of strictly increasing subarraysclass GFG{ // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysstatic int sum_of_differences(int arr[], int N){ // Stores the sum int sum = 0; int i, j, flag; // Traverse the array for(i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for(j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver Codepublic static void main (String []args){ int arr[] = { 6, 1, 2, 5, 3, 4 }; int N = arr.length; System.out.print(sum_of_differences(arr, N));}} // This code is contributed by chitranayal # Python3 program to find the sum of# differences of maximum and minimum# of strictly increasing subarrays # Function to calculate and return the# sum of differences of maximum and# minimum of strictly increasing subarraysdef sum_of_differences(arr, N): # Stores the sum sum = 0 # Traverse the array i = 0 while(i < N - 1): if arr[i] < arr[i + 1]: flag = 0 for j in range(i + 1, N - 1): # If last element of the # increasing sub-array is found if arr[j] >= arr[j + 1]: # Update sum sum += (arr[j] - arr[i]) i = j flag = 1 break # If the last element of the array # is reached if flag == 0 and arr[i] < arr[N - 1]: # Update sum sum += (arr[N - 1] - arr[i]) break i += 1 # Return the sum return sum # Driver Codearr = [ 6, 1, 2, 5, 3, 4 ] N = len(arr) print(sum_of_differences(arr, N)) # This code is contributed by yatinagg // C# program to find the sum of// differences of maximum and minimum// of strictly increasing subarraysusing System;class GFG{ // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysstatic int sum_of_differences(int []arr, int N){ // Stores the sum int sum = 0; int i, j, flag; // Traverse the array for(i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for(j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver Codepublic static void Main (string []args){ int []arr = { 6, 1, 2, 5, 3, 4 }; int N = arr.Length; Console.Write(sum_of_differences(arr, N));}} // This code is contributed by rock_cool <script> // Javascript program to find the sum of// differences of maximum and minimum// of strictly increasing subarrays // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysfunction sum_of_differences(arr, N){ // Stores the sum let sum = 0; let i, j, flag; // Traverse the array for(i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for(j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver codelet arr = [ 6, 1, 2, 5, 3, 4 ]; let N = arr.length; document.write(sum_of_differences(arr, N)); // This code is contributed by divyesh072019 </script> 5 Time Complexity: O(N) Auxiliary Space: O(1) yatinagg ukasp rock_cool divyesh072019 subarray Arrays Mathematical Arrays Mathematical 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 Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26339, "s": 26311, "text": "\n01 Apr, 2021" }, { "code": null, "e": 26738, "s": 26339, "text": "Given an array arr[] consisting of N integers, the task is to find the sum of the differences between maximum and minimum element of all strictly increasing subarrays from the given array. All subarrays need to be in their longest possible form, i.e. if a subarray [i, j] form a strictly increasing subarray, then it should be considered as a whole and not [i, k] and [k+1, j] for some i <= k <= j." }, { "code": null, "e": 26866, "s": 26738, "text": "A subarray is said to be strictly increasing if for every ith index in the subarray, except the last index, arr[i+1] > arr[i] " }, { "code": null, "e": 26878, "s": 26866, "text": "Examples: " }, { "code": null, "e": 27061, "s": 26878, "text": "Input: arr[ ] = {7, 1, 5, 3, 6, 4} Output: 7 Explanation: All possible increasing subarrays are {7}, {1, 5}, {3, 6} and {4} Therefore, sum = (7 – 7) + (5 – 1) + (6 – 3) + (4 – 4) = 7" }, { "code": null, "e": 27222, "s": 27061, "text": "Input: arr[ ] = {1, 2, 3, 4, 5, 2} Output: 4 Explanation: All possible increasing subarrays are {1, 2, 3, 4, 5} and {2} Therefore, sum = (5 – 1) + (2 – 2) = 4 " }, { "code": null, "e": 27279, "s": 27222, "text": "Approach: Follow the steps below to solve the problem: " }, { "code": null, "e": 27406, "s": 27279, "text": "Traverse the array and for each iteration, find the rightmost element up to which the current subarray is strictly increasing." }, { "code": null, "e": 27656, "s": 27406, "text": "Let i be the starting element of the current subarray, and j index up to which the current subarray is strictly increasing. The maximum and minimum values of this subarray will be arr[j] and arr[i] respectively. So, add (arr[j] – arr[i]) to the sum." }, { "code": null, "e": 27717, "s": 27656, "text": "Continue iterating for the next subarray from (j+1)th index." }, { "code": null, "e": 27786, "s": 27717, "text": "After complete traversal of the array, print the final value of sum." }, { "code": null, "e": 27838, "s": 27786, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27842, "s": 27838, "text": "C++" }, { "code": null, "e": 27847, "s": 27842, "text": "Java" }, { "code": null, "e": 27855, "s": 27847, "text": "Python3" }, { "code": null, "e": 27858, "s": 27855, "text": "C#" }, { "code": null, "e": 27869, "s": 27858, "text": "Javascript" }, { "code": "// C++ Program to find the sum of// differences of maximum and minimum// of strictly increasing subarrays #include <bits/stdc++.h>using namespace std; // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysint sum_of_differences(int arr[], int N){ // Stores the sum int sum = 0; int i, j, flag; // Traverse the array for (i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for (j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver Codeint main(){ int arr[] = { 6, 1, 2, 5, 3, 4 }; int N = sizeof(arr) / sizeof(arr[0]); cout << sum_of_differences(arr, N); return 0;}", "e": 29173, "s": 27869, "text": null }, { "code": "// Java program to find the sum of// differences of maximum and minimum// of strictly increasing subarraysclass GFG{ // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysstatic int sum_of_differences(int arr[], int N){ // Stores the sum int sum = 0; int i, j, flag; // Traverse the array for(i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for(j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver Codepublic static void main (String []args){ int arr[] = { 6, 1, 2, 5, 3, 4 }; int N = arr.length; System.out.print(sum_of_differences(arr, N));}} // This code is contributed by chitranayal", "e": 30566, "s": 29173, "text": null }, { "code": "# Python3 program to find the sum of# differences of maximum and minimum# of strictly increasing subarrays # Function to calculate and return the# sum of differences of maximum and# minimum of strictly increasing subarraysdef sum_of_differences(arr, N): # Stores the sum sum = 0 # Traverse the array i = 0 while(i < N - 1): if arr[i] < arr[i + 1]: flag = 0 for j in range(i + 1, N - 1): # If last element of the # increasing sub-array is found if arr[j] >= arr[j + 1]: # Update sum sum += (arr[j] - arr[i]) i = j flag = 1 break # If the last element of the array # is reached if flag == 0 and arr[i] < arr[N - 1]: # Update sum sum += (arr[N - 1] - arr[i]) break i += 1 # Return the sum return sum # Driver Codearr = [ 6, 1, 2, 5, 3, 4 ] N = len(arr) print(sum_of_differences(arr, N)) # This code is contributed by yatinagg", "e": 31751, "s": 30566, "text": null }, { "code": "// C# program to find the sum of// differences of maximum and minimum// of strictly increasing subarraysusing System;class GFG{ // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysstatic int sum_of_differences(int []arr, int N){ // Stores the sum int sum = 0; int i, j, flag; // Traverse the array for(i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for(j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver Codepublic static void Main (string []args){ int []arr = { 6, 1, 2, 5, 3, 4 }; int N = arr.Length; Console.Write(sum_of_differences(arr, N));}} // This code is contributed by rock_cool", "e": 33166, "s": 31751, "text": null }, { "code": "<script> // Javascript program to find the sum of// differences of maximum and minimum// of strictly increasing subarrays // Function to calculate and return the// sum of differences of maximum and// minimum of strictly increasing subarraysfunction sum_of_differences(arr, N){ // Stores the sum let sum = 0; let i, j, flag; // Traverse the array for(i = 0; i < N - 1; i++) { if (arr[i] < arr[i + 1]) { flag = 0; for(j = i + 1; j < N - 1; j++) { // If last element of the // increasing sub-array is found if (arr[j] >= arr[j + 1]) { // Update sum sum += (arr[j] - arr[i]); i = j; flag = 1; break; } } // If the last element of the array // is reached if (flag == 0 && arr[i] < arr[N - 1]) { // Update sum sum += (arr[N - 1] - arr[i]); break; } } } // Return the sum return sum;} // Driver codelet arr = [ 6, 1, 2, 5, 3, 4 ]; let N = arr.length; document.write(sum_of_differences(arr, N)); // This code is contributed by divyesh072019 </script>", "e": 34537, "s": 33166, "text": null }, { "code": null, "e": 34539, "s": 34537, "text": "5" }, { "code": null, "e": 34586, "s": 34541, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 34595, "s": 34586, "text": "yatinagg" }, { "code": null, "e": 34601, "s": 34595, "text": "ukasp" }, { "code": null, "e": 34611, "s": 34601, "text": "rock_cool" }, { "code": null, "e": 34625, "s": 34611, "text": "divyesh072019" }, { "code": null, "e": 34634, "s": 34625, "text": "subarray" }, { "code": null, "e": 34641, "s": 34634, "text": "Arrays" }, { "code": null, "e": 34654, "s": 34641, "text": "Mathematical" }, { "code": null, "e": 34661, "s": 34654, "text": "Arrays" }, { "code": null, "e": 34674, "s": 34661, "text": "Mathematical" }, { "code": null, "e": 34772, "s": 34674, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34840, "s": 34772, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 34884, "s": 34840, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 34932, "s": 34884, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 34955, "s": 34932, "text": "Introduction to Arrays" }, { "code": null, "e": 34987, "s": 34955, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 35017, "s": 34987, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 35032, "s": 35017, "text": "C++ Data Types" }, { "code": null, "e": 35092, "s": 35032, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 35135, "s": 35092, "text": "Set in C++ Standard Template Library (STL)" } ]
MySQL Tryit Editor v1.0
SELECT IFNULL("Hello", "W3Schools.com"); ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 41, "s": 0, "text": "SELECT IFNULL(\"Hello\", \"W3Schools.com\");" }, { "code": null, "e": 43, "s": 41, "text": "​" }, { "code": null, "e": 115, "s": 52, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 175, "s": 115, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 243, "s": 175, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 281, "s": 243, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 366, "s": 281, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 540, "s": 366, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 591, "s": 540, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 659, "s": 591, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 830, "s": 659, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 930, "s": 830, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 980, "s": 930, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Java JDOM Parser - Parse XML Document
Following are the steps used while parsing a document using JDOM Parser. Import XML-related packages. Create a SAXBuilder Create a Document from a file or stream Extract the root element Examine attributes Examine sub-elements import java.io.*; import java.util.*; import org.jdom2.*; SAXBuilder saxBuilder = new SAXBuilder(); File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); Element classElement = document.getRootElement(); //returns specific attribute getAttribute("attributeName"); //returns a list of subelements of specified name getChildren("subelementName"); //returns a list of all child nodes getChildren(); //returns first child node getChild("subelementName"); Here is the input xml file we need to parse − <?xml version = "1.0"?> <class> <student rollno = "393"> <firstname>dinkar</firstname> <lastname>kad</lastname> <nickname>dinkar</nickname> <marks>85</marks> </student> <student rollno = "493"> <firstname>Vaneet</firstname> <lastname>Gupta</lastname> <nickname>vinni</nickname> <marks>95</marks> </student> <student rollno = "593"> <firstname>jasvir</firstname> <lastname>singn</lastname> <nickname>jazz</nickname> <marks>90</marks> </student> </class> import java.io.File; import java.io.IOException; import java.util.List; import org.jdom2.Attribute; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.JDOMException; import org.jdom2.input.SAXBuilder; public class JDomParserDemo { public static void main(String[] args) { try { File inputFile = new File("input.txt"); SAXBuilder saxBuilder = new SAXBuilder(); Document document = saxBuilder.build(inputFile); System.out.println("Root element :" + document.getRootElement().getName()); Element classElement = document.getRootElement(); List<Element> studentList = classElement.getChildren(); System.out.println("----------------------------"); for (int temp = 0; temp < studentList.size(); temp++) { Element student = studentList.get(temp); System.out.println("\nCurrent Element :" + student.getName()); Attribute attribute = student.getAttribute("rollno"); System.out.println("Student roll no : " + attribute.getValue() ); System.out.println("First Name : " + student.getChild("firstname").getText()); System.out.println("Last Name : " + student.getChild("lastname").getText()); System.out.println("Nick Name : " + student.getChild("nickname").getText()); System.out.println("Marks : " + student.getChild("marks").getText()); } } catch(JDOMException e) { e.printStackTrace(); } catch(IOException ioe) { ioe.printStackTrace(); } } } This would produce the following result − Root element :class ---------------------------- Current Element :student Student roll no : 393 First Name : dinkar Last Name : kad Nick Name : dinkar Marks : 85 Current Element :student Student roll no : 493 First Name : Vaneet Last Name : Gupta Nick Name : vinni Marks : 95 Current Element :student Student roll no : 593 First Name : jasvir Last Name : singn Nick Name : jazz Marks : 90 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2396, "s": 2323, "text": "Following are the steps used while parsing a document using JDOM Parser." }, { "code": null, "e": 2425, "s": 2396, "text": "Import XML-related packages." }, { "code": null, "e": 2445, "s": 2425, "text": "Create a SAXBuilder" }, { "code": null, "e": 2485, "s": 2445, "text": "Create a Document from a file or stream" }, { "code": null, "e": 2510, "s": 2485, "text": "Extract the root element" }, { "code": null, "e": 2529, "s": 2510, "text": "Examine attributes" }, { "code": null, "e": 2550, "s": 2529, "text": "Examine sub-elements" }, { "code": null, "e": 2608, "s": 2550, "text": "import java.io.*;\nimport java.util.*;\nimport org.jdom2.*;" }, { "code": null, "e": 2650, "s": 2608, "text": "SAXBuilder saxBuilder = new SAXBuilder();" }, { "code": null, "e": 2781, "s": 2650, "text": "File inputFile = new File(\"input.txt\");\nSAXBuilder saxBuilder = new SAXBuilder();\nDocument document = saxBuilder.build(inputFile);" }, { "code": null, "e": 2831, "s": 2781, "text": "Element classElement = document.getRootElement();" }, { "code": null, "e": 2892, "s": 2831, "text": "//returns specific attribute\ngetAttribute(\"attributeName\"); " }, { "code": null, "e": 3084, "s": 2892, "text": "//returns a list of subelements of specified name\ngetChildren(\"subelementName\"); \n\n//returns a list of all child nodes\ngetChildren(); \n\n//returns first child node\ngetChild(\"subelementName\"); " }, { "code": null, "e": 3130, "s": 3084, "text": "Here is the input xml file we need to parse −" }, { "code": null, "e": 3681, "s": 3130, "text": "<?xml version = \"1.0\"?>\n<class>\n <student rollno = \"393\">\n <firstname>dinkar</firstname>\n <lastname>kad</lastname>\n <nickname>dinkar</nickname>\n <marks>85</marks>\n </student>\n \n <student rollno = \"493\">\n <firstname>Vaneet</firstname>\n <lastname>Gupta</lastname>\n <nickname>vinni</nickname>\n <marks>95</marks>\n </student>\n \n <student rollno = \"593\">\n <firstname>jasvir</firstname>\n <lastname>singn</lastname>\n <nickname>jazz</nickname>\n <marks>90</marks>\n </student>\n</class>" }, { "code": null, "e": 5361, "s": 3681, "text": "import java.io.File;\nimport java.io.IOException;\nimport java.util.List;\n\nimport org.jdom2.Attribute;\nimport org.jdom2.Document;\nimport org.jdom2.Element;\nimport org.jdom2.JDOMException;\nimport org.jdom2.input.SAXBuilder;\n\n\npublic class JDomParserDemo {\n\n public static void main(String[] args) {\n\n try {\n File inputFile = new File(\"input.txt\");\n SAXBuilder saxBuilder = new SAXBuilder();\n Document document = saxBuilder.build(inputFile);\n System.out.println(\"Root element :\" + document.getRootElement().getName());\n Element classElement = document.getRootElement();\n\n List<Element> studentList = classElement.getChildren();\n System.out.println(\"----------------------------\");\n\n for (int temp = 0; temp < studentList.size(); temp++) { \n Element student = studentList.get(temp);\n System.out.println(\"\\nCurrent Element :\" \n + student.getName());\n Attribute attribute = student.getAttribute(\"rollno\");\n System.out.println(\"Student roll no : \" \n + attribute.getValue() );\n System.out.println(\"First Name : \"\n + student.getChild(\"firstname\").getText());\n System.out.println(\"Last Name : \"\n + student.getChild(\"lastname\").getText());\n System.out.println(\"Nick Name : \"\n + student.getChild(\"nickname\").getText());\n System.out.println(\"Marks : \"\n + student.getChild(\"marks\").getText());\n }\n } catch(JDOMException e) {\n e.printStackTrace();\n } catch(IOException ioe) {\n ioe.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 5403, "s": 5361, "text": "This would produce the following result −" }, { "code": null, "e": 5796, "s": 5403, "text": "Root element :class\n----------------------------\n\nCurrent Element :student\nStudent roll no : 393\nFirst Name : dinkar\nLast Name : kad\nNick Name : dinkar\nMarks : 85\n\nCurrent Element :student\nStudent roll no : 493\nFirst Name : Vaneet\nLast Name : Gupta\nNick Name : vinni\nMarks : 95\n\nCurrent Element :student\nStudent roll no : 593\nFirst Name : jasvir\nLast Name : singn\nNick Name : jazz\nMarks : 90\n" }, { "code": null, "e": 5829, "s": 5796, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5845, "s": 5829, "text": " Malhar Lathkar" }, { "code": null, "e": 5878, "s": 5845, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5894, "s": 5878, "text": " Malhar Lathkar" }, { "code": null, "e": 5929, "s": 5894, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5943, "s": 5929, "text": " Anadi Sharma" }, { "code": null, "e": 5977, "s": 5943, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5991, "s": 5977, "text": " Tushar Kale" }, { "code": null, "e": 6028, "s": 5991, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 6043, "s": 6028, "text": " Monica Mittal" }, { "code": null, "e": 6076, "s": 6043, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 6095, "s": 6076, "text": " Arnab Chakraborty" }, { "code": null, "e": 6102, "s": 6095, "text": " Print" }, { "code": null, "e": 6113, "s": 6102, "text": " Add Notes" } ]
How to read a CSV file and store the values into an array in C#?
A CSV file is a comma-separated file, that is used to store data in an organized way. It usually stores data in tabular form. Most of the business organizations store their data in CSV files. In C#, StreamReader class is used to deal with the files. It opens, reads and helps in performing other functions to different types of files. We can also perform different operations on a CSV file while using this class. OpenRead() method is used to open a CSV file and ReadLine() method is used to read its contents. OpenRead() method is used to open a CSV file and ReadLine() method is used to read Data.csv A,B,C class Program{ public static void Main(){ string filePath = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp\Data.csv"; StreamReader reader = null; if (File.Exists(filePath)){ reader = new StreamReader(File.OpenRead(filePath)); List<string> listA = new List<string>(); while (!reader.EndOfStream){ var line = reader.ReadLine(); var values = line.Split(','); foreach (var item in values){ listA.Add(item); } foreach (var coloumn1 in listA){ Console.WriteLine(coloumn1); } } } else { Console.WriteLine("File doesn't exist"); } Console.ReadLine(); } } A B C
[ { "code": null, "e": 1254, "s": 1062, "text": "A CSV file is a comma-separated file, that is used to store data in an organized way. It\nusually stores data in tabular form. Most of the business organizations store their data\nin CSV files." }, { "code": null, "e": 1476, "s": 1254, "text": "In C#, StreamReader class is used to deal with the files. It opens, reads and helps in\nperforming other functions to different types of files. We can also perform different\noperations on a CSV file while using this class." }, { "code": null, "e": 1573, "s": 1476, "text": "OpenRead() method is used to open a CSV file and ReadLine() method is used to read\nits contents." }, { "code": null, "e": 1656, "s": 1573, "text": "OpenRead() method is used to open a CSV file and ReadLine() method is used to read" }, { "code": null, "e": 1671, "s": 1656, "text": "Data.csv\nA,B,C" }, { "code": null, "e": 2414, "s": 1671, "text": "class Program{\n public static void Main(){\n string filePath =\n @\"C:\\Users\\Koushik\\Desktop\\Questions\\ConsoleApp\\Data.csv\";\n StreamReader reader = null;\n if (File.Exists(filePath)){\n reader = new StreamReader(File.OpenRead(filePath));\n List<string> listA = new List<string>();\n while (!reader.EndOfStream){\n var line = reader.ReadLine();\n var values = line.Split(',');\n foreach (var item in values){\n listA.Add(item);\n }\n foreach (var coloumn1 in listA){\n Console.WriteLine(coloumn1);\n }\n }\n } else {\n Console.WriteLine(\"File doesn't exist\");\n }\n Console.ReadLine();\n }\n}" }, { "code": null, "e": 2420, "s": 2414, "text": "A\nB\nC" } ]
DateTime.IsLeapYear() Method in C#
The DateTime.IsLeapYear() method in C# is used to check whether the specified year is a leap year. The return value is a boolean, with TRUE if the year is a leap year, else FALSE. Following is the syntax − public static bool IsLeapYear (int y); Above, y is the year to be checked, 2010, 2016, 2019, etc. Let us now see an example to implement the DateTime.IsLeapYear() method − using System; public class Demo { public static void Main() { int year = 2019; Console.WriteLine("Year = "+year); if (DateTime.IsLeapYear(year)){ Console.WriteLine("Leap Year!"); } else { Console.WriteLine("Not a Leap Year!"); } } } This will produce the following output − Year = 2019 Not a Leap Year! Let us now see another example to implement the DateTime.IsLeapYear() method. Here, we will add an out of range year − using System; public class Demo { public static void Main() { int year = 101910; Console.WriteLine("Year = "+year); if (DateTime.IsLeapYear(year)){ Console.WriteLine("Leap Year!"); } else { Console.WriteLine("Not a Leap Year!"); } } } This will produce the following output i.e. error will get generated. The Stack Trace would print the same error as shown below − Year = 101910 Run-time exception (line 11): Year must be between 1 and 9999. Parameter name: year Stack Trace: [System.ArgumentOutOfRangeException: Year must be between 1 and 9999. Parameter name: year] at System.DateTime.IsLeapYear(Int32 year) at Demo.Main() :line 11
[ { "code": null, "e": 1242, "s": 1062, "text": "The DateTime.IsLeapYear() method in C# is used to check whether the specified year is a leap year. The return value is a boolean, with TRUE if the year is a leap year, else FALSE." }, { "code": null, "e": 1268, "s": 1242, "text": "Following is the syntax −" }, { "code": null, "e": 1307, "s": 1268, "text": "public static bool IsLeapYear (int y);" }, { "code": null, "e": 1366, "s": 1307, "text": "Above, y is the year to be checked, 2010, 2016, 2019, etc." }, { "code": null, "e": 1440, "s": 1366, "text": "Let us now see an example to implement the DateTime.IsLeapYear() method −" }, { "code": null, "e": 1727, "s": 1440, "text": "using System;\npublic class Demo {\n public static void Main() {\n int year = 2019;\n Console.WriteLine(\"Year = \"+year);\n if (DateTime.IsLeapYear(year)){\n Console.WriteLine(\"Leap Year!\");\n } else {\n Console.WriteLine(\"Not a Leap Year!\");\n }\n }\n}" }, { "code": null, "e": 1768, "s": 1727, "text": "This will produce the following output −" }, { "code": null, "e": 1797, "s": 1768, "text": "Year = 2019\nNot a Leap Year!" }, { "code": null, "e": 1916, "s": 1797, "text": "Let us now see another example to implement the DateTime.IsLeapYear() method. Here, we will add an out of range year −" }, { "code": null, "e": 2205, "s": 1916, "text": "using System;\npublic class Demo {\n public static void Main() {\n int year = 101910;\n Console.WriteLine(\"Year = \"+year);\n if (DateTime.IsLeapYear(year)){\n Console.WriteLine(\"Leap Year!\");\n } else {\n Console.WriteLine(\"Not a Leap Year!\");\n }\n }\n}" }, { "code": null, "e": 2335, "s": 2205, "text": "This will produce the following output i.e. error will get generated. The Stack Trace would print the same error as shown below −" }, { "code": null, "e": 2604, "s": 2335, "text": "Year = 101910\nRun-time exception (line 11): Year must be between 1 and 9999.\nParameter name: year\nStack Trace:\n[System.ArgumentOutOfRangeException: Year must be between 1 and 9999.\nParameter name: year]\nat System.DateTime.IsLeapYear(Int32 year) at Demo.Main() :line 11" } ]
Java Program to find largest element in an array - GeeksforGeeks
13 Jun, 2020 Given an array, find the largest element in it. Input : arr[] = {10, 20, 4} Output : 20 Input : arr[] = {20, 10, 20, 4, 100} Output : 100 Method 1: Iterative Way // Java Program to find maximum in arr[] class Test{ static int arr[] = {10, 324, 45, 90, 9808}; // Method to find maximum in arr[] static int largest() { int i; // Initialize maximum element int max = arr[0]; // Traverse array elements from second and // compare every element with current max for (i = 1; i < arr.length; i++) if (arr[i] > max) max = arr[i]; return max; } // Driver method public static void main(String[] args) { System.out.println("Largest in given array is " + largest()); } } Output: Largest in given array is 9808 Method 2: Java 8 StreamYou can simply use the new Java 8 Streams but you have to work with int. import java.util.Arrays; public class GFG { public static void main(String[] args){ int arr[] = {10, 324, 45, 90, 9808}; int max = Arrays.stream(arr).max().getAsInt(); System.out.println("Largest in given array is " +max); } } Output: Largest in given array is 9808 Method 3 : (Sorting) // Java program to find maximum in // arr[] of size n import java .io.*; import java.util.*; class GFG { // returns maximum in arr[] of size n static int largest(int []arr, int n) { Arrays.sort(arr); return arr[n - 1]; } // Driver code static public void main (String[] args) { int []arr = {10, 324, 45, 90, 9808}; int n = arr.length; System.out.println(largest(arr, n)); } } Please refer complete article on Program to find largest element in an array for more details! 29AjayKumar Java Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Java Programming Examples How to Iterate HashMap in Java? Iterate through List in Java Java Program to Remove Duplicate Elements From the Array Factory method design pattern in Java Min Heap in Java Java program to count the occurrence of each character in a string using Hashmap Iterate Over the Characters of a String in Java How to Get Elements By Index from HashSet in Java? Sorting in Java
[ { "code": null, "e": 24952, "s": 24924, "text": "\n13 Jun, 2020" }, { "code": null, "e": 25000, "s": 24952, "text": "Given an array, find the largest element in it." }, { "code": null, "e": 25092, "s": 25000, "text": "Input : arr[] = {10, 20, 4}\nOutput : 20\n\nInput : arr[] = {20, 10, 20, 4, 100}\nOutput : 100\n" }, { "code": null, "e": 25116, "s": 25092, "text": "Method 1: Iterative Way" }, { "code": "// Java Program to find maximum in arr[] class Test{ static int arr[] = {10, 324, 45, 90, 9808}; // Method to find maximum in arr[] static int largest() { int i; // Initialize maximum element int max = arr[0]; // Traverse array elements from second and // compare every element with current max for (i = 1; i < arr.length; i++) if (arr[i] > max) max = arr[i]; return max; } // Driver method public static void main(String[] args) { System.out.println(\"Largest in given array is \" + largest()); } }", "e": 25789, "s": 25116, "text": null }, { "code": null, "e": 25797, "s": 25789, "text": "Output:" }, { "code": null, "e": 25829, "s": 25797, "text": "Largest in given array is 9808\n" }, { "code": null, "e": 25925, "s": 25829, "text": "Method 2: Java 8 StreamYou can simply use the new Java 8 Streams but you have to work with int." }, { "code": "import java.util.Arrays; public class GFG { public static void main(String[] args){ int arr[] = {10, 324, 45, 90, 9808}; int max = Arrays.stream(arr).max().getAsInt(); System.out.println(\"Largest in given array is \" +max); } }", "e": 26181, "s": 25925, "text": null }, { "code": null, "e": 26189, "s": 26181, "text": "Output:" }, { "code": null, "e": 26221, "s": 26189, "text": "Largest in given array is 9808\n" }, { "code": null, "e": 26242, "s": 26221, "text": "Method 3 : (Sorting)" }, { "code": "// Java program to find maximum in // arr[] of size n import java .io.*; import java.util.*; class GFG { // returns maximum in arr[] of size n static int largest(int []arr, int n) { Arrays.sort(arr); return arr[n - 1]; } // Driver code static public void main (String[] args) { int []arr = {10, 324, 45, 90, 9808}; int n = arr.length; System.out.println(largest(arr, n)); } } ", "e": 26753, "s": 26242, "text": null }, { "code": null, "e": 26848, "s": 26753, "text": "Please refer complete article on Program to find largest element in an array for more details!" }, { "code": null, "e": 26860, "s": 26848, "text": "29AjayKumar" }, { "code": null, "e": 26874, "s": 26860, "text": "Java Programs" }, { "code": null, "e": 26972, "s": 26874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26981, "s": 26972, "text": "Comments" }, { "code": null, "e": 26994, "s": 26981, "text": "Old Comments" }, { "code": null, "e": 27020, "s": 26994, "text": "Java Programming Examples" }, { "code": null, "e": 27052, "s": 27020, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 27081, "s": 27052, "text": "Iterate through List in Java" }, { "code": null, "e": 27138, "s": 27081, "text": "Java Program to Remove Duplicate Elements From the Array" }, { "code": null, "e": 27176, "s": 27138, "text": "Factory method design pattern in Java" }, { "code": null, "e": 27193, "s": 27176, "text": "Min Heap in Java" }, { "code": null, "e": 27274, "s": 27193, "text": "Java program to count the occurrence of each character in a string using Hashmap" }, { "code": null, "e": 27322, "s": 27274, "text": "Iterate Over the Characters of a String in Java" }, { "code": null, "e": 27373, "s": 27322, "text": "How to Get Elements By Index from HashSet in Java?" } ]
Convert Tuple to integer in Python
When it is required to convert a tuple into an integer, the lambda function and the 'reduce' function can be used. Anonymous function is a function which is defined without a name. The reduce function takes two parameters- a function and a sequence, where it applies the function to all the elements of the list/sequence. It is present in the 'functools' module. In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it. Below is a demonstration of the same − Live Demo import functools my_tuple_1 = (23, 45, 12, 56, 78, 0) print("The first tuple is : ") print(my_tuple_1) my_result = functools.reduce(lambda sub, elem: sub * 10 + elem, my_tuple_1) print("After converting tuple to integer, it is ") print(my_result) The first tuple is : (23, 45, 12, 56, 78, 0) After converting tuple to integer, it is 2768380 The required packages are downloaded. A tuple is defined, and is displayed on the console. The reduce function is used, to which the lambda, and the tuple are passed as arguments. The lambda function multiples every element in the tuple with 10 and adds the previous element to it. This operation's data is stored in a variable. This variable is the output that is displayed on the console.
[ { "code": null, "e": 1177, "s": 1062, "text": "When it is required to convert a tuple into an integer, the lambda function and the 'reduce' function can be used." }, { "code": null, "e": 1425, "s": 1177, "text": "Anonymous function is a function which is defined without a name. The reduce function takes two parameters- a function and a sequence, where it applies the function to all the elements of the list/sequence. It is present in the 'functools' module." }, { "code": null, "e": 1680, "s": 1425, "text": "In general, functions in Python are defined using 'def' keyword, but anonymous function is defined with the help of 'lambda' keyword. It takes a single expression, but can take any number of arguments. It uses the expression and returns the result of it." }, { "code": null, "e": 1719, "s": 1680, "text": "Below is a demonstration of the same −" }, { "code": null, "e": 1729, "s": 1719, "text": "Live Demo" }, { "code": null, "e": 1979, "s": 1729, "text": "import functools\nmy_tuple_1 = (23, 45, 12, 56, 78, 0)\n\nprint(\"The first tuple is : \")\nprint(my_tuple_1)\n\nmy_result = functools.reduce(lambda sub, elem: sub * 10 + elem, my_tuple_1)\n\nprint(\"After converting tuple to integer, it is \")\nprint(my_result)" }, { "code": null, "e": 2073, "s": 1979, "text": "The first tuple is :\n(23, 45, 12, 56, 78, 0)\nAfter converting tuple to integer, it is\n2768380" }, { "code": null, "e": 2111, "s": 2073, "text": "The required packages are downloaded." }, { "code": null, "e": 2164, "s": 2111, "text": "A tuple is defined, and is displayed on the console." }, { "code": null, "e": 2253, "s": 2164, "text": "The reduce function is used, to which the lambda, and the tuple are passed as arguments." }, { "code": null, "e": 2355, "s": 2253, "text": "The lambda function multiples every element in the tuple with 10 and adds the previous element to it." }, { "code": null, "e": 2402, "s": 2355, "text": "This operation's data is stored in a variable." }, { "code": null, "e": 2464, "s": 2402, "text": "This variable is the output that is displayed on the console." } ]
How can I get a file's size in C++?
To get a file’s size in C++ first open the file and seek it to the end. tell() will tell us the current position of the stream, which will be the number of bytes in the file. Live Demo #include<iostream> #include<fstream> using namespace std; int main() { ifstream in_file("a.txt", ios::binary); in_file.seekg(0, ios::end); int file_size = in_file.tellg(); cout<<"Size of the file is"<<" "<< file_size<<" "<<"bytes"; } Size of the file is 44 bytes
[ { "code": null, "e": 1237, "s": 1062, "text": "To get a file’s size in C++ first open the file and seek it to the end. tell() will tell us the current position of the stream, which will be the number of bytes in the file." }, { "code": null, "e": 1248, "s": 1237, "text": " Live Demo" }, { "code": null, "e": 1494, "s": 1248, "text": "#include<iostream>\n#include<fstream>\nusing namespace std;\nint main() {\n ifstream in_file(\"a.txt\", ios::binary);\n in_file.seekg(0, ios::end);\n int file_size = in_file.tellg();\n cout<<\"Size of the file is\"<<\" \"<< file_size<<\" \"<<\"bytes\";\n}" }, { "code": null, "e": 1523, "s": 1494, "text": "Size of the file is 44 bytes" } ]
Report Fonts
A report contains text elements and each of these can have its own font settings. These settings can be specified using the <font> tag available in the <textElement> tag. A report can define a number of fonts. Once defined, they can be used as default or base font settings for other font definitions throughout the entire report. A report font is a collection of font settings, declared at the report level. A report font can be reused throughout the entire report template when setting the font properties of text elements. Report fonts are now deprecated. Do not use <reportFont/> elements declared within the document itself. Use the <style/> element instead. Table below summarizes the main attributes of the <font> element − fontName The font name, which can be the name of a physical font, a logical one, or the name of a font family from the registered JasperReports font extensions. size The size of the font measured in points. It defaults to 10. isBold The flag specifying if a bold font is required. It defaults to false. isItalic The flag specifying if an italic font is required. It defaults to false. isUnderline The flag specifying if the underline text decoration is required. It defaults to false. isStrikeThrough The flag specifying if the strikethrough text decoration is required. It defaults to false. pdfFontName The name of an equivalent PDF font required by the iText library when exporting documents to PDF format. pdfEncoding The equivalent PDF character encoding, also required by the iText library. isPdfEmbedded The flag that specifies whether the font should be embedded into the document itself. It defaults to false. If set to true, helps view the PDF document without any problem. In JasperReports fonts can be categorized as − Logical Fonts − Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are − Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system. Logical Fonts − Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are − Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system. Physical Fonts − These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts. Physical Fonts − These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts. Font Extensions − The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales. Font Extensions − The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales. As described in the table above we need to specify in the attribute fontName the name of a physical font, the name of a logical font, or the name of a font family from the registered JasperReports font extensions. JasperReports library uses the iText library, when exporting reports to PDF(Portable Document Format). PDF files can be viewed on various platforms and will always look the same. This is partially because in this format, there is a special way of dealing with fonts. fontName attribute is of no use when exporting to PDF. Attribute pdfFontName exist where we need to specify the font settings. The iText library knows how to deal with built-in fonts and TTF files and recognizes the following built-in font names − Courier Courier-Bold Courier-BoldOblique Courier-Oblique Helvetica Helvetica-Bold Helvetica-BoldOblique Helvetica-Oblique Symbol Times-Roman Times-Bold Times-BoldItalic Times-Italic ZapfDingbats As per iText library pre-requisite, to work with fonts, we need to specify one of the following as the font name − A built-in font name from the above list. A built-in font name from the above list. The name of a TTF (True Type Font) file, which it can locate on disk. The name of a TTF (True Type Font) file, which it can locate on disk. The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered. The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered. Based on the above pre-requisites, the pdfFontName attribute can contain one of the following values − The name of a built-in PDF font from the above list. The name of a built-in PDF font from the above list. The name of a TTF file that can be located on disk at runtime when exporting to PDF. The name of a TTF file that can be located on disk at runtime when exporting to PDF. The real name of a registered font. The real name of a registered font. The suffix of the key (the part after net.sf.jasperreports.export.pdf.font) for a font registered with iText as a font file. The suffix of the key (the part after net.sf.jasperreports.export.pdf.font) for a font registered with iText as a font file. Each text element inherits font and style attributes from its parent element, which in turn inherits these attributes from its parent. If no styles and/or fonts are defined for elements, the default style (and/or font - but this is now deprecated) declared in the <jasperReport/> root element will be applied. Defining default styles or fonts in JasperReports is not mandatory. If no font is defined for a given element, the engine looks either for the inherited font attributes, or, if no attributes are found on this way, it looks for the net.sf.jasperreports.default.font.name property in the /src/default.jasperreports.properties file. Its value defines the name of the font family to be used when font properties are not explicitly defined for a text element or inherited from its parent. The main default font properties and their values defined in the /src/default.jasperreports.properties file are in the table below − To demonstrate using fonts and font attributes in order to get a particular text appearance, let's write new report template (jasper_report_template.jrxml). The contents of the JRXML are as below. Save it to C:\tools\jasperreports-5.0.1\test directory. Here, we will display a text in the title of the report in various font formats. <?xml version = "1.0" encoding = "UTF-8"?> <jasperReport xmlns = "http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name = "jasper_report_template" pageWidth = "595" pageHeight = "842" columnWidth = "555" leftMargin = "20" rightMargin = "20" topMargin = "30" bottomMargin = "30"> <title> <band height = "682"> <staticText> <reportElement x = "0" y = "50" width = "150" height = "40"/> <textElement/> <text> <![CDATA[Welcome to TutorialsPoint!]]> </text> </staticText> <staticText> <reportElement x = "160" y = "50" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "50" width = "150" height = "40"/> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "100" width = "150" height = "40"/> <textElement> <font size = "12"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "100" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "100" width = "150" height = "40"/> <textElement> <font size = "14"/> </textElement> <text> Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "150" width = "150" height = "40"/> <textElement> <font fontName = "DejaVu Serif" size = "12" isBold = "false"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "150" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "250" width = "150" height = "40"/> <textElement> <font fontName = "DejaVu Serif" size = "12" isBold = "false"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "200" width = "150" height = "40"/> <textElement> <font fontName = "DejaVu Serif" size = "12" isBold = "true"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "200" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "300" width = "150" height = "40"/> <textElement> <font fontName = "DejaVu Serif" size = "12" isBold = "true"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "250" width = "150" height = "40"/> <textElement> <font fontName = "Monospaced" size = "12" isItalic = "true" isUnderline = "true" pdfFontName = "Courier-Oblique"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "250" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "350" width = "150" height = "40"/> <textElement> <font fontName = "Monospaced" size = "12" isItalic = "true" isUnderline = "true" pdfFontName = "Courier-Oblique"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "300" width = "150" height = "40"/> <textElement> <font fontName = "Monospaced" size = "12" isBold = "true" isStrikeThrough = "true" pdfFontName = "Courier-Bold"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "300" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "400" width = "150" height = "40"/> <textElement> <font fontName = "Monospaced" size = "12" isBold = "true" isStrikeThrough = "true" pdfFontName = "Courier-Bold"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "350" width = "150" height = "40" forecolor = "#FF0000"/> <textElement> <font size = "14"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "350" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "450" width = "150" height = "40" forecolor = "red"/> <textElement><font size = "14"/></textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "400" width = "150" height = "40" mode = "Opaque" forecolor = "#00FF00" backcolor = "#FFFF00"/> <textElement> <font fontName = "Serif" size = "12" isBold = "true" pdfFontName = "Times-Bold"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "400" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "500" width = "150" height = "40" forecolor = "green" backcolor = "#FFFF00" mode = "Opaque"/> <textElement> <font fontName = "Serif" size = "12" isBold = "true" pdfFontName = "Times-Bold"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement x = "0" y = "450" width = "150" height = "40" mode = "Opaque" forecolor = "#0000FF" backcolor = "#FFDD99"/> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font fontName = "SansSerif" size = "12" isBold = "false" isItalic = "true" pdfFontName = "Sans.Slanted" isPdfEmbedded = "true"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "450" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "550" width = "150" height = "90" forecolor = "blue" backcolor = "#FFDD99" mode = "Opaque"/> <textElement textAlignment = "Center" verticalAlignment = "Middle"> <font fontName = "SansSerif" size = "12" isBold = "false" pdfFontName = "Sans.Slanted" isPdfEmbedded = "true"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> <staticText> <reportElement mode = "Opaque" x = "0" y = "500" width = "150" height = "40" forecolor = "#FF0000" backcolor = "#99DDFF"/> <textElement textAlignment = "Right" verticalAlignment = "Bottom"> <font fontName = "SansSerif" size = "12" isBold = "true" pdfFontName = "DejaVu Sans Bold" isPdfEmbedded = "true"/> </textElement> <text><![CDATA[Welcome to TutorialsPoint!]]></text> </staticText> <staticText> <reportElement x = "160" y = "500" width = "390" height = "40"/> <textElement/> <text> <![CDATA[<staticText> <reportElement x = "0" y = "650" width = "150" height = "90" forecolor = "red" backcolor = "#99DDFF" mode = "Opaque"/> <textElement textAlignment = "Right" verticalAlignment = "Bottom"> <font fontName = "SansSerif" size = "12" isBold = "true" pdfFontName = "DejaVu Sans Bold" isPdfEmbedded = "true"/> </textElement> <text>Welcome to TutorialsPoint!</text></staticText>]]> </text> </staticText> </band> </title> </jasperReport> The java code to fill and generate the report is as given below. Let's save this file JasperFontsReportFill.java to C:\tools\jasperreports-5.0.1\test\src\com\tutorialspoint directory. package com.tutorialspoint; import net.sf.jasperreports.engine.JREmptyDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; public class JasperFontsReportFill { public static void main(String[] args) { String sourceFileName = "C://tools/jasperreports-5.0.1/test/" + "jasper_report_template.jasper"; try { JasperFillManager.fillReportToFile(sourceFileName, null, new JREmptyDataSource()); } catch (JRException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields being null. We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\tools\jasperreports-5.0.1\test) are as given below. The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml. <?xml version = "1.0" encoding = "UTF-8"?> <project name = "JasperReportTest" default = "viewFillReport" basedir = "."> <import file = "baseBuild.xml" /> <target name = "viewFillReport" depends = "compile,compilereportdesing,run" description = "Launches the report viewer to preview the report stored in the .JRprint file."> <java classname = "net.sf.jasperreports.view.JasperViewer" fork = "true"> <arg value = "-F${file.name}.JRprint" /> <classpath refid = "classpath" /> </java> </target> <target name = "compilereportdesing" description = "Compiles the JXML file and produces the .jasper file."> <taskdef name = "jrc" classname = "net.sf.jasperreports.ant.JRAntCompileTask"> <classpath refid = "classpath" /> </taskdef> <jrc destdir = "."> <src> <fileset dir = "."> <include name = "*.jrxml" /> </fileset> </src> <classpath refid = "classpath" /> </jrc> </target> </project> Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill (viewFullReport is the default target) as − C:\tools\jasperreports-5.0.1\test>ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill Buildfile: C:\tools\jasperreports-5.0.1\test\build.xml clean-sample: [delete] Deleting directory C:\tools\jasperreports-5.0.1\test\classes [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jasper [delete] Deleting: C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrprint compile: [mkdir] Created dir: C:\tools\jasperreports-5.0.1\test\classes [javac] C:\tools\jasperreports-5.0.1\test\baseBuild.xml:28: warning: 'includeantruntime' was not set, defaulting to build. [javac] Compiling 5 source files to C:\tools\jasperreports-5.0.1\test\classes compilereportdesing: [jrc] Compiling 1 report design files. [jrc] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory). [jrc] log4j:WARN Please initialize the log4j system properly. [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info. [jrc] File : C:\tools\jasperreports-5.0.1\test\jasper_report_template.jrxml ... OK. run: [echo] Runnin class : com.tutorialspoint.JasperFontsReportFill [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. viewFillReport: [java] log4j:WARN No appenders could be found for logger (net.sf.jasperreports.extensions.ExtensionsEnvironment). [java] log4j:WARN Please initialize the log4j system properly. BUILD SUCCESSFUL Total time: 45 minutes 3 seconds As a result of above compilation, a JasperViewer window opens up as shown in the screen given below − Here, we can see that the text "Welcome to TutorialsPoint" is displayed in different font formats. Print Add Notes Bookmark this page
[ { "code": null, "e": 2585, "s": 2254, "text": "A report contains text elements and each of these can have its own font settings. These settings can be specified using the <font> tag available in the <textElement> tag. A report can define a number of fonts. Once defined, they can be used as default or base font settings for other font definitions throughout the entire report." }, { "code": null, "e": 2780, "s": 2585, "text": "A report font is a collection of font settings, declared at the report level. A report font can be reused throughout the entire report template when setting the font properties of text elements." }, { "code": null, "e": 2918, "s": 2780, "text": "Report fonts are now deprecated. Do not use <reportFont/> elements declared within the document itself. Use the <style/> element instead." }, { "code": null, "e": 2985, "s": 2918, "text": "Table below summarizes the main attributes of the <font> element −" }, { "code": null, "e": 2994, "s": 2985, "text": "fontName" }, { "code": null, "e": 3146, "s": 2994, "text": "The font name, which can be the name of a physical font, a logical one, or the name of a font family from the registered JasperReports font extensions." }, { "code": null, "e": 3151, "s": 3146, "text": "size" }, { "code": null, "e": 3211, "s": 3151, "text": "The size of the font measured in points. It defaults to 10." }, { "code": null, "e": 3218, "s": 3211, "text": "isBold" }, { "code": null, "e": 3288, "s": 3218, "text": "The flag specifying if a bold font is required. It defaults to false." }, { "code": null, "e": 3297, "s": 3288, "text": "isItalic" }, { "code": null, "e": 3370, "s": 3297, "text": "The flag specifying if an italic font is required. It defaults to false." }, { "code": null, "e": 3382, "s": 3370, "text": "isUnderline" }, { "code": null, "e": 3470, "s": 3382, "text": "The flag specifying if the underline text decoration is required. It defaults to false." }, { "code": null, "e": 3486, "s": 3470, "text": "isStrikeThrough" }, { "code": null, "e": 3578, "s": 3486, "text": "The flag specifying if the strikethrough text decoration is required. It defaults to false." }, { "code": null, "e": 3590, "s": 3578, "text": "pdfFontName" }, { "code": null, "e": 3695, "s": 3590, "text": "The name of an equivalent PDF font required by the iText library when exporting documents to PDF format." }, { "code": null, "e": 3707, "s": 3695, "text": "pdfEncoding" }, { "code": null, "e": 3782, "s": 3707, "text": "The equivalent PDF character encoding, also required by the iText library." }, { "code": null, "e": 3796, "s": 3782, "text": "isPdfEmbedded" }, { "code": null, "e": 3969, "s": 3796, "text": "The flag that specifies whether the font should be embedded into the document itself. It defaults to false. If set to true, helps view the PDF document without any problem." }, { "code": null, "e": 4016, "s": 3969, "text": "In JasperReports fonts can be categorized as −" }, { "code": null, "e": 4442, "s": 4016, "text": "Logical Fonts − Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are − Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system." }, { "code": null, "e": 4868, "s": 4442, "text": "Logical Fonts − Five font types, which have been recognized by the Java platform since version 1.0, are called logical fonts. These are − Serif, SansSerif, Monospaced, Dialog, and DialogInput. These logical fonts are not actual font libraries that are installed anywhere on the system. They are merely font type names recognized by the Java runtime. These must be mapped to some physical font that is installed on the system." }, { "code": null, "e": 5113, "s": 4868, "text": "Physical Fonts − These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts." }, { "code": null, "e": 5358, "s": 5113, "text": "Physical Fonts − These fonts are the actual font libraries consisting of, for example, TrueType or PostScript Type 1 fonts. The physical fonts may be Arial, Time, Helvetica, Courier, or any number of other fonts, including international fonts." }, { "code": null, "e": 5681, "s": 5358, "text": "Font Extensions − The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales." }, { "code": null, "e": 6004, "s": 5681, "text": "Font Extensions − The JasperReports library can make use of fonts registered on-the-fly at runtime, through its built-in support for font extensions. A list of font families can be made available to the JasperReports using font extension. These are made out of similarly looking font faces and supporting specific locales." }, { "code": null, "e": 6218, "s": 6004, "text": "As described in the table above we need to specify in the attribute fontName the name of a physical font, the name of a logical font, or the name of a font family from the registered JasperReports font extensions." }, { "code": null, "e": 6612, "s": 6218, "text": "JasperReports library uses the iText library, when exporting reports to PDF(Portable Document Format). PDF files can be viewed on various platforms and will always look the same. This is partially because in this format, there is a special way of dealing with fonts. fontName attribute is of no use when exporting to PDF. Attribute pdfFontName exist where we need to specify the font settings." }, { "code": null, "e": 6733, "s": 6612, "text": "The iText library knows how to deal with built-in fonts and TTF files and recognizes the following built-in font names −" }, { "code": null, "e": 6741, "s": 6733, "text": "Courier" }, { "code": null, "e": 6754, "s": 6741, "text": "Courier-Bold" }, { "code": null, "e": 6774, "s": 6754, "text": "Courier-BoldOblique" }, { "code": null, "e": 6790, "s": 6774, "text": "Courier-Oblique" }, { "code": null, "e": 6800, "s": 6790, "text": "Helvetica" }, { "code": null, "e": 6815, "s": 6800, "text": "Helvetica-Bold" }, { "code": null, "e": 6837, "s": 6815, "text": "Helvetica-BoldOblique" }, { "code": null, "e": 6855, "s": 6837, "text": "Helvetica-Oblique" }, { "code": null, "e": 6862, "s": 6855, "text": "Symbol" }, { "code": null, "e": 6874, "s": 6862, "text": "Times-Roman" }, { "code": null, "e": 6885, "s": 6874, "text": "Times-Bold" }, { "code": null, "e": 6902, "s": 6885, "text": "Times-BoldItalic" }, { "code": null, "e": 6915, "s": 6902, "text": "Times-Italic" }, { "code": null, "e": 6928, "s": 6915, "text": "ZapfDingbats" }, { "code": null, "e": 7043, "s": 6928, "text": "As per iText library pre-requisite, to work with fonts, we need to specify one of the following as the font name −" }, { "code": null, "e": 7085, "s": 7043, "text": "A built-in font name from the above list." }, { "code": null, "e": 7127, "s": 7085, "text": "A built-in font name from the above list." }, { "code": null, "e": 7197, "s": 7127, "text": "The name of a TTF (True Type Font) file, which it can locate on disk." }, { "code": null, "e": 7267, "s": 7197, "text": "The name of a TTF (True Type Font) file, which it can locate on disk." }, { "code": null, "e": 7442, "s": 7267, "text": "The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered." }, { "code": null, "e": 7617, "s": 7442, "text": "The real name of the font, provided that the TTF file containing the font has been previously registered with iText or that an alias was defined when the font was registered." }, { "code": null, "e": 7720, "s": 7617, "text": "Based on the above pre-requisites, the pdfFontName attribute can contain one of the following values −" }, { "code": null, "e": 7773, "s": 7720, "text": "The name of a built-in PDF font from the above list." }, { "code": null, "e": 7826, "s": 7773, "text": "The name of a built-in PDF font from the above list." }, { "code": null, "e": 7911, "s": 7826, "text": "The name of a TTF file that can be located on disk at runtime when exporting to PDF." }, { "code": null, "e": 7996, "s": 7911, "text": "The name of a TTF file that can be located on disk at runtime when exporting to PDF." }, { "code": null, "e": 8032, "s": 7996, "text": "The real name of a registered font." }, { "code": null, "e": 8068, "s": 8032, "text": "The real name of a registered font." }, { "code": null, "e": 8193, "s": 8068, "text": "The suffix of the key (the part after net.sf.jasperreports.export.pdf.font) for a font registered with iText as a font file." }, { "code": null, "e": 8318, "s": 8193, "text": "The suffix of the key (the part after net.sf.jasperreports.export.pdf.font) for a font registered with iText as a font file." }, { "code": null, "e": 8629, "s": 8318, "text": "Each text element inherits font and style attributes from its parent element, which in turn inherits these attributes from its parent. If no styles and/or fonts are defined for elements, the default style (and/or font - but this is now deprecated) declared in the <jasperReport/> root element will be applied. " }, { "code": null, "e": 9113, "s": 8629, "text": "Defining default styles or fonts in JasperReports is not mandatory. If no font is defined for a given element, the engine looks either for the inherited font attributes, or, if no attributes are found on this way, it looks for the net.sf.jasperreports.default.font.name property in the /src/default.jasperreports.properties file. Its value defines the name of the font family to be used when font properties are not explicitly defined for a text element or inherited from its parent." }, { "code": null, "e": 9246, "s": 9113, "text": "The main default font properties and their values defined in the /src/default.jasperreports.properties file are in the table below −" }, { "code": null, "e": 9581, "s": 9246, "text": "To demonstrate using fonts and font attributes in order to get a particular text appearance, let's write new report template (jasper_report_template.jrxml). The contents of the JRXML are as below. Save it to C:\\tools\\jasperreports-5.0.1\\test directory. Here, we will display a text in the title of the report in various font formats." }, { "code": null, "e": 19358, "s": 9581, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n\n<jasperReport xmlns = \"http://jasperreports.sourceforge.net/jasperreports\"\n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://jasperreports.sourceforge.net/jasperreports\n http://jasperreports.sourceforge.net/xsd/jasperreport.xsd\"\n name = \"jasper_report_template\" pageWidth = \"595\" pageHeight = \"842\"\n columnWidth = \"555\" leftMargin = \"20\" rightMargin = \"20\" topMargin = \"30\"\n bottomMargin = \"30\">\n\n <title>\n <band height = \"682\">\n \n <staticText>\n <reportElement x = \"0\" y = \"50\" width = \"150\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[Welcome to TutorialsPoint!]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"50\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"50\" width = \"150\" height = \"40\"/>\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"100\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font size = \"12\"/>\n </textElement>\n \n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"100\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"100\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font size = \"14\"/>\n </textElement>\n\t\t\t\t\n <text> Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"150\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"DejaVu Serif\" size = \"12\" isBold = \"false\"/>\n </textElement>\n\t\t\t\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"150\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"250\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"DejaVu Serif\" size = \"12\" isBold = \"false\"/>\n </textElement>\n\t\t\t\t\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"200\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"DejaVu Serif\" size = \"12\" isBold = \"true\"/>\n </textElement>\n\t\t\t\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"200\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"300\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"DejaVu Serif\" size = \"12\" isBold = \"true\"/>\n </textElement>\n\t\t\t\t\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"250\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"Monospaced\" size = \"12\" isItalic = \"true\" \n isUnderline = \"true\" pdfFontName = \"Courier-Oblique\"/>\n </textElement>\n \n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"250\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"350\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"Monospaced\" size = \"12\" isItalic = \"true\"\n isUnderline = \"true\" pdfFontName = \"Courier-Oblique\"/>\n </textElement>\n \n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"300\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"Monospaced\" size = \"12\" isBold = \"true\"\n isStrikeThrough = \"true\" pdfFontName = \"Courier-Bold\"/>\n </textElement>\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"300\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"400\" width = \"150\" height = \"40\"/>\n \n <textElement>\n <font fontName = \"Monospaced\" size = \"12\" isBold = \"true\"\n isStrikeThrough = \"true\" pdfFontName = \"Courier-Bold\"/>\n </textElement>\n\t\t\t\t\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"350\" width = \"150\" height = \"40\" \n forecolor = \"#FF0000\"/>\n \n <textElement>\n <font size = \"14\"/>\n </textElement>\n\t\t\t\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"350\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"450\" width = \"150\" height = \"40\"\n forecolor = \"red\"/>\n \n <textElement><font size = \"14\"/></textElement>\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"400\" width = \"150\" height = \"40\" mode = \"Opaque\"\n forecolor = \"#00FF00\" backcolor = \"#FFFF00\"/>\n \n <textElement>\n <font fontName = \"Serif\" size = \"12\" isBold = \"true\" \n pdfFontName = \"Times-Bold\"/>\n </textElement>\n\t\t\t\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"400\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"500\" width = \"150\" height = \"40\"\n forecolor = \"green\" backcolor = \"#FFFF00\" mode = \"Opaque\"/>\n \n <textElement>\n <font fontName = \"Serif\" size = \"12\" isBold = \"true\"\n pdfFontName = \"Times-Bold\"/>\n </textElement>\n\t\t\t\t\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement x = \"0\" y = \"450\" width = \"150\" height = \"40\" mode = \"Opaque\"\n forecolor = \"#0000FF\" backcolor = \"#FFDD99\"/>\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font fontName = \"SansSerif\" size = \"12\" isBold = \"false\"\n isItalic = \"true\" pdfFontName = \"Sans.Slanted\" isPdfEmbedded = \"true\"/>\n </textElement>\n\t\t\t\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"450\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"550\" width = \"150\" height = \"90\"\n forecolor = \"blue\" backcolor = \"#FFDD99\" mode = \"Opaque\"/>\n \n <textElement textAlignment = \"Center\" verticalAlignment = \"Middle\">\n <font fontName = \"SansSerif\" size = \"12\" isBold = \"false\"\n pdfFontName = \"Sans.Slanted\" isPdfEmbedded = \"true\"/>\n </textElement>\n\t\t\t\t\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n </staticText>\n \n <staticText>\n <reportElement mode = \"Opaque\" x = \"0\" y = \"500\" width = \"150\" height = \"40\"\n forecolor = \"#FF0000\" backcolor = \"#99DDFF\"/>\n \n <textElement textAlignment = \"Right\" verticalAlignment = \"Bottom\">\n <font fontName = \"SansSerif\" size = \"12\" isBold = \"true\"\n pdfFontName = \"DejaVu Sans Bold\" isPdfEmbedded = \"true\"/>\n </textElement>\n\t\t\t\n <text><![CDATA[Welcome to TutorialsPoint!]]></text>\n </staticText>\n \n <staticText>\n <reportElement x = \"160\" y = \"500\" width = \"390\" height = \"40\"/>\n <textElement/>\n \n <text>\n <![CDATA[<staticText>\n <reportElement x = \"0\" y = \"650\" width = \"150\" height = \"90\" forecolor = \"red\"\n backcolor = \"#99DDFF\" mode = \"Opaque\"/>\n \n <textElement textAlignment = \"Right\" verticalAlignment = \"Bottom\">\n <font fontName = \"SansSerif\" size = \"12\" isBold = \"true\"\n pdfFontName = \"DejaVu Sans Bold\" isPdfEmbedded = \"true\"/>\n </textElement>\n\t\t\t\t\n <text>Welcome to TutorialsPoint!</text></staticText>]]>\n </text>\n \n </staticText>\n \n </band>\n</title>\n\n</jasperReport>" }, { "code": null, "e": 19542, "s": 19358, "text": "The java code to fill and generate the report is as given below. Let's save this file JasperFontsReportFill.java to C:\\tools\\jasperreports-5.0.1\\test\\src\\com\\tutorialspoint directory." }, { "code": null, "e": 20161, "s": 19542, "text": "package com.tutorialspoint;\n\nimport net.sf.jasperreports.engine.JREmptyDataSource;\nimport net.sf.jasperreports.engine.JRException;\nimport net.sf.jasperreports.engine.JasperFillManager;\n\npublic class JasperFontsReportFill {\n public static void main(String[] args) {\n String sourceFileName = \"C://tools/jasperreports-5.0.1/test/\" + \n \"jasper_report_template.jasper\";\n\n try {\n JasperFillManager.fillReportToFile(sourceFileName, null,\n new JREmptyDataSource());\n } catch (JRException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n }\n\n }\n}" }, { "code": null, "e": 20313, "s": 20161, "text": "Here, we use an instance of JREmptyDataSource when filling reports to simulate a data source with one record in it, but with all the fields being null." }, { "code": null, "e": 20506, "s": 20313, "text": "We will compile and execute the above file using our regular ANT build process. The contents of the file build.xml (saved under directory C:\\tools\\jasperreports-5.0.1\\test) are as given below." }, { "code": null, "e": 20640, "s": 20506, "text": "The import file - baseBuild.xml is picked from chapter Environment Setup and should be placed in the same directory as the build.xml." }, { "code": null, "e": 21720, "s": 20640, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project name = \"JasperReportTest\" default = \"viewFillReport\" basedir = \".\">\n <import file = \"baseBuild.xml\" />\n \n <target name = \"viewFillReport\" depends = \"compile,compilereportdesing,run\"\n description = \"Launches the report viewer to preview the report \n stored in the .JRprint file.\">\n \n <java classname = \"net.sf.jasperreports.view.JasperViewer\" fork = \"true\">\n <arg value = \"-F${file.name}.JRprint\" />\n <classpath refid = \"classpath\" />\n </java>\n\t\t\n </target>\n \n <target name = \"compilereportdesing\" description = \"Compiles the JXML file and\n produces the .jasper file.\">\n \n <taskdef name = \"jrc\" classname = \"net.sf.jasperreports.ant.JRAntCompileTask\">\n <classpath refid = \"classpath\" />\n </taskdef>\n \n <jrc destdir = \".\">\n <src>\n <fileset dir = \".\">\n <include name = \"*.jrxml\" />\n </fileset>\n </src>\n <classpath refid = \"classpath\" />\n </jrc>\n \n </target>\n\t\n</project>" }, { "code": null, "e": 21939, "s": 21720, "text": "Next, let's open command line window and go to the directory where build.xml is placed. Finally, execute the command ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill (viewFullReport is the default target) as −" }, { "code": null, "e": 23573, "s": 21939, "text": "C:\\tools\\jasperreports-5.0.1\\test>ant -Dmain-class=com.tutorialspoint.JasperFontsReportFill\nBuildfile: C:\\tools\\jasperreports-5.0.1\\test\\build.xml\n\nclean-sample:\n [delete] Deleting directory C:\\tools\\jasperreports-5.0.1\\test\\classes\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jasper\n [delete] Deleting: C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrprint\n\ncompile:\n [mkdir] Created dir: C:\\tools\\jasperreports-5.0.1\\test\\classes\n [javac] C:\\tools\\jasperreports-5.0.1\\test\\baseBuild.xml:28:\n warning: 'includeantruntime' was not set, defaulting to build.\n [javac] Compiling 5 source files to C:\\tools\\jasperreports-5.0.1\\test\\classes\n\ncompilereportdesing:\n [jrc] Compiling 1 report design files.\n [jrc] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.engine.xml.JRXmlDigesterFactory).\n [jrc] log4j:WARN Please initialize the log4j system properly.\n [jrc] log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.\n [jrc] File : C:\\tools\\jasperreports-5.0.1\\test\\jasper_report_template.jrxml ... OK.\n\nrun:\n [echo] Runnin class : com.tutorialspoint.JasperFontsReportFill\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nviewFillReport:\n [java] log4j:WARN No appenders could be found for logger\n (net.sf.jasperreports.extensions.ExtensionsEnvironment).\n [java] log4j:WARN Please initialize the log4j system properly.\n\nBUILD SUCCESSFUL\nTotal time: 45 minutes 3 seconds\n" }, { "code": null, "e": 23675, "s": 23573, "text": "As a result of above compilation, a JasperViewer window opens up as shown in the screen given below −" }, { "code": null, "e": 23774, "s": 23675, "text": "Here, we can see that the text \"Welcome to TutorialsPoint\" is displayed in different font formats." }, { "code": null, "e": 23781, "s": 23774, "text": " Print" }, { "code": null, "e": 23792, "s": 23781, "text": " Add Notes" } ]
Design a data structure that supports insert, delete, search and getRandom in constant time - GeeksforGeeks
18 May, 2021 Design a data structure that supports the following operations in Θ(1) time.insert(x): Inserts an item x to the data structure if not already present.remove(x): Removes item x from the data structure if present. search(x): Searches an item x in the data structure.getRandom(): Returns a random element from current set of elements We can use hashing to support first 3 operations in Θ(1) time. How to do the 4th operation? The idea is to use a resizable array (ArrayList in Java, vector in C) together with hashing. Resizable arrays support insert in Θ(1) amortized time complexity. To implement getRandom(), we can simply pick a random number from 0 to size-1 (size is the number of current elements) and return the element at that index. The hash map stores array values as keys and array indexes as values.Following are detailed operations.insert(x) 1) Check if x is already present by doing a hash map lookup. 2) If not present, then insert it at the end of the array. 3) Add in the hash table also, x is added as key and last array index as the index.remove(x) 1) Check if x is present by doing a hash map lookup. 2) If present, then find its index and remove it from a hash map. 3) Swap the last element with this element in an array and remove the last element. Swapping is done because the last element can be removed in O(1) time. 4) Update index of the last element in a hash map.getRandom() 1) Generate a random number from 0 to last index. 2) Return the array element at the randomly generated index.search(x) Do a lookup for x in hash map.Below is the implementation of the data structure. C++ Java Python3 /* C++ program to design a DS that supports following operationsin Theta(n) timea) Insertb) Deletec) Searchd) getRandom */ #include<bits/stdc++.h>using namespace std; // class to represent the required data structureclass myStructure{ // A resizable array vector <int> arr; // A hash where keys are array elements and values are // indexes in arr[] map <int, int> Map; public: // A Theta(1) function to add an element to MyDS // data structure void add(int x) { // If element is already present, then nothing to do if(Map.find(x) != Map.end()) return; // Else put element at the end of arr[] int index = arr.size(); arr.push_back(x); // and hashmap also Map.insert(std::pair<int,int>(x, index)); } // function to remove a number to DS in O(1) void remove(int x) { // element not found then return if(Map.find(x) == Map.end()) return; // remove element from map int index = Map.at(x); Map.erase(x); // swap with last element in arr // then remove element at back int last = arr.size() - 1; swap(arr[index], arr[last]); arr.pop_back(); // Update hash table for new index of last element Map.at(arr[index]) = index; } // Returns index of element if element is present, otherwise null int search(int x) { if(Map.find(x) != Map.end()) return Map.at(x); return -1; } // Returns a random element from myStructure int getRandom() { // Find a random index from 0 to size - 1 srand (time(NULL)); int random_index = rand() % arr.size(); // Return element at randomly picked index return arr.at(random_index); } }; // Driver mainint main(){ myStructure ds; ds.add(10); ds.add(20); ds.add(30); ds.add(40); cout << ds.search(30) << endl; ds.remove(20); ds.add(50); cout << ds.search(50) << endl; cout << ds.getRandom() << endl;} // This code is contributed by Aditi Sharma /* Java program to design a data structure that support following operations in Theta(n) time a) Insert b) Delete c) Search d) getRandom */import java.util.*; // class to represent the required data structureclass MyDS{ ArrayList<Integer> arr; // A resizable array // A hash where keys are array elements and values are // indexes in arr[] HashMap<Integer, Integer> hash; // Constructor (creates arr[] and hash) public MyDS() { arr = new ArrayList<Integer>(); hash = new HashMap<Integer, Integer>(); } // A Theta(1) function to add an element to MyDS // data structure void add(int x) { // If element is already present, then nothing to do if (hash.get(x) != null) return; // Else put element at the end of arr[] int s = arr.size(); arr.add(x); // And put in hash also hash.put(x, s); } // A Theta(1) function to remove an element from MyDS // data structure void remove(int x) { // Check if element is present Integer index = hash.get(x); if (index == null) return; // If present, then remove element from hash hash.remove(x); // Swap element with last element so that remove from // arr[] can be done in O(1) time int size = arr.size(); Integer last = arr.get(size-1); Collections.swap(arr, index, size-1); // Remove last element (This is O(1)) arr.remove(size-1); // Update hash table for new index of last element hash.put(last, index); } // Returns a random element from MyDS int getRandom() { // Find a random index from 0 to size - 1 Random rand = new Random(); // Choose a different seed int index = rand.nextInt(arr.size()); // Return element at randomly picked index return arr.get(index); } // Returns index of element if element is present, otherwise null Integer search(int x) { return hash.get(x); }} // Driver classclass Main{ public static void main (String[] args) { MyDS ds = new MyDS(); ds.add(10); ds.add(20); ds.add(30); ds.add(40); System.out.println(ds.search(30)); ds.remove(20); ds.add(50); System.out.println(ds.search(50)); System.out.println(ds.getRandom()); }} '''Python program to design a DS thatsupports following operationsin Theta(n) time:a) Insertb) Deletec) Searchd) getRandom'''import random # Class to represent the required# data structureclass MyDS: # Constructor (creates a list and a hash) def __init__(self): # A resizable array self.arr = [] # A hash where keys are lists elements # and values are indexes of the list self.hashd = {} # A Theta(1) function to add an element # to MyDS data structure def add(self, x): # If element is already present, # then nothing has to be done if x in self.hashd: return # Else put element at # the end of the list s = len(self.arr) self.arr.append(x) # Also put it into hash self.hashd[x] = s # A Theta(1) function to remove an element # from MyDS data structure def remove(self, x): # Check if element is present index = self.hashd.get(x, None) if index == None: return # If present, then remove # element from hash del self.hashd[x] # Swap element with last element # so that removal from the list # can be done in O(1) time size = len(self.arr) last = self.arr[size - 1] self.arr[index], \ self.arr[size - 1] = self.arr[size - 1], \ self.arr[index] # Remove last element (This is O(1)) del self.arr[-1] # Update hash table for # new index of last element self.hashd[last] = index # Returns a random element from MyDS def getRandom(self): # Find a random index from 0 to size - 1 index = random.randrange(0, len(self.arr)) # Return element at randomly picked index return self.arr[index] # Returns index of element # if element is present, # otherwise none def search(self, x): return self.hashd.get(x, None) # Driver Codeif __name__=="__main__": ds = MyDS() ds.add(10) ds.add(20) ds.add(30) ds.add(40) print(ds.search(30)) ds.remove(20) ds.add(50) print(ds.search(50)) print(ds.getRandom()) # This code is contributed# by Saurabh Singh Output: 2 3 40 This article is contributed by Manish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above SwapnilShukla1 ssaurabhh4 dhyey35 simmytarika5 Amazon Advanced Data Structure Hash Amazon Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Disjoint Set Data Structures AVL Tree | Set 2 (Deletion) Red-Black Tree | Set 2 (Insert) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Hashing | Set 3 (Open Addressing) Count pairs with given sum
[ { "code": null, "e": 25020, "s": 24992, "text": "\n18 May, 2021" }, { "code": null, "e": 25353, "s": 25020, "text": "Design a data structure that supports the following operations in Θ(1) time.insert(x): Inserts an item x to the data structure if not already present.remove(x): Removes item x from the data structure if present. search(x): Searches an item x in the data structure.getRandom(): Returns a random element from current set of elements " }, { "code": null, "e": 26626, "s": 25353, "text": "We can use hashing to support first 3 operations in Θ(1) time. How to do the 4th operation? The idea is to use a resizable array (ArrayList in Java, vector in C) together with hashing. Resizable arrays support insert in Θ(1) amortized time complexity. To implement getRandom(), we can simply pick a random number from 0 to size-1 (size is the number of current elements) and return the element at that index. The hash map stores array values as keys and array indexes as values.Following are detailed operations.insert(x) 1) Check if x is already present by doing a hash map lookup. 2) If not present, then insert it at the end of the array. 3) Add in the hash table also, x is added as key and last array index as the index.remove(x) 1) Check if x is present by doing a hash map lookup. 2) If present, then find its index and remove it from a hash map. 3) Swap the last element with this element in an array and remove the last element. Swapping is done because the last element can be removed in O(1) time. 4) Update index of the last element in a hash map.getRandom() 1) Generate a random number from 0 to last index. 2) Return the array element at the randomly generated index.search(x) Do a lookup for x in hash map.Below is the implementation of the data structure. " }, { "code": null, "e": 26630, "s": 26626, "text": "C++" }, { "code": null, "e": 26635, "s": 26630, "text": "Java" }, { "code": null, "e": 26643, "s": 26635, "text": "Python3" }, { "code": "/* C++ program to design a DS that supports following operationsin Theta(n) timea) Insertb) Deletec) Searchd) getRandom */ #include<bits/stdc++.h>using namespace std; // class to represent the required data structureclass myStructure{ // A resizable array vector <int> arr; // A hash where keys are array elements and values are // indexes in arr[] map <int, int> Map; public: // A Theta(1) function to add an element to MyDS // data structure void add(int x) { // If element is already present, then nothing to do if(Map.find(x) != Map.end()) return; // Else put element at the end of arr[] int index = arr.size(); arr.push_back(x); // and hashmap also Map.insert(std::pair<int,int>(x, index)); } // function to remove a number to DS in O(1) void remove(int x) { // element not found then return if(Map.find(x) == Map.end()) return; // remove element from map int index = Map.at(x); Map.erase(x); // swap with last element in arr // then remove element at back int last = arr.size() - 1; swap(arr[index], arr[last]); arr.pop_back(); // Update hash table for new index of last element Map.at(arr[index]) = index; } // Returns index of element if element is present, otherwise null int search(int x) { if(Map.find(x) != Map.end()) return Map.at(x); return -1; } // Returns a random element from myStructure int getRandom() { // Find a random index from 0 to size - 1 srand (time(NULL)); int random_index = rand() % arr.size(); // Return element at randomly picked index return arr.at(random_index); } }; // Driver mainint main(){ myStructure ds; ds.add(10); ds.add(20); ds.add(30); ds.add(40); cout << ds.search(30) << endl; ds.remove(20); ds.add(50); cout << ds.search(50) << endl; cout << ds.getRandom() << endl;} // This code is contributed by Aditi Sharma", "e": 28826, "s": 26643, "text": null }, { "code": "/* Java program to design a data structure that support following operations in Theta(n) time a) Insert b) Delete c) Search d) getRandom */import java.util.*; // class to represent the required data structureclass MyDS{ ArrayList<Integer> arr; // A resizable array // A hash where keys are array elements and values are // indexes in arr[] HashMap<Integer, Integer> hash; // Constructor (creates arr[] and hash) public MyDS() { arr = new ArrayList<Integer>(); hash = new HashMap<Integer, Integer>(); } // A Theta(1) function to add an element to MyDS // data structure void add(int x) { // If element is already present, then nothing to do if (hash.get(x) != null) return; // Else put element at the end of arr[] int s = arr.size(); arr.add(x); // And put in hash also hash.put(x, s); } // A Theta(1) function to remove an element from MyDS // data structure void remove(int x) { // Check if element is present Integer index = hash.get(x); if (index == null) return; // If present, then remove element from hash hash.remove(x); // Swap element with last element so that remove from // arr[] can be done in O(1) time int size = arr.size(); Integer last = arr.get(size-1); Collections.swap(arr, index, size-1); // Remove last element (This is O(1)) arr.remove(size-1); // Update hash table for new index of last element hash.put(last, index); } // Returns a random element from MyDS int getRandom() { // Find a random index from 0 to size - 1 Random rand = new Random(); // Choose a different seed int index = rand.nextInt(arr.size()); // Return element at randomly picked index return arr.get(index); } // Returns index of element if element is present, otherwise null Integer search(int x) { return hash.get(x); }} // Driver classclass Main{ public static void main (String[] args) { MyDS ds = new MyDS(); ds.add(10); ds.add(20); ds.add(30); ds.add(40); System.out.println(ds.search(30)); ds.remove(20); ds.add(50); System.out.println(ds.search(50)); System.out.println(ds.getRandom()); }}", "e": 31169, "s": 28826, "text": null }, { "code": "'''Python program to design a DS thatsupports following operationsin Theta(n) time:a) Insertb) Deletec) Searchd) getRandom'''import random # Class to represent the required# data structureclass MyDS: # Constructor (creates a list and a hash) def __init__(self): # A resizable array self.arr = [] # A hash where keys are lists elements # and values are indexes of the list self.hashd = {} # A Theta(1) function to add an element # to MyDS data structure def add(self, x): # If element is already present, # then nothing has to be done if x in self.hashd: return # Else put element at # the end of the list s = len(self.arr) self.arr.append(x) # Also put it into hash self.hashd[x] = s # A Theta(1) function to remove an element # from MyDS data structure def remove(self, x): # Check if element is present index = self.hashd.get(x, None) if index == None: return # If present, then remove # element from hash del self.hashd[x] # Swap element with last element # so that removal from the list # can be done in O(1) time size = len(self.arr) last = self.arr[size - 1] self.arr[index], \\ self.arr[size - 1] = self.arr[size - 1], \\ self.arr[index] # Remove last element (This is O(1)) del self.arr[-1] # Update hash table for # new index of last element self.hashd[last] = index # Returns a random element from MyDS def getRandom(self): # Find a random index from 0 to size - 1 index = random.randrange(0, len(self.arr)) # Return element at randomly picked index return self.arr[index] # Returns index of element # if element is present, # otherwise none def search(self, x): return self.hashd.get(x, None) # Driver Codeif __name__==\"__main__\": ds = MyDS() ds.add(10) ds.add(20) ds.add(30) ds.add(40) print(ds.search(30)) ds.remove(20) ds.add(50) print(ds.search(50)) print(ds.getRandom()) # This code is contributed# by Saurabh Singh", "e": 33438, "s": 31169, "text": null }, { "code": null, "e": 33448, "s": 33438, "text": "Output: " }, { "code": null, "e": 33455, "s": 33448, "text": "2\n3\n40" }, { "code": null, "e": 33625, "s": 33455, "text": "This article is contributed by Manish Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 33640, "s": 33625, "text": "SwapnilShukla1" }, { "code": null, "e": 33651, "s": 33640, "text": "ssaurabhh4" }, { "code": null, "e": 33659, "s": 33651, "text": "dhyey35" }, { "code": null, "e": 33672, "s": 33659, "text": "simmytarika5" }, { "code": null, "e": 33679, "s": 33672, "text": "Amazon" }, { "code": null, "e": 33703, "s": 33679, "text": "Advanced Data Structure" }, { "code": null, "e": 33708, "s": 33703, "text": "Hash" }, { "code": null, "e": 33715, "s": 33708, "text": "Amazon" }, { "code": null, "e": 33720, "s": 33715, "text": "Hash" }, { "code": null, "e": 33818, "s": 33720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33852, "s": 33818, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 33892, "s": 33852, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 33921, "s": 33892, "text": "Disjoint Set Data Structures" }, { "code": null, "e": 33949, "s": 33921, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 33981, "s": 33949, "text": "Red-Black Tree | Set 2 (Insert)" }, { "code": null, "e": 34066, "s": 33981, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34102, "s": 34066, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 34133, "s": 34102, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 34167, "s": 34133, "text": "Hashing | Set 3 (Open Addressing)" } ]
Create an Analog Clock using HTML, CSS and JavaScript - GeeksforGeeks
12 Mar, 2021 We are going to build a real-time analog clock using HTML, CSS, and JavaScript. Prerequisite: Basic understanding of HTML, CSS, and JavaScript. Approach: We will create three files (HTML file, a CSS file, and JavaScript File), we also have an image of the clock that will be used in the background, and on top of that, we will make an hour, minute, and second hand (using HTML and CSS). These hands will rotate as per the system time (we will use the predefined Date function of JavaScript to calculate the degree of rotations of each hand). HTML: It is a simple file having the basic structure of the webpage and ID for the clock’s body and for the second, minute, hour hands. CSS: The CSS is used just for making the clock actually look a bit nicer. We have basically centered our clock in the middle of the webpage. JavaScript: The JavaScript file will provide the logic behind the rotation of the hands. Example: First we have selected the hour, minute, and second from HTML. To get the current time we have used the Date() object provided by the JavaScript. This will give the current seconds, minutes, and hours respectively. Now, we have got our hour, minute, and second, and we know that the clock rotates 360 degrees. So, we will convert to convert the rotation of the hands of the clock into degrees. The degree calculation is based on a simple unary method. index.html <!DOCTYPE html><html lang="en"><head> <link rel="stylesheet" href="style.css"> <script src="index.js"></script></head><body> <div id="clockContainer"> <div id="hour"></div> <div id="minute"></div> <div id="second"></div> </div></body></html> style.css #clockContainer { position: relative; margin: auto; height: 40vw; /*to make the height and width responsive*/ width: 40vw; background: url(clock.png) no-repeat; /*setting our background image*/ background-size: 100%;} #hour,#minute,#second { position: absolute; background: black; border-radius: 10px; transform-origin: bottom;} #hour { width: 1.8%; height: 25%; top: 25%; left: 48.85%; opacity: 0.8;} #minute { width: 1.6%; height: 30%; top: 19%; left: 48.9%; opacity: 0.8;} #second { width: 1%; height: 40%; top: 9%; left: 49.25%; opacity: 0.8;} index,js setInterval(() => { d = new Date(); //object of date() hr = d.getHours(); min = d.getMinutes(); sec = d.getSeconds(); hr_rotation = 30 * hr + min / 2; //converting current time min_rotation = 6 * min; sec_rotation = 6 * sec; hour.style.transform = `rotate(${hr_rotation}deg)`; minute.style.transform = `rotate(${min_rotation}deg)`; second.style.transform = `rotate(${sec_rotation}deg)`;}, 1000); Image used:https://media.geeksforgeeks.org/wp-content/uploads/20210302161254/imgonlinecomuaCompressToSizeOmNATjUMFKw-300×300.jpg Output: CSS-Questions HTML-Questions JavaScript-Questions CSS HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to create footer to stay at the bottom of a Web page? Types of CSS (Cascading Style Sheet) Create a Responsive Navbar using ReactJS Design a web page using HTML and CSS How to position a div at the bottom of its container using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? How to Insert Form Data into Database using PHP ? Hide or show elements in HTML using display property REST API (Introduction)
[ { "code": null, "e": 24512, "s": 24484, "text": "\n12 Mar, 2021" }, { "code": null, "e": 24592, "s": 24512, "text": "We are going to build a real-time analog clock using HTML, CSS, and JavaScript." }, { "code": null, "e": 24606, "s": 24592, "text": "Prerequisite:" }, { "code": null, "e": 24656, "s": 24606, "text": "Basic understanding of HTML, CSS, and JavaScript." }, { "code": null, "e": 25054, "s": 24656, "text": "Approach: We will create three files (HTML file, a CSS file, and JavaScript File), we also have an image of the clock that will be used in the background, and on top of that, we will make an hour, minute, and second hand (using HTML and CSS). These hands will rotate as per the system time (we will use the predefined Date function of JavaScript to calculate the degree of rotations of each hand)." }, { "code": null, "e": 25190, "s": 25054, "text": "HTML: It is a simple file having the basic structure of the webpage and ID for the clock’s body and for the second, minute, hour hands." }, { "code": null, "e": 25331, "s": 25190, "text": "CSS: The CSS is used just for making the clock actually look a bit nicer. We have basically centered our clock in the middle of the webpage." }, { "code": null, "e": 25420, "s": 25331, "text": "JavaScript: The JavaScript file will provide the logic behind the rotation of the hands." }, { "code": null, "e": 25429, "s": 25420, "text": "Example:" }, { "code": null, "e": 25492, "s": 25429, "text": "First we have selected the hour, minute, and second from HTML." }, { "code": null, "e": 25644, "s": 25492, "text": "To get the current time we have used the Date() object provided by the JavaScript. This will give the current seconds, minutes, and hours respectively." }, { "code": null, "e": 25881, "s": 25644, "text": "Now, we have got our hour, minute, and second, and we know that the clock rotates 360 degrees. So, we will convert to convert the rotation of the hands of the clock into degrees. The degree calculation is based on a simple unary method." }, { "code": null, "e": 25892, "s": 25881, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <link rel=\"stylesheet\" href=\"style.css\"> <script src=\"index.js\"></script></head><body> <div id=\"clockContainer\"> <div id=\"hour\"></div> <div id=\"minute\"></div> <div id=\"second\"></div> </div></body></html>", "e": 26167, "s": 25892, "text": null }, { "code": null, "e": 26177, "s": 26167, "text": "style.css" }, { "code": "#clockContainer { position: relative; margin: auto; height: 40vw; /*to make the height and width responsive*/ width: 40vw; background: url(clock.png) no-repeat; /*setting our background image*/ background-size: 100%;} #hour,#minute,#second { position: absolute; background: black; border-radius: 10px; transform-origin: bottom;} #hour { width: 1.8%; height: 25%; top: 25%; left: 48.85%; opacity: 0.8;} #minute { width: 1.6%; height: 30%; top: 19%; left: 48.9%; opacity: 0.8;} #second { width: 1%; height: 40%; top: 9%; left: 49.25%; opacity: 0.8;}", "e": 26810, "s": 26177, "text": null }, { "code": null, "e": 26819, "s": 26810, "text": "index,js" }, { "code": "setInterval(() => { d = new Date(); //object of date() hr = d.getHours(); min = d.getMinutes(); sec = d.getSeconds(); hr_rotation = 30 * hr + min / 2; //converting current time min_rotation = 6 * min; sec_rotation = 6 * sec; hour.style.transform = `rotate(${hr_rotation}deg)`; minute.style.transform = `rotate(${min_rotation}deg)`; second.style.transform = `rotate(${sec_rotation}deg)`;}, 1000);", "e": 27247, "s": 26819, "text": null }, { "code": null, "e": 27376, "s": 27247, "text": "Image used:https://media.geeksforgeeks.org/wp-content/uploads/20210302161254/imgonlinecomuaCompressToSizeOmNATjUMFKw-300×300.jpg" }, { "code": null, "e": 27384, "s": 27376, "text": "Output:" }, { "code": null, "e": 27398, "s": 27384, "text": "CSS-Questions" }, { "code": null, "e": 27413, "s": 27398, "text": "HTML-Questions" }, { "code": null, "e": 27434, "s": 27413, "text": "JavaScript-Questions" }, { "code": null, "e": 27438, "s": 27434, "text": "CSS" }, { "code": null, "e": 27443, "s": 27438, "text": "HTML" }, { "code": null, "e": 27454, "s": 27443, "text": "JavaScript" }, { "code": null, "e": 27471, "s": 27454, "text": "Web Technologies" }, { "code": null, "e": 27476, "s": 27471, "text": "HTML" }, { "code": null, "e": 27574, "s": 27476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27583, "s": 27574, "text": "Comments" }, { "code": null, "e": 27596, "s": 27583, "text": "Old Comments" }, { "code": null, "e": 27654, "s": 27596, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 27691, "s": 27654, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 27732, "s": 27691, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27769, "s": 27732, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27833, "s": 27769, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 27893, "s": 27833, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27954, "s": 27893, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 28004, "s": 27954, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28057, "s": 28004, "text": "Hide or show elements in HTML using display property" } ]
How to convert html pages to pdf using wkhtml2pdf
This article will guide you to install a tool which can convert your HTML pages or HTML output to PDF format. This feature will also be helpful to write a code for generating Pdf’s, if we need to send them to a group of customers or clients and for sending reports instead of HTML (which you can send them via emails in PDF format) that will be a value addition to your software. Open source and cross platform. Convert any HTML web pages to PDF files using WebKit engine. Options to add headers and footers Table of Content (TOC) generation option. Provides batch mode conversions. Support for PHP or Python via bindings to libwkhtmltox Need to install some required fonts which are used for wkhtmltopdf # yum install -y xorg-x11-fonts-75dpi # yum install -y xorg-x11-fonts-Type1 To get the file, please run the following # wget https://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2 To extract the files – # tar -xvzf wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2 -C /opt # cd /opt # mv wkhtmltopdf-amd64 wkhtmltopdf # mv wkhtmltopdf /usr/local/bin To convert any HTML web page to PDF, run the following example command. It will convert the given web pages to install-eclipse .pdf as as output to /opt directory. # wkhtmltopdf http://google.com/ /opt/google.pdf Sample Output: Loading pages (1/6) Counting pages (2/6) Resolving links (4/6) Loading headers and footers (5/6) Printing pages (6/6) Done After this installation, as mentioned earlier, now you really want a homepage and want to save it as a PDF, then you could use Wkhtmltopdf for that. Seriously, you could use it to generate invoices and save or send, create birthday cards and send them or save them or all other sorts of fun things. Just use your imagination! That we can save any web pages or html page into PDF format for further use.
[ { "code": null, "e": 1442, "s": 1062, "text": "This article will guide you to install a tool which can convert your HTML pages or HTML output to PDF format. This feature will also be helpful to write a code for generating Pdf’s, if we need to send them to a group of customers or clients and for sending reports instead of HTML (which you can send them via emails in PDF format) that will be a value addition to your software." }, { "code": null, "e": 1474, "s": 1442, "text": "Open source and cross platform." }, { "code": null, "e": 1535, "s": 1474, "text": "Convert any HTML web pages to PDF files using WebKit engine." }, { "code": null, "e": 1570, "s": 1535, "text": "Options to add headers and footers" }, { "code": null, "e": 1612, "s": 1570, "text": "Table of Content (TOC) generation option." }, { "code": null, "e": 1645, "s": 1612, "text": "Provides batch mode conversions." }, { "code": null, "e": 1700, "s": 1645, "text": "Support for PHP or Python via bindings to libwkhtmltox" }, { "code": null, "e": 1767, "s": 1700, "text": "Need to install some required fonts which are used for wkhtmltopdf" }, { "code": null, "e": 1843, "s": 1767, "text": "# yum install -y xorg-x11-fonts-75dpi\n# yum install -y xorg-x11-fonts-Type1" }, { "code": null, "e": 1885, "s": 1843, "text": "To get the file, please run the following" }, { "code": null, "e": 1977, "s": 1885, "text": "# wget https://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2" }, { "code": null, "e": 2000, "s": 1977, "text": "To extract the files –" }, { "code": null, "e": 2141, "s": 2000, "text": "# tar -xvzf wkhtmltopdf-0.10.0_rc2-static-amd64.tar.bz2 -C /opt\n# cd /opt\n# mv wkhtmltopdf-amd64 wkhtmltopdf\n# mv wkhtmltopdf /usr/local/bin" }, { "code": null, "e": 2305, "s": 2141, "text": "To convert any HTML web page to PDF, run the following example command. It will convert the given web pages to install-eclipse .pdf as as output to /opt directory." }, { "code": null, "e": 2492, "s": 2305, "text": "# wkhtmltopdf http://google.com/ /opt/google.pdf\nSample Output:\nLoading pages (1/6)\nCounting pages (2/6)\nResolving links (4/6)\nLoading headers and footers (5/6)\nPrinting pages (6/6)\nDone" }, { "code": null, "e": 2791, "s": 2492, "text": "After this installation, as mentioned earlier, now you really want a homepage and want to save it as a PDF, then you could use Wkhtmltopdf for that. Seriously, you could use it to generate invoices and save or send, create birthday cards and send them or save them or all other sorts of fun things." }, { "code": null, "e": 2895, "s": 2791, "text": "Just use your imagination! That we can save any web pages or html page into PDF format for further use." } ]
Add a grey background color to the Bootstrap 4 card
To add a gray background color to the Bootstrap 4 card, use the card class with the bg-dark contextual class − <div class="card bg-dark text-white"> Set the card body inside the same <div> class − <div class="card bg-dark text-white"> <div class="card-body">Hello</div> </div> Let us see the complete example add a grey background color to Bootstrap card − 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"> <h2>Welcome</h2> <div class="card bg-dark text-white"> <div class="card-body">Hello</div> </div> </div> </body> </html>
[ { "code": null, "e": 1173, "s": 1062, "text": "To add a gray background color to the Bootstrap 4 card, use the card class with the bg-dark contextual class −" }, { "code": null, "e": 1211, "s": 1173, "text": "<div class=\"card bg-dark text-white\">" }, { "code": null, "e": 1259, "s": 1211, "text": "Set the card body inside the same <div> class −" }, { "code": null, "e": 1341, "s": 1259, "text": "<div class=\"card bg-dark text-white\">\n <div class=\"card-body\">Hello</div>\n</div>" }, { "code": null, "e": 1421, "s": 1341, "text": "Let us see the complete example add a grey background color to Bootstrap card −" }, { "code": null, "e": 1431, "s": 1421, "text": "Live Demo" }, { "code": null, "e": 2101, "s": 1431, "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 <h2>Welcome</h2>\n <div class=\"card bg-dark text-white\">\n <div class=\"card-body\">Hello</div>\n </div>\n </div>\n</body>\n</html>" } ]
Check if a number is Primorial Prime or not - GeeksforGeeks
07 Sep, 2021 Given a positive number N, the task is to check if N is a primorial prime number or not. Print ‘YES’ if N is a primorial prime number otherwise print ‘NO.Primorial Prime: In Mathematics, A Primorial prime is a prime number of the form pn# + 1 or pn# – 1 , where pn# is the primorial of pn i.e the product of first n prime numbers.Examples: Input : N = 5 Output : YES 5 is Primorial prime of the form pn - 1 for n=2, Primorial is 2*3 = 6 and 6-1 =5. Input : N = 31 Output : YES 31 is Primorial prime of the form pn + 1 for n=3, Primorial is 2*3*5 = 30 and 30+1 = 31. The First few Primorial primes are: 2, 3, 5, 7, 29, 31, 211, 2309, 2311, 30029 Prerequisite: Primorial Sieve of Eratosthenes Approach: Generate all prime number in the range using Sieve of Eratosthenes.Check if n is prime or not, If n is not prime Then print NoElse, starting from first prime (i.e 2 ) start multiplying next prime number and keep checking if product + 1 = n or product – 1 = n or notIf either product+1=n or product-1=n, then n is a Primorial Prime Otherwise not. Generate all prime number in the range using Sieve of Eratosthenes. Check if n is prime or not, If n is not prime Then print No Else, starting from first prime (i.e 2 ) start multiplying next prime number and keep checking if product + 1 = n or product – 1 = n or not If either product+1=n or product-1=n, then n is a Primorial Prime Otherwise not. Below is the implementation of above approach: C++ Java Python 3 C# PHP Javascript // CPP program to check Primorial Prime #include <bits/stdc++.h>using namespace std; #define MAX 10000 vector<int> arr; bool prime[MAX]; // Function to generate prime numbersvoid SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. memset(prime, true, sizeof(prime)); for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < MAX; i += p) prime[i] = false; } } // store all prime numbers // to vector 'arr' for (int p = 2; p < MAX; p++) if (prime[p]) arr.push_back(p);} // Function to check the number for Primorial primebool isPrimorialPrime(long n){ // If n is not prime Number // return false if (!prime[n]) return false; long long product = 1; int i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or Product-1 =n // holds or not product = product * arr[i]; if (product + 1 == n || product - 1 == n) return true; i++; } return false;} // Driver codeint main(){ SieveOfEratosthenes(); long n = 31; // Check if n is Primorial Prime if (isPrimorialPrime(n)) cout << "YES\n"; else cout << "NO\n"; return 0;} // Java program to check Primorial prime import java.util.*; class GFG { static final int MAX = 1000000; static Vector<Integer> arr = new Vector<Integer>(); static boolean[] prime = new boolean[MAX]; // Function to get the prime numbers static void SieveOfEratosthenes() { // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (int i = 0; i < MAX; i++) prime[i] = true; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < MAX; i += p) prime[i] = false; } } // store all prime numbers // to vector 'arr' for (int p = 2; p < MAX; p++) if (prime[p]) arr.add(p); } // Function to check the number for Primorial prime static boolean isPrimorialPrime(int n) { // If n is not prime // Then return false if (!prime[n]) return false; long product = 1; int i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or product -1=n // holds or not product = product * arr.get(i); if (product + 1 == n || product - 1 == n) return true; i++; } return false; } // Driver Code public static void main(String[] args) { SieveOfEratosthenes(); int n = 31; if (isPrimorialPrime(n)) System.out.println("YES"); else System.out.println("NO"); }} # Python3 Program to check Primorial Prime # from math lib import sqrt methodfrom math import sqrt MAX = 100000 # Create a boolean array "prime[0..n]"# and initialize make all entries of# boolean array 'prime' as true.# A value in prime[i] will finally be# false if i is Not a prime, else true.prime = [True] * MAX arr = [] # Utility function to generate# prime numbersdef SieveOfEratosthenes() : for p in range(2, int(sqrt(MAX)) + 1) : # If prime[p] is not changed, # then it is a prime if prime[p] == True : # Update all multiples of p for i in range(p * 2 , MAX, p) : prime[i] = False # store all prime numbers # to list 'arr' for p in range(2, MAX) : if prime[p] : arr.append(p) # Function to check the number# for Primorial primedef isPrimorialPrime(n) : # If n is not prime Number # return false if not prime[n] : return False product, i = 1, 0 # Multiply next prime number # and check if product + 1 = n # or Product-1 = n holds or not while product < n : product *= arr[i] if product + 1 == n or product - 1 == n : return True i += 1 return False # Driver codeif __name__ == "__main__" : SieveOfEratosthenes() n = 31 # Check if n is Primorial Prime if (isPrimorialPrime(n)) : print("YES") else : print("NO") # This code is contributed by ANKITRAI1 // c# program to check Primorial primeusing System;using System.Collections.Generic; public class GFG{ public const int MAX = 1000000; public static List<int> arr = new List<int>(); public static bool[] prime = new bool[MAX]; // Function to get the prime numbers public static void SieveOfEratosthenes() { // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (int i = 0; i < MAX; i++) { prime[i] = true; } for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < MAX; i += p) { prime[i] = false; } } } // store all prime numbers // to vector 'arr' for (int p = 2; p < MAX; p++) { if (prime[p]) { arr.Add(p); } } } // Function to check the number for Primorial prime public static bool isPrimorialPrime(int n) { // If n is not prime // Then return false if (!prime[n]) { return false; } long product = 1; int i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or product -1=n // holds or not product = product * arr[i]; if (product + 1 == n || product - 1 == n) { return true; } i++; } return false; } // Driver Code public static void Main(string[] args) { SieveOfEratosthenes(); int n = 31; if (isPrimorialPrime(n)) { Console.WriteLine("YES"); } else { Console.WriteLine("NO"); } }} // This code is contributed by Shrikant13 <?php// PHP Program to check Primorial Prime$MAX = 100000; // Create a boolean array "prime[0..n]"// and initialize make all entries of// boolean array 'prime' as true.// A value in prime[i] will finally be// false if i is Not a prime, else true.$prime = array_fill(0, $MAX, true); $arr = array(); // Utility function to generate// prime numbersfunction SieveOfEratosthenes(){ global $MAX, $prime, $arr; for($p = 2; $p <= (int)(sqrt($MAX)); $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) // Update all multiples of p for ($i = $p * 2; $i < $MAX; $i += $p) $prime[$i] = false; } // store all prime numbers // to list 'arr' for ($p = 2; $p < $MAX; $p++) if ($prime[$p]) array_push($arr, $p);} // Function to check the number// for Primorial primefunction isPrimorialPrime($n){ global $MAX, $prime, $arr; // If n is not prime Number // return false if(!$prime[$n]) return false; $product = 1; $i = 0; // Multiply next prime number // and check if product + 1 = n // or Product-1 = n holds or not while ($product < $n) { $product *= $arr[$i]; if ($product + 1 == $n || $product - 1 == $n ) return true; $i += 1; } return false;} // Driver codeSieveOfEratosthenes(); $n = 31; // Check if n is Primorial Primeif (isPrimorialPrime($n)) print("YES");else print("NO"); // This code is contributed by mits <script> // Javascript program to check Primorial Prime var MAX = 10000; var arr = []; var prime = Array(MAX).fill(true); // Function to generate prime numbersfunction SieveOfEratosthenes(){ // Create a boolean array "prime[0..n]" and initialize // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (var p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i < MAX; i += p) prime[i] = false; } } // store all prime numbers // to vector 'arr' for (var p = 2; p < MAX; p++) if (prime[p]) arr.push(p);} // Function to check the number for Primorial primefunction isPrimorialPrime(n){ // If n is not prime Number // return false if (!prime[n]) return false; var product = 1; var i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or Product-1 =n // holds or not product = product * arr[i]; if (product + 1 == n || product - 1 == n) return true; i++; } return false;} // Driver codeSieveOfEratosthenes();var n = 31;// Check if n is Primorial Primeif (isPrimorialPrime(n)) document.write( "YES");else document.write("NO"); </script> YES shrikanth13 ankthon Mithun Kumar noob2000 sumitgumber28 number-theory Prime Number series sieve Mathematical number-theory Mathematical Prime Number series sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Segment Tree | Set 1 (Sum of given range) Modular multiplicative inverse Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Check if a number is Palindrome Program to multiply two matrices Merge two sorted arrays with O(1) extra space Generate all permutation of a set in Python Count ways to reach the n'th stair
[ { "code": null, "e": 25937, "s": 25909, "text": "\n07 Sep, 2021" }, { "code": null, "e": 26279, "s": 25937, "text": "Given a positive number N, the task is to check if N is a primorial prime number or not. Print ‘YES’ if N is a primorial prime number otherwise print ‘NO.Primorial Prime: In Mathematics, A Primorial prime is a prime number of the form pn# + 1 or pn# – 1 , where pn# is the primorial of pn i.e the product of first n prime numbers.Examples: " }, { "code": null, "e": 26510, "s": 26279, "text": "Input : N = 5\nOutput : YES\n5 is Primorial prime of the form pn - 1 \nfor n=2, Primorial is 2*3 = 6\nand 6-1 =5.\n\nInput : N = 31\nOutput : YES\n31 is Primorial prime of the form pn + 1 \nfor n=3, Primorial is 2*3*5 = 30\nand 30+1 = 31." }, { "code": null, "e": 26548, "s": 26510, "text": "The First few Primorial primes are: " }, { "code": null, "e": 26593, "s": 26548, "text": "2, 3, 5, 7, 29, 31, 211, 2309, 2311, 30029 " }, { "code": null, "e": 26611, "s": 26595, "text": "Prerequisite: " }, { "code": null, "e": 26621, "s": 26611, "text": "Primorial" }, { "code": null, "e": 26643, "s": 26621, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 26655, "s": 26643, "text": "Approach: " }, { "code": null, "e": 27001, "s": 26655, "text": "Generate all prime number in the range using Sieve of Eratosthenes.Check if n is prime or not, If n is not prime Then print NoElse, starting from first prime (i.e 2 ) start multiplying next prime number and keep checking if product + 1 = n or product – 1 = n or notIf either product+1=n or product-1=n, then n is a Primorial Prime Otherwise not." }, { "code": null, "e": 27069, "s": 27001, "text": "Generate all prime number in the range using Sieve of Eratosthenes." }, { "code": null, "e": 27129, "s": 27069, "text": "Check if n is prime or not, If n is not prime Then print No" }, { "code": null, "e": 27269, "s": 27129, "text": "Else, starting from first prime (i.e 2 ) start multiplying next prime number and keep checking if product + 1 = n or product – 1 = n or not" }, { "code": null, "e": 27350, "s": 27269, "text": "If either product+1=n or product-1=n, then n is a Primorial Prime Otherwise not." }, { "code": null, "e": 27398, "s": 27350, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27402, "s": 27398, "text": "C++" }, { "code": null, "e": 27407, "s": 27402, "text": "Java" }, { "code": null, "e": 27416, "s": 27407, "text": "Python 3" }, { "code": null, "e": 27419, "s": 27416, "text": "C#" }, { "code": null, "e": 27423, "s": 27419, "text": "PHP" }, { "code": null, "e": 27434, "s": 27423, "text": "Javascript" }, { "code": "// CPP program to check Primorial Prime #include <bits/stdc++.h>using namespace std; #define MAX 10000 vector<int> arr; bool prime[MAX]; // Function to generate prime numbersvoid SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. memset(prime, true, sizeof(prime)); for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < MAX; i += p) prime[i] = false; } } // store all prime numbers // to vector 'arr' for (int p = 2; p < MAX; p++) if (prime[p]) arr.push_back(p);} // Function to check the number for Primorial primebool isPrimorialPrime(long n){ // If n is not prime Number // return false if (!prime[n]) return false; long long product = 1; int i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or Product-1 =n // holds or not product = product * arr[i]; if (product + 1 == n || product - 1 == n) return true; i++; } return false;} // Driver codeint main(){ SieveOfEratosthenes(); long n = 31; // Check if n is Primorial Prime if (isPrimorialPrime(n)) cout << \"YES\\n\"; else cout << \"NO\\n\"; return 0;}", "e": 28983, "s": 27434, "text": null }, { "code": "// Java program to check Primorial prime import java.util.*; class GFG { static final int MAX = 1000000; static Vector<Integer> arr = new Vector<Integer>(); static boolean[] prime = new boolean[MAX]; // Function to get the prime numbers static void SieveOfEratosthenes() { // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (int i = 0; i < MAX; i++) prime[i] = true; for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < MAX; i += p) prime[i] = false; } } // store all prime numbers // to vector 'arr' for (int p = 2; p < MAX; p++) if (prime[p]) arr.add(p); } // Function to check the number for Primorial prime static boolean isPrimorialPrime(int n) { // If n is not prime // Then return false if (!prime[n]) return false; long product = 1; int i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or product -1=n // holds or not product = product * arr.get(i); if (product + 1 == n || product - 1 == n) return true; i++; } return false; } // Driver Code public static void main(String[] args) { SieveOfEratosthenes(); int n = 31; if (isPrimorialPrime(n)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }}", "e": 30777, "s": 28983, "text": null }, { "code": "# Python3 Program to check Primorial Prime # from math lib import sqrt methodfrom math import sqrt MAX = 100000 # Create a boolean array \"prime[0..n]\"# and initialize make all entries of# boolean array 'prime' as true.# A value in prime[i] will finally be# false if i is Not a prime, else true.prime = [True] * MAX arr = [] # Utility function to generate# prime numbersdef SieveOfEratosthenes() : for p in range(2, int(sqrt(MAX)) + 1) : # If prime[p] is not changed, # then it is a prime if prime[p] == True : # Update all multiples of p for i in range(p * 2 , MAX, p) : prime[i] = False # store all prime numbers # to list 'arr' for p in range(2, MAX) : if prime[p] : arr.append(p) # Function to check the number# for Primorial primedef isPrimorialPrime(n) : # If n is not prime Number # return false if not prime[n] : return False product, i = 1, 0 # Multiply next prime number # and check if product + 1 = n # or Product-1 = n holds or not while product < n : product *= arr[i] if product + 1 == n or product - 1 == n : return True i += 1 return False # Driver codeif __name__ == \"__main__\" : SieveOfEratosthenes() n = 31 # Check if n is Primorial Prime if (isPrimorialPrime(n)) : print(\"YES\") else : print(\"NO\") # This code is contributed by ANKITRAI1", "e": 32247, "s": 30777, "text": null }, { "code": "// c# program to check Primorial primeusing System;using System.Collections.Generic; public class GFG{ public const int MAX = 1000000; public static List<int> arr = new List<int>(); public static bool[] prime = new bool[MAX]; // Function to get the prime numbers public static void SieveOfEratosthenes() { // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (int i = 0; i < MAX; i++) { prime[i] = true; } for (int p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i < MAX; i += p) { prime[i] = false; } } } // store all prime numbers // to vector 'arr' for (int p = 2; p < MAX; p++) { if (prime[p]) { arr.Add(p); } } } // Function to check the number for Primorial prime public static bool isPrimorialPrime(int n) { // If n is not prime // Then return false if (!prime[n]) { return false; } long product = 1; int i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or product -1=n // holds or not product = product * arr[i]; if (product + 1 == n || product - 1 == n) { return true; } i++; } return false; } // Driver Code public static void Main(string[] args) { SieveOfEratosthenes(); int n = 31; if (isPrimorialPrime(n)) { Console.WriteLine(\"YES\"); } else { Console.WriteLine(\"NO\"); } }} // This code is contributed by Shrikant13", "e": 34315, "s": 32247, "text": null }, { "code": "<?php// PHP Program to check Primorial Prime$MAX = 100000; // Create a boolean array \"prime[0..n]\"// and initialize make all entries of// boolean array 'prime' as true.// A value in prime[i] will finally be// false if i is Not a prime, else true.$prime = array_fill(0, $MAX, true); $arr = array(); // Utility function to generate// prime numbersfunction SieveOfEratosthenes(){ global $MAX, $prime, $arr; for($p = 2; $p <= (int)(sqrt($MAX)); $p++) { // If prime[p] is not changed, // then it is a prime if ($prime[$p] == true) // Update all multiples of p for ($i = $p * 2; $i < $MAX; $i += $p) $prime[$i] = false; } // store all prime numbers // to list 'arr' for ($p = 2; $p < $MAX; $p++) if ($prime[$p]) array_push($arr, $p);} // Function to check the number// for Primorial primefunction isPrimorialPrime($n){ global $MAX, $prime, $arr; // If n is not prime Number // return false if(!$prime[$n]) return false; $product = 1; $i = 0; // Multiply next prime number // and check if product + 1 = n // or Product-1 = n holds or not while ($product < $n) { $product *= $arr[$i]; if ($product + 1 == $n || $product - 1 == $n ) return true; $i += 1; } return false;} // Driver codeSieveOfEratosthenes(); $n = 31; // Check if n is Primorial Primeif (isPrimorialPrime($n)) print(\"YES\");else print(\"NO\"); // This code is contributed by mits", "e": 35858, "s": 34315, "text": null }, { "code": "<script> // Javascript program to check Primorial Prime var MAX = 10000; var arr = []; var prime = Array(MAX).fill(true); // Function to generate prime numbersfunction SieveOfEratosthenes(){ // Create a boolean array \"prime[0..n]\" and initialize // make all entries of boolean array 'prime' // as true. A value in prime[i] will // finally be false if i is Not a prime, else true. for (var p = 2; p * p < MAX; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (var i = p * 2; i < MAX; i += p) prime[i] = false; } } // store all prime numbers // to vector 'arr' for (var p = 2; p < MAX; p++) if (prime[p]) arr.push(p);} // Function to check the number for Primorial primefunction isPrimorialPrime(n){ // If n is not prime Number // return false if (!prime[n]) return false; var product = 1; var i = 0; while (product < n) { // Multiply next prime number // and check if product + 1 = n or Product-1 =n // holds or not product = product * arr[i]; if (product + 1 == n || product - 1 == n) return true; i++; } return false;} // Driver codeSieveOfEratosthenes();var n = 31;// Check if n is Primorial Primeif (isPrimorialPrime(n)) document.write( \"YES\");else document.write(\"NO\"); </script>", "e": 37310, "s": 35858, "text": null }, { "code": null, "e": 37314, "s": 37310, "text": "YES" }, { "code": null, "e": 37328, "s": 37316, "text": "shrikanth13" }, { "code": null, "e": 37336, "s": 37328, "text": "ankthon" }, { "code": null, "e": 37349, "s": 37336, "text": "Mithun Kumar" }, { "code": null, "e": 37358, "s": 37349, "text": "noob2000" }, { "code": null, "e": 37372, "s": 37358, "text": "sumitgumber28" }, { "code": null, "e": 37386, "s": 37372, "text": "number-theory" }, { "code": null, "e": 37399, "s": 37386, "text": "Prime Number" }, { "code": null, "e": 37406, "s": 37399, "text": "series" }, { "code": null, "e": 37412, "s": 37406, "text": "sieve" }, { "code": null, "e": 37425, "s": 37412, "text": "Mathematical" }, { "code": null, "e": 37439, "s": 37425, "text": "number-theory" }, { "code": null, "e": 37452, "s": 37439, "text": "Mathematical" }, { "code": null, "e": 37465, "s": 37452, "text": "Prime Number" }, { "code": null, "e": 37472, "s": 37465, "text": "series" }, { "code": null, "e": 37478, "s": 37472, "text": "sieve" }, { "code": null, "e": 37576, "s": 37478, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37620, "s": 37576, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 37662, "s": 37620, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 37693, "s": 37662, "text": "Modular multiplicative inverse" }, { "code": null, "e": 37764, "s": 37693, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 37789, "s": 37764, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 37821, "s": 37789, "text": "Check if a number is Palindrome" }, { "code": null, "e": 37854, "s": 37821, "text": "Program to multiply two matrices" }, { "code": null, "e": 37900, "s": 37854, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 37944, "s": 37900, "text": "Generate all permutation of a set in Python" } ]
jQWidgets jqxLayout render() Method - GeeksforGeeks
10 Dec, 2021 jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxLayout is used for representing a jQuery widget that is used for the creation of complex layouts with nested, resized, pinned, unpinned, and closed panels. The render() method is used for rendering the specified jqxLayout widget. Syntax: $('#jqxLayout').jqxLayout('render'); Parameters: This method does not accept any parameters. Return Values: This method does not return any values. Linked Files: Download jQWidgets from the given link. In the HTML file, locate the script files in the downloaded folder. <link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqxbuttons.js”></script><script type=”text/javascript” src=”jqwidgets/jqxribbon.js”></script><script type=”text/javascript” src=”jqwidgets/jqxlayout.js”></script><script type=”text/javascript” src=”jqwidgets/jqx-all.js”></script> Example: The below example illustrates the jQWidgets jqxLayout render() method. HTML <!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="jqwidgets/styles/jqx.base.css" type="text/css"/> <script type="text/javascript" src="scripts/jquery.js"> </script> <script type="text/javascript" src="jqwidgets/jqxcore.js"> </script> <script type="text/javascript" src="jqwidgets/jqxbuttons.js"> </script> <script type="text/javascript" src="jqwidgets/jqxribbon.js"> </script> <script type="text/javascript" src="jqwidgets/jqxlayout.js"> </script> <script type="text/javascript" src="jqwidgets/jqx-all.js"> </script></head> <body> <center> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> jQWidgets jqxLayout render() Method </h3> <div id="jqx_Layout"> <div data-container="A1"> <li>It is a computer science portal.</li> </div> <div data-container="A2"> <li>It is a eCommerce platform.</li> </div> <div data-container="A3"> <li>It is a service based company.</li> </div> </div> <input type="button" style="margin: 5px;" id="button_for_render" value="Render the above widget"/> <div id="log"></div> <script type="text/javascript"> $(document).ready(function () { var jqx_Layout = [{ items: [{ items: [{ items: [{ contentContainer: 'A1', type: 'documentPanel', title: 'GeeksforGeeks', }, { contentContainer: 'A2', type: 'documentPanel', title: 'Amazon', }, { contentContainer: 'A3', type: 'documentPanel', title: 'Capgemini', }], type: 'documentGroup', height: 100, },], type: 'layoutGroup', height: 100, }], orientation: 'vertical', type: 'layoutGroup' }]; $('#jqx_Layout').jqxLayout({ width: 370, height: 100, layout: jqx_Layout }); $("#button_for_render").jqxButton({ width: 300 }); $('#button_for_render').jqxButton(). click(function () { $('#jqx_Layout').jqxLayout('render'); }) }); </script> </center></body></html> Output: Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxlayout/jquery-layout-api.htm?search= jQuery-jQWidgets jQWidgets-jqxLayout JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to prevent Body from scrolling when a modal is opened using jQuery ? How to Become a Full Stack Web Developer in 2021? jQuery getJSON() Method jQuery | focus() with Examples jQuery | removeAttr() with Examples Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26954, "s": 26926, "text": "\n10 Dec, 2021" }, { "code": null, "e": 27302, "s": 26954, "text": "jQWidgets is a JavaScript framework for making web-based applications for PC and mobile devices. It is a very powerful, optimized, platform-independent, and widely supported framework. The jqxLayout is used for representing a jQuery widget that is used for the creation of complex layouts with nested, resized, pinned, unpinned, and closed panels." }, { "code": null, "e": 27376, "s": 27302, "text": "The render() method is used for rendering the specified jqxLayout widget." }, { "code": null, "e": 27384, "s": 27376, "text": "Syntax:" }, { "code": null, "e": 27421, "s": 27384, "text": "$('#jqxLayout').jqxLayout('render');" }, { "code": null, "e": 27477, "s": 27421, "text": "Parameters: This method does not accept any parameters." }, { "code": null, "e": 27532, "s": 27477, "text": "Return Values: This method does not return any values." }, { "code": null, "e": 27654, "s": 27532, "text": "Linked Files: Download jQWidgets from the given link. In the HTML file, locate the script files in the downloaded folder." }, { "code": null, "e": 28139, "s": 27654, "text": "<link rel=”stylesheet” href=”jqwidgets/styles/jqx.base.css” type=”text/css” /><script type=”text/javascript” src=”scripts/jquery.js”></script><script type=”text/javascript” src=”jqwidgets/jqxcore.js”></script><script type=”text/javascript” src=”jqwidgets/jqxbuttons.js”></script><script type=”text/javascript” src=”jqwidgets/jqxribbon.js”></script><script type=”text/javascript” src=”jqwidgets/jqxlayout.js”></script><script type=”text/javascript” src=”jqwidgets/jqx-all.js”></script>" }, { "code": null, "e": 28219, "s": 28139, "text": "Example: The below example illustrates the jQWidgets jqxLayout render() method." }, { "code": null, "e": 28224, "s": 28219, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"jqwidgets/styles/jqx.base.css\" type=\"text/css\"/> <script type=\"text/javascript\" src=\"scripts/jquery.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxcore.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxbuttons.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxribbon.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqxlayout.js\"> </script> <script type=\"text/javascript\" src=\"jqwidgets/jqx-all.js\"> </script></head> <body> <center> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h3> jQWidgets jqxLayout render() Method </h3> <div id=\"jqx_Layout\"> <div data-container=\"A1\"> <li>It is a computer science portal.</li> </div> <div data-container=\"A2\"> <li>It is a eCommerce platform.</li> </div> <div data-container=\"A3\"> <li>It is a service based company.</li> </div> </div> <input type=\"button\" style=\"margin: 5px;\" id=\"button_for_render\" value=\"Render the above widget\"/> <div id=\"log\"></div> <script type=\"text/javascript\"> $(document).ready(function () { var jqx_Layout = [{ items: [{ items: [{ items: [{ contentContainer: 'A1', type: 'documentPanel', title: 'GeeksforGeeks', }, { contentContainer: 'A2', type: 'documentPanel', title: 'Amazon', }, { contentContainer: 'A3', type: 'documentPanel', title: 'Capgemini', }], type: 'documentGroup', height: 100, },], type: 'layoutGroup', height: 100, }], orientation: 'vertical', type: 'layoutGroup' }]; $('#jqx_Layout').jqxLayout({ width: 370, height: 100, layout: jqx_Layout }); $(\"#button_for_render\").jqxButton({ width: 300 }); $('#button_for_render').jqxButton(). click(function () { $('#jqx_Layout').jqxLayout('render'); }) }); </script> </center></body></html>", "e": 31206, "s": 28224, "text": null }, { "code": null, "e": 31214, "s": 31206, "text": "Output:" }, { "code": null, "e": 31334, "s": 31214, "text": "Reference: https://www.jqwidgets.com/jquery-widgets-documentation/documentation/jqxlayout/jquery-layout-api.htm?search=" }, { "code": null, "e": 31351, "s": 31334, "text": "jQuery-jQWidgets" }, { "code": null, "e": 31371, "s": 31351, "text": "jQWidgets-jqxLayout" }, { "code": null, "e": 31378, "s": 31371, "text": "JQuery" }, { "code": null, "e": 31395, "s": 31378, "text": "Web Technologies" }, { "code": null, "e": 31493, "s": 31395, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31566, "s": 31493, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 31616, "s": 31566, "text": "How to Become a Full Stack Web Developer in 2021?" }, { "code": null, "e": 31640, "s": 31616, "text": "jQuery getJSON() Method" }, { "code": null, "e": 31671, "s": 31640, "text": "jQuery | focus() with Examples" }, { "code": null, "e": 31707, "s": 31671, "text": "jQuery | removeAttr() with Examples" }, { "code": null, "e": 31747, "s": 31707, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31780, "s": 31747, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31825, "s": 31780, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31887, "s": 31825, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
CSS :focus-within Selector - GeeksforGeeks
18 Sep, 2020 The :focus-within pseudo-class is a selects an element that consists of a focused element as a child. The CSS rules are applied when any child element gets focus. Example includes clicking a link, selecting an input, etc. Syntax: :focus { /* CSS Properties */ } Example: Below is the example which illustrates the use of :focus-within pseudo-class Selector. HTML <!DOCTYPE html><html lang="en"> <head> <style> form { border: 2px solid red; padding: 15px; width: 30%; } form:focus-within { background: #ff8; color: black; } input { margin: 5px; } </style></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <form> <label>Geek 1</label> <input type="text"> <br> <label>Geek 2</label> <input type="text"> </form></body> </html> Output: Supported Browsers: Chrome Firefox Edge Opera Safari Internet Explorer (Not Supported). CSS-Selectors CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a web page using HTML and CSS Form validation using jQuery How to style a checkbox using CSS? Search Bar using HTML, CSS and JavaScript 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26621, "s": 26593, "text": "\n18 Sep, 2020" }, { "code": null, "e": 26843, "s": 26621, "text": "The :focus-within pseudo-class is a selects an element that consists of a focused element as a child. The CSS rules are applied when any child element gets focus. Example includes clicking a link, selecting an input, etc." }, { "code": null, "e": 26851, "s": 26843, "text": "Syntax:" }, { "code": null, "e": 26887, "s": 26851, "text": ":focus {\n /* CSS Properties */\n}" }, { "code": null, "e": 26983, "s": 26887, "text": "Example: Below is the example which illustrates the use of :focus-within pseudo-class Selector." }, { "code": null, "e": 26988, "s": 26983, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> form { border: 2px solid red; padding: 15px; width: 30%; } form:focus-within { background: #ff8; color: black; } input { margin: 5px; } </style></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <form> <label>Geek 1</label> <input type=\"text\"> <br> <label>Geek 2</label> <input type=\"text\"> </form></body> </html>", "e": 27539, "s": 26988, "text": null }, { "code": null, "e": 27547, "s": 27539, "text": "Output:" }, { "code": null, "e": 27567, "s": 27547, "text": "Supported Browsers:" }, { "code": null, "e": 27574, "s": 27567, "text": "Chrome" }, { "code": null, "e": 27582, "s": 27574, "text": "Firefox" }, { "code": null, "e": 27587, "s": 27582, "text": "Edge" }, { "code": null, "e": 27593, "s": 27587, "text": "Opera" }, { "code": null, "e": 27600, "s": 27593, "text": "Safari" }, { "code": null, "e": 27635, "s": 27600, "text": "Internet Explorer (Not Supported)." }, { "code": null, "e": 27649, "s": 27635, "text": "CSS-Selectors" }, { "code": null, "e": 27653, "s": 27649, "text": "CSS" }, { "code": null, "e": 27670, "s": 27653, "text": "Web Technologies" }, { "code": null, "e": 27768, "s": 27670, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27807, "s": 27768, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27844, "s": 27807, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27873, "s": 27844, "text": "Form validation using jQuery" }, { "code": null, "e": 27908, "s": 27873, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 27950, "s": 27908, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27990, "s": 27950, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28023, "s": 27990, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28068, "s": 28023, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28111, "s": 28068, "text": "How to fetch data from an API in ReactJS ?" } ]
Image Processing in Java - Creating a Mirror Image - GeeksforGeeks
14 Nov, 2021 Prerequisite: Image Processing in Java – Read and Write Image Processing In Java – Get and Set Pixels Image Processing in Java – Colored Image to Grayscale Image Conversion Image Processing in Java – Colored Image to Negative Image Conversion Image Processing in Java – Colored to Red Green Blue Image Conversion Image Processing in Java – Colored Image to Sepia Image Conversion Image Processing in Java – Creating a Random Pixel Image In this set, we will be creating a mirror image. The image of an object as seen in a mirror is its mirror reflection or mirror image. In such an image, the object’s right side appears on the left side and vice versa. A mirror image is therefore said to be laterally inverted, and the phenomenon is called lateral inversion. The main trick is to get the source pixel values from left to right and set the same in the resulting image from right to left. Read the source image in a BufferedImage to read the given image.Get the dimensions of the given image.Create another BufferedImage object of the same dimension to hold the mirror image.Get ARGB (Alpha, Red, Green, and Blue) values from the source image [in left to right fashion].Set ARGB (Alpha, Red, Green, and Blue) to newly created image [in the right to left fashion].Repeat steps 4 and 5 for each pixel of the image. Read the source image in a BufferedImage to read the given image. Get the dimensions of the given image. Create another BufferedImage object of the same dimension to hold the mirror image. Get ARGB (Alpha, Red, Green, and Blue) values from the source image [in left to right fashion]. Set ARGB (Alpha, Red, Green, and Blue) to newly created image [in the right to left fashion]. Repeat steps 4 and 5 for each pixel of the image. Java // Java program to demonstrate// creation of a mirror image import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class MirrorImage { public static void main(String args[]) throws IOException { // BufferedImage for source image BufferedImage simg = null; // File object File f = null; // Read source image file try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png"); simg = ImageIO.read(f); } catch (IOException e) { System.out.println("Error: " + e); } // Get source image dimension int width = simg.getWidth(); int height = simg.getHeight(); // BufferedImage for mirror image BufferedImage mimg = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB); // Create mirror image pixel by pixel for (int y = 0; y < height; y++) { for (int lx = 0, rx = width - 1; lx < width; lx++, rx--) { // lx starts from the left side of the image // rx starts from the right side of the // image lx is used since we are getting // pixel from left side rx is used to set // from right side get source pixel value int p = simg.getRGB(lx, y); // set mirror image pixel value mimg.setRGB(rx, y, p); } } // save mirror image try { f = new File( "C:/Users/hp/Desktop/Image Processing in Java/GFG.png"); ImageIO.write(mimg, "png", f); } catch (IOException e) { System.out.println("Error: " + e); } }} Note: This code will not run on online ide since it requires an image in the drive. This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above. nishkarshgandhi Image-Processing Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Interfaces in Java Singleton Class in Java Set in Java Multithreading in Java Collections in Java Queue Interface In Java Initializing a List in Java LinkedList in Java Overriding in Java
[ { "code": null, "e": 26179, "s": 26151, "text": "\n14 Nov, 2021" }, { "code": null, "e": 26194, "s": 26179, "text": "Prerequisite: " }, { "code": null, "e": 26236, "s": 26194, "text": "Image Processing in Java – Read and Write" }, { "code": null, "e": 26282, "s": 26236, "text": "Image Processing In Java – Get and Set Pixels" }, { "code": null, "e": 26353, "s": 26282, "text": "Image Processing in Java – Colored Image to Grayscale Image Conversion" }, { "code": null, "e": 26423, "s": 26353, "text": "Image Processing in Java – Colored Image to Negative Image Conversion" }, { "code": null, "e": 26493, "s": 26423, "text": "Image Processing in Java – Colored to Red Green Blue Image Conversion" }, { "code": null, "e": 26560, "s": 26493, "text": "Image Processing in Java – Colored Image to Sepia Image Conversion" }, { "code": null, "e": 26617, "s": 26560, "text": "Image Processing in Java – Creating a Random Pixel Image" }, { "code": null, "e": 27069, "s": 26617, "text": "In this set, we will be creating a mirror image. The image of an object as seen in a mirror is its mirror reflection or mirror image. In such an image, the object’s right side appears on the left side and vice versa. A mirror image is therefore said to be laterally inverted, and the phenomenon is called lateral inversion. The main trick is to get the source pixel values from left to right and set the same in the resulting image from right to left." }, { "code": null, "e": 27493, "s": 27069, "text": "Read the source image in a BufferedImage to read the given image.Get the dimensions of the given image.Create another BufferedImage object of the same dimension to hold the mirror image.Get ARGB (Alpha, Red, Green, and Blue) values from the source image [in left to right fashion].Set ARGB (Alpha, Red, Green, and Blue) to newly created image [in the right to left fashion].Repeat steps 4 and 5 for each pixel of the image." }, { "code": null, "e": 27559, "s": 27493, "text": "Read the source image in a BufferedImage to read the given image." }, { "code": null, "e": 27598, "s": 27559, "text": "Get the dimensions of the given image." }, { "code": null, "e": 27682, "s": 27598, "text": "Create another BufferedImage object of the same dimension to hold the mirror image." }, { "code": null, "e": 27778, "s": 27682, "text": "Get ARGB (Alpha, Red, Green, and Blue) values from the source image [in left to right fashion]." }, { "code": null, "e": 27872, "s": 27778, "text": "Set ARGB (Alpha, Red, Green, and Blue) to newly created image [in the right to left fashion]." }, { "code": null, "e": 27922, "s": 27872, "text": "Repeat steps 4 and 5 for each pixel of the image." }, { "code": null, "e": 27927, "s": 27922, "text": "Java" }, { "code": "// Java program to demonstrate// creation of a mirror image import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO; public class MirrorImage { public static void main(String args[]) throws IOException { // BufferedImage for source image BufferedImage simg = null; // File object File f = null; // Read source image file try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/gfg-logo.png\"); simg = ImageIO.read(f); } catch (IOException e) { System.out.println(\"Error: \" + e); } // Get source image dimension int width = simg.getWidth(); int height = simg.getHeight(); // BufferedImage for mirror image BufferedImage mimg = new BufferedImage( width, height, BufferedImage.TYPE_INT_ARGB); // Create mirror image pixel by pixel for (int y = 0; y < height; y++) { for (int lx = 0, rx = width - 1; lx < width; lx++, rx--) { // lx starts from the left side of the image // rx starts from the right side of the // image lx is used since we are getting // pixel from left side rx is used to set // from right side get source pixel value int p = simg.getRGB(lx, y); // set mirror image pixel value mimg.setRGB(rx, y, p); } } // save mirror image try { f = new File( \"C:/Users/hp/Desktop/Image Processing in Java/GFG.png\"); ImageIO.write(mimg, \"png\", f); } catch (IOException e) { System.out.println(\"Error: \" + e); } }}", "e": 29763, "s": 27927, "text": null }, { "code": null, "e": 29847, "s": 29763, "text": "Note: This code will not run on online ide since it requires an image in the drive." }, { "code": null, "e": 30269, "s": 29847, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above." }, { "code": null, "e": 30285, "s": 30269, "text": "nishkarshgandhi" }, { "code": null, "e": 30302, "s": 30285, "text": "Image-Processing" }, { "code": null, "e": 30307, "s": 30302, "text": "Java" }, { "code": null, "e": 30312, "s": 30307, "text": "Java" }, { "code": null, "e": 30410, "s": 30312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30425, "s": 30410, "text": "Stream In Java" }, { "code": null, "e": 30444, "s": 30425, "text": "Interfaces in Java" }, { "code": null, "e": 30468, "s": 30444, "text": "Singleton Class in Java" }, { "code": null, "e": 30480, "s": 30468, "text": "Set in Java" }, { "code": null, "e": 30503, "s": 30480, "text": "Multithreading in Java" }, { "code": null, "e": 30523, "s": 30503, "text": "Collections in Java" }, { "code": null, "e": 30547, "s": 30523, "text": "Queue Interface In Java" }, { "code": null, "e": 30575, "s": 30547, "text": "Initializing a List in Java" }, { "code": null, "e": 30594, "s": 30575, "text": "LinkedList in Java" } ]
How to print a page using jQuery ? - GeeksforGeeks
15 Oct, 2020 The task is to print a page using jQuery by calling a window.print method when the user clicks on a Button. The window.print() method is sent to open the Print Dialog Box to print the current document. It does not have any parameter value. Example:: HTML Code: HTML <!DOCTYPE html><html> <head> <title> How to. print a page using jQuery.? </title></head> <body> <center> <h1>Hello GeeksForGeeks Users</h1> <h3> How to. print a page using jQuery.? </h3> <Button id="sudo" onclick= "print_current_page()" /> Print! </button> </center></body> </html> jQuery Code: $('#sudo).click(function(){ window.print(); return false; }); Output: Before Clicking On Button: After Clicking On Button: Supported Browsers: Google Chrome Internet Explorer Firefox Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Misc jQuery-Misc HTML JQuery Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 26202, "s": 26174, "text": "\n15 Oct, 2020" }, { "code": null, "e": 26443, "s": 26202, "text": "The task is to print a page using jQuery by calling a window.print method when the user clicks on a Button. The window.print() method is sent to open the Print Dialog Box to print the current document. It does not have any parameter value. " }, { "code": null, "e": 26454, "s": 26443, "text": "Example:: " }, { "code": null, "e": 26465, "s": 26454, "text": "HTML Code:" }, { "code": null, "e": 26470, "s": 26465, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to. print a page using jQuery.? </title></head> <body> <center> <h1>Hello GeeksForGeeks Users</h1> <h3> How to. print a page using jQuery.? </h3> <Button id=\"sudo\" onclick= \"print_current_page()\" /> Print! </button> </center></body> </html>", "e": 26846, "s": 26470, "text": null }, { "code": null, "e": 26859, "s": 26846, "text": "jQuery Code:" }, { "code": null, "e": 26930, "s": 26859, "text": "$('#sudo).click(function(){\n window.print();\n return false;\n});\n" }, { "code": null, "e": 26938, "s": 26930, "text": "Output:" }, { "code": null, "e": 26965, "s": 26938, "text": "Before Clicking On Button:" }, { "code": null, "e": 26991, "s": 26965, "text": "After Clicking On Button:" }, { "code": null, "e": 27011, "s": 26991, "text": "Supported Browsers:" }, { "code": null, "e": 27025, "s": 27011, "text": "Google Chrome" }, { "code": null, "e": 27043, "s": 27025, "text": "Internet Explorer" }, { "code": null, "e": 27051, "s": 27043, "text": "Firefox" }, { "code": null, "e": 27057, "s": 27051, "text": "Opera" }, { "code": null, "e": 27064, "s": 27057, "text": "Safari" }, { "code": null, "e": 27201, "s": 27064, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 27211, "s": 27201, "text": "HTML-Misc" }, { "code": null, "e": 27223, "s": 27211, "text": "jQuery-Misc" }, { "code": null, "e": 27228, "s": 27223, "text": "HTML" }, { "code": null, "e": 27235, "s": 27228, "text": "JQuery" }, { "code": null, "e": 27252, "s": 27235, "text": "Web Technologies" }, { "code": null, "e": 27257, "s": 27252, "text": "HTML" }, { "code": null, "e": 27355, "s": 27257, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27379, "s": 27355, "text": "REST API (Introduction)" }, { "code": null, "e": 27420, "s": 27379, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27457, "s": 27420, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27486, "s": 27457, "text": "Form validation using jQuery" }, { "code": null, "e": 27506, "s": 27486, "text": "Angular File Upload" }, { "code": null, "e": 27552, "s": 27506, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 27581, "s": 27552, "text": "Form validation using jQuery" }, { "code": null, "e": 27644, "s": 27581, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 27721, "s": 27644, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
NumberFormat getCurrency() method in Java with Examples - GeeksforGeeks
01 Apr, 2019 The getCurrency() method is a built-in method of the java.text.NumberFormat returns the currency which is used while formatting currency values by this currency. It can be null if there is no valid currency to be determined or if no currency has been set previously. Syntax: public Currency getCurrency() Parameters: The function does not accepts a single parameter. Return Value: The function returns the currency which is used while formatting currency values. Errors and Exceptions: The function throws UnsupportedOperationException when the number format class doesn’t implement currency formatting Below is the implementation of the above function: Program 1: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} US Dollar Program 2: // Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }} Canadian Dollar Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrency() Java-Functions Java-NumberFormat Java-text package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Interfaces in Java Stream In Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25735, "s": 25707, "text": "\n01 Apr, 2019" }, { "code": null, "e": 26002, "s": 25735, "text": "The getCurrency() method is a built-in method of the java.text.NumberFormat returns the currency which is used while formatting currency values by this currency. It can be null if there is no valid currency to be determined or if no currency has been set previously." }, { "code": null, "e": 26010, "s": 26002, "text": "Syntax:" }, { "code": null, "e": 26040, "s": 26010, "text": "public Currency getCurrency()" }, { "code": null, "e": 26102, "s": 26040, "text": "Parameters: The function does not accepts a single parameter." }, { "code": null, "e": 26198, "s": 26102, "text": "Return Value: The function returns the currency which is used while formatting currency values." }, { "code": null, "e": 26338, "s": 26198, "text": "Errors and Exceptions: The function throws UnsupportedOperationException when the number format class doesn’t implement currency formatting" }, { "code": null, "e": 26389, "s": 26338, "text": "Below is the implementation of the above function:" }, { "code": null, "e": 26400, "s": 26389, "text": "Program 1:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getInstance(); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 26899, "s": 26400, "text": null }, { "code": null, "e": 26910, "s": 26899, "text": "US Dollar\n" }, { "code": null, "e": 26921, "s": 26910, "text": "Program 2:" }, { "code": "// Java program to implement// the above function import java.text.NumberFormat;import java.util.Locale;import java.util.Currency; public class Main { public static void main(String[] args) throws Exception { // Get the instance NumberFormat nF = NumberFormat .getNumberInstance(); // Sets the currency to Canadian Dollar nF.setCurrency( Currency.getInstance( Locale.CANADA)); // Stores the values String values = nF.getCurrency() .getDisplayName(); // Prints the currency System.out.println(values); }}", "e": 27589, "s": 26921, "text": null }, { "code": null, "e": 27606, "s": 27589, "text": "Canadian Dollar\n" }, { "code": null, "e": 27702, "s": 27606, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/text/NumberFormat.html#getCurrency()" }, { "code": null, "e": 27717, "s": 27702, "text": "Java-Functions" }, { "code": null, "e": 27735, "s": 27717, "text": "Java-NumberFormat" }, { "code": null, "e": 27753, "s": 27735, "text": "Java-text package" }, { "code": null, "e": 27758, "s": 27753, "text": "Java" }, { "code": null, "e": 27763, "s": 27758, "text": "Java" }, { "code": null, "e": 27861, "s": 27763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27912, "s": 27861, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27942, "s": 27912, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27961, "s": 27942, "text": "Interfaces in Java" }, { "code": null, "e": 27976, "s": 27961, "text": "Stream In Java" }, { "code": null, "e": 28007, "s": 27976, "text": "How to iterate any Map in Java" }, { "code": null, "e": 28025, "s": 28007, "text": "ArrayList in Java" }, { "code": null, "e": 28057, "s": 28025, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 28077, "s": 28057, "text": "Stack Class in Java" }, { "code": null, "e": 28109, "s": 28077, "text": "Multidimensional Arrays in Java" } ]
Rust - If let Operator - GeeksforGeeks
15 Nov, 2021 The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it. Syntax : let gfg=value; let gfg_answer=if let value_1 = expression{ } else if let value_2=expression{ } ... else{ } Example 1: Program for if let operator in Rust. In this example the value we will have one variable gfg=”algo” and we will check it against other values. For the first condition here if the string “cp” equals to gfg variable then gfg_answer will be assigned the value “dsa topic=cp“ because we used the concat method to add “dsa topic=” and “cp“. let gfg_answer=if let "cp" = gfg { concat!("dsa topic=","cp") } If this condition is not met then it will check for other else if or else conditions. The final step is to print the value of gfg_answer. Rust // Rust program for if let operatorfn main() { // string created algo assigned to gfglet gfg = "algo"; // using if let operator let gfg_answer = if let "cp" = gfg { concat!("dsa topic=","cp")} else if let "ds" = gfg { concat!("dsa topic=","ds")} else if let "algo" = gfg { concat!("dsa topic=","algo")} else { concat!("dsa topic=","not in gfg")}; // printing the gfg_answer variableprintln!("{}",gfg_answer);} Output : dsa topic=algo Example 2 : Here we will use gfg variable having value 10, and we will compare it to values and assign the variable gfg_answer according to it. let gfg = Some(10); let gfg_answer = if let Some(10) = gfg { 11 } And we will keep on checking the conditions until some condition is matched or last will be the else condition. Finally, we will print the gfg_answer variable. Below is the program for if let operator Rust. Rust // Rust program for if let operatorfn main() { // gfg variable assigned value 10 let gfg = Some(10); // using if let operator let gfg_answer = if let Some(10) = gfg { 11} else if Some(20) == gfg { 22} else if let Some(30) = gfg { 33} else { -1}; // printing the valueprintln!("gfg_anser={}",gfg_answer );} Output : gfg_answer=11 saurabh1990aror Picked Rust Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Generate Random Numbers in Rust Language? Rust - Casting Rust - For and Range Rust - Generic Function Rust - Creating a Library Rust - References & Borrowing Rust - Concept of Structures Rust - Box Smart Pointer Rust - Concept of Smart Pointers Rust - While Loop
[ { "code": null, "e": 24896, "s": 24868, "text": "\n15 Nov, 2021" }, { "code": null, "e": 25192, "s": 24896, "text": "The basic difference between conventional if-else and if let is that if let uses one pattern that needs to be matched to an expression also known as scrutinee, if the pattern matches the expression then the corresponding code is executed, or in most cases that value is assigned according to it." }, { "code": null, "e": 25201, "s": 25192, "text": "Syntax :" }, { "code": null, "e": 25310, "s": 25201, "text": "let gfg=value;\nlet gfg_answer=if let value_1 = expression{\n}\nelse if let value_2=expression{\n}\n...\nelse{\n} " }, { "code": null, "e": 25358, "s": 25310, "text": "Example 1: Program for if let operator in Rust." }, { "code": null, "e": 25464, "s": 25358, "text": "In this example the value we will have one variable gfg=”algo” and we will check it against other values." }, { "code": null, "e": 25657, "s": 25464, "text": "For the first condition here if the string “cp” equals to gfg variable then gfg_answer will be assigned the value “dsa topic=cp“ because we used the concat method to add “dsa topic=” and “cp“." }, { "code": null, "e": 25725, "s": 25657, "text": "let gfg_answer=if let \"cp\" = gfg {\n concat!(\"dsa topic=\",\"cp\")\n} " }, { "code": null, "e": 25811, "s": 25725, "text": "If this condition is not met then it will check for other else if or else conditions." }, { "code": null, "e": 25863, "s": 25811, "text": "The final step is to print the value of gfg_answer." }, { "code": null, "e": 25868, "s": 25863, "text": "Rust" }, { "code": "// Rust program for if let operatorfn main() { // string created algo assigned to gfglet gfg = \"algo\"; // using if let operator let gfg_answer = if let \"cp\" = gfg { concat!(\"dsa topic=\",\"cp\")} else if let \"ds\" = gfg { concat!(\"dsa topic=\",\"ds\")} else if let \"algo\" = gfg { concat!(\"dsa topic=\",\"algo\")} else { concat!(\"dsa topic=\",\"not in gfg\")}; // printing the gfg_answer variableprintln!(\"{}\",gfg_answer);}", "e": 26293, "s": 25868, "text": null }, { "code": null, "e": 26302, "s": 26293, "text": "Output :" }, { "code": null, "e": 26317, "s": 26302, "text": "dsa topic=algo" }, { "code": null, "e": 26329, "s": 26317, "text": "Example 2 :" }, { "code": null, "e": 26461, "s": 26329, "text": "Here we will use gfg variable having value 10, and we will compare it to values and assign the variable gfg_answer according to it." }, { "code": null, "e": 26531, "s": 26461, "text": "let gfg = Some(10);\nlet gfg_answer = if let Some(10) = gfg {\n 11\n}" }, { "code": null, "e": 26643, "s": 26531, "text": "And we will keep on checking the conditions until some condition is matched or last will be the else condition." }, { "code": null, "e": 26691, "s": 26643, "text": "Finally, we will print the gfg_answer variable." }, { "code": null, "e": 26738, "s": 26691, "text": "Below is the program for if let operator Rust." }, { "code": null, "e": 26743, "s": 26738, "text": "Rust" }, { "code": "// Rust program for if let operatorfn main() { // gfg variable assigned value 10 let gfg = Some(10); // using if let operator let gfg_answer = if let Some(10) = gfg { 11} else if Some(20) == gfg { 22} else if let Some(30) = gfg { 33} else { -1}; // printing the valueprintln!(\"gfg_anser={}\",gfg_answer );}", "e": 27065, "s": 26743, "text": null }, { "code": null, "e": 27074, "s": 27065, "text": "Output :" }, { "code": null, "e": 27088, "s": 27074, "text": "gfg_answer=11" }, { "code": null, "e": 27104, "s": 27088, "text": "saurabh1990aror" }, { "code": null, "e": 27111, "s": 27104, "text": "Picked" }, { "code": null, "e": 27116, "s": 27111, "text": "Rust" }, { "code": null, "e": 27214, "s": 27116, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27263, "s": 27214, "text": "How to Generate Random Numbers in Rust Language?" }, { "code": null, "e": 27278, "s": 27263, "text": "Rust - Casting" }, { "code": null, "e": 27299, "s": 27278, "text": "Rust - For and Range" }, { "code": null, "e": 27323, "s": 27299, "text": "Rust - Generic Function" }, { "code": null, "e": 27349, "s": 27323, "text": "Rust - Creating a Library" }, { "code": null, "e": 27379, "s": 27349, "text": "Rust - References & Borrowing" }, { "code": null, "e": 27408, "s": 27379, "text": "Rust - Concept of Structures" }, { "code": null, "e": 27433, "s": 27408, "text": "Rust - Box Smart Pointer" }, { "code": null, "e": 27466, "s": 27433, "text": "Rust - Concept of Smart Pointers" } ]
Program to find transpose of a matrix - GeeksforGeeks
29 Aug, 2021 Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]. For Square Matrix : The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. C++ C Java Python3 C# PHP Javascript // C++ Program to find// transpose of a matrix#include <bits/stdc++.h>using namespace std;#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} // Driver codeint main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N], i, j; transpose(A, B); cout <<"Result matrix is \n"; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout <<" "<< B[i][j]; cout <<"\n"; } return 0;} // This code is contributed by shivanisinghss2110 // C Program to find// transpose of a matrix#include <stdio.h>#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N], i, j; transpose(A, B); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", B[i][j]); printf("\n"); } return 0;} // Java Program to find// transpose of a matrix class GFG{ static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = new int[N][N], i, j; transpose(A, B); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(B[i][j] + " "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal. # Python3 Program to find# transpose of a matrix N = 4 # This function stores# transpose of A[][] in B[][] def transpose(A,B): for i in range(N): for j in range(N): B[i][j] = A[j][i] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] # To store result transpose(A, B) print("Result matrix is")for i in range(N): for j in range(N): print(B[i][j], " ", end='') print() # This code is contributed# by Anant Agarwal. // C# Program to find// transpose of a matrixusing System; class GFG{ static int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int [,]A, int [,]B) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i,j] = A[j,i]; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int [,]B = new int[N,N]; // Function calling transpose(A, B); Console.Write("Result matrix is \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(B[i,j] + " "); Console.Write("\n"); } }} // This code is contributed by nitin mittal. <?php // This function stores transpose// of A[][] in B[][]function transpose(&$A, &$B){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $B[$i][$j] = $A[$j][$i];} // Driver code$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $N = 4; transpose($A, $B); echo "Result matrix is \n";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo $B[$i][$j]; echo " "; } echo "\n";} // This code is contributed// by Shivi_Aggarwal?> <script>// javascript Program to find// transpose of a matrix var N = 4; // This function stores transpose // of A in B function transpose(A , B) { var i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; var B = Array(4).fill(0); for(let i = 0; i < N; i++){ B[i] = new Array(N); } transpose(A, B); document.write("Result matrix is <br/>"); for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(B[i][j] + " "); document.write("<br/>"); } // This code is contributed by gauravrajput1 </script> Output: Result matrix is 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 For Rectangular Matrix : The below program finds transpose of A[][] and stores the result in B[][]. C++ C Java Python3 C# PHP Javascript // C++ program to find// transpose of a matrix#include <bits/stdc++.h>using namespace std;#define M 3#define N 4 // This function stores transpose// of A[][] in B[][]void transpose(int A[][N], int B[][M]){ int i, j; for(i = 0; i < N; i++) for(j = 0; j < M; j++) B[i][j] = A[j][i];} // Driver codeint main(){ int A[M][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 } }; // Note dimensions of B[][] int B[N][M], i, j; transpose(A, B); cout << "Result matrix is \n"; for(i = 0; i < N; i++) { for(j = 0; j < M; j++) cout << " " << B[i][j]; cout << "\n"; } return 0;} // This code is contributed by shivanisinghss2110 #include <stdio.h>#define M 3#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][M]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i];} int main(){ int A[M][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; // Note dimensions of B[][] int B[N][M], i, j; transpose(A, B); printf("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf("%d ", B[i][j]); printf("\n"); } return 0;} // Java Program to find// transpose of a matrix class GFG{ static final int M = 3; static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; int B[][] = new int[N][M], i, j; transpose(A, B); System.out.print("Result matrix is \n"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) System.out.print(B[i][j] + " "); System.out.print("\n"); } }} // This code is contributed by Anant Agarwal. # Python3 Program to find# transpose of a matrix M = 3N = 4 # This function stores# transpose of A[][] in B[][] def transpose(A, B): for i in range(N): for j in range(M): B[i][j] = A[j][i] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] # To store resultB = [[0 for x in range(M)] for y in range(N)] transpose(A, B) print("Result matrix is")for i in range(N): for j in range(M): print(B[i][j], " ", end='') print() // C# Program to find// transpose of a matrix using System;class GFG { static int M = 3; static int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int [,]A, int [,]B) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i,j] = A[j,i]; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; int [,]B= new int[N,M]; transpose(A, B); Console.WriteLine("Result matrix is \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) Console.Write(B[i,j] + " "); Console.Write("\n"); } }} // This code is contributed by nitin mittal <?php // This function stores transpose// of A[][] in B[][]function transpose(&$A, &$B){ $N = 4; $M = 3; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $M; $j++) $B[$i][$j] = $A[$j][$i];} // Driver code $A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3)); $N = 4;$M = 3;transpose($A, $B); echo "Result matrix is \n";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $M; $j++) { echo $B[$i][$j]; echo " "; } echo "\n";} // This code is contributed// by Shivi_Aggarwal?> <script>// javascript Program to find// transpose of a matrix var M = 3; var N = 4; // This function stores transpose // of A in B function transpose(A , B) { var i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i]; } // Driver code var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ]]; var B = Array(N); for(i=0;i<N;i++) B[i] =Array(M).fill(0); transpose(A, B); document.write("Result matrix is <br/>"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) document.write(B[i][j] + " "); document.write("<br/>"); }// This code contributed by Rajput-Ji</script> Output: Result matrix is 1 2 3 1 2 3 1 2 3 1 2 3 In-Place for Square Matrix: C++ Java Python3 C# PHP Javascript #include <bits/stdc++.h>using namespace std; #define N 4 // Converts A[][] to its transposevoid transpose(int A[][N]){ for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) swap(A[i][j], A[j][i]);} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); printf("Modified matrix is \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf("%d ", A[i][j]); printf("\n"); } return 0;} // Java Program to find// transpose of a matrix class GFG{ static final int N = 4; // Finds transpose of A[][] in-place static void transpose(int A[][]) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) { int temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); System.out.print("Modified matrix is \n"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(A[i][j] + " "); System.out.print("\n"); } }} # Python3 Program to find# transpose of a matrix N = 4 # Finds transpose of A[][] in-placedef transpose(A): for i in range(N): for j in range(i+1, N): A[i][j], A[j][i] = A[j][i], A[i][j] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] transpose(A) print("Modified matrix is")for i in range(N): for j in range(N): print(A[i][j], " ", end='') print() # This code is contributed# by Anant Agarwal. // C# Program to find transpose of// a matrixusing System; class GFG { static int N = 4; // Finds transpose of A[][] in-place static void transpose(int [,]A) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) { int temp = A[i,j]; A[i,j] = A[j,i]; A[j,i] = temp; } } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); Console.WriteLine("Modified matrix is "); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(A[i,j] + " "); Console.WriteLine(); } }} // This code is contributed by anuj_67. <?php// Converts A[][] to its transposefunction transpose(&$A){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = $i + 1; $j < $N; $j++) { $temp = $A[$i][$j]; $A[$i][$j] = $A[$j][$i]; $A[$j][$i] = $temp; }} // Driver Code$N = 4;$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); transpose($A); echo "Modified matrix is " . "\n";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) echo $A[$i][$j] . " "; echo "\n";} // This code is contributed// by Akanksha Rai(Abby_akku)?> <script> // JavaScript Program to find// transpose of a matrix var N = 4; // Finds transpose of A in-place function transpose(A) { for (i = 0; i < N; i++) for (j = i + 1; j < N; j++) { var temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Driver code var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; transpose(A); document.write("Modified matrix is <br/>"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(A[i][j] + " "); document.write("\<br/>"); } // This code is contributed by aashish1995 </script> Output: Modified matrix is 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 Note- Transpose has a time complexity of O(n + m), where n is the number of columns and m is the number of non-zero elements in the matrix. The computational time for transpose of a matrix using identity matrix as reference matrix is O(m*n). Suppose, if the given matrix is a square matrix, the running time will be O(n2). Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above AbhijeetPrakash nitin mittal vt_m Shivi_Aggarwal Akanksha_Rai Himanshu Srivastav 2 GauravRajput1 Rajput-Ji aashish1995 shivanisinghss2110 gargr0109 Amazon MakeMyTrip Wipro Matrix School Programming Amazon MakeMyTrip Wipro Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum size square sub-matrix with all 1s Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Maximum size rectangle binary sub-matrix with all 1s Program to multiply two matrices Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26261, "s": 26233, "text": "\n29 Aug, 2021" }, { "code": null, "e": 26423, "s": 26261, "text": "Transpose of a matrix is obtained by changing rows to columns and columns to rows. In other words, transpose of A[][] is obtained by changing A[i][j] to A[j][i]." }, { "code": null, "e": 26443, "s": 26423, "text": "For Square Matrix :" }, { "code": null, "e": 26561, "s": 26443, "text": "The below program finds transpose of A[][] and stores the result in B[][], we can change N for different dimension. " }, { "code": null, "e": 26565, "s": 26561, "text": "C++" }, { "code": null, "e": 26567, "s": 26565, "text": "C" }, { "code": null, "e": 26572, "s": 26567, "text": "Java" }, { "code": null, "e": 26580, "s": 26572, "text": "Python3" }, { "code": null, "e": 26583, "s": 26580, "text": "C#" }, { "code": null, "e": 26587, "s": 26583, "text": "PHP" }, { "code": null, "e": 26598, "s": 26587, "text": "Javascript" }, { "code": "// C++ Program to find// transpose of a matrix#include <bits/stdc++.h>using namespace std;#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} // Driver codeint main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N], i, j; transpose(A, B); cout <<\"Result matrix is \\n\"; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) cout <<\" \"<< B[i][j]; cout <<\"\\n\"; } return 0;} // This code is contributed by shivanisinghss2110", "e": 27315, "s": 26598, "text": null }, { "code": "// C Program to find// transpose of a matrix#include <stdio.h>#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][N]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i];} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[N][N], i, j; transpose(A, B); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf(\"%d \", B[i][j]); printf(\"\\n\"); } return 0;}", "e": 27944, "s": 27315, "text": null }, { "code": "// Java Program to find// transpose of a matrix class GFG{ static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int B[][] = new int[N][N], i, j; transpose(A, B); System.out.print(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) System.out.print(B[i][j] + \" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.", "e": 28824, "s": 27944, "text": null }, { "code": "# Python3 Program to find# transpose of a matrix N = 4 # This function stores# transpose of A[][] in B[][] def transpose(A,B): for i in range(N): for j in range(N): B[i][j] = A[j][i] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] B = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]] # To store result transpose(A, B) print(\"Result matrix is\")for i in range(N): for j in range(N): print(B[i][j], \" \", end='') print() # This code is contributed# by Anant Agarwal.", "e": 29360, "s": 28824, "text": null }, { "code": "// C# Program to find// transpose of a matrixusing System; class GFG{ static int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int [,]A, int [,]B) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i,j] = A[j,i]; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; int [,]B = new int[N,N]; // Function calling transpose(A, B); Console.Write(\"Result matrix is \\n\"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(B[i,j] + \" \"); Console.Write(\"\\n\"); } }} // This code is contributed by nitin mittal.", "e": 30244, "s": 29360, "text": null }, { "code": "<?php // This function stores transpose// of A[][] in B[][]function transpose(&$A, &$B){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $N; $j++) $B[$i][$j] = $A[$j][$i];} // Driver code$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); $N = 4; transpose($A, $B); echo \"Result matrix is \\n\";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) { echo $B[$i][$j]; echo \" \"; } echo \"\\n\";} // This code is contributed// by Shivi_Aggarwal?>", "e": 30809, "s": 30244, "text": null }, { "code": "<script>// javascript Program to find// transpose of a matrix var N = 4; // This function stores transpose // of A in B function transpose(A , B) { var i, j; for (i = 0; i < N; i++) for (j = 0; j < N; j++) B[i][j] = A[j][i]; } // Driver code var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; var B = Array(4).fill(0); for(let i = 0; i < N; i++){ B[i] = new Array(N); } transpose(A, B); document.write(\"Result matrix is <br/>\"); for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(B[i][j] + \" \"); document.write(\"<br/>\"); } // This code is contributed by gauravrajput1 </script>", "e": 31619, "s": 30809, "text": null }, { "code": null, "e": 31628, "s": 31619, "text": "Output: " }, { "code": null, "e": 31677, "s": 31628, "text": "Result matrix is\n1 2 3 4\n1 2 3 4\n1 2 3 4\n1 2 3 4" }, { "code": null, "e": 31702, "s": 31677, "text": "For Rectangular Matrix :" }, { "code": null, "e": 31778, "s": 31702, "text": "The below program finds transpose of A[][] and stores the result in B[][]. " }, { "code": null, "e": 31782, "s": 31778, "text": "C++" }, { "code": null, "e": 31784, "s": 31782, "text": "C" }, { "code": null, "e": 31789, "s": 31784, "text": "Java" }, { "code": null, "e": 31797, "s": 31789, "text": "Python3" }, { "code": null, "e": 31800, "s": 31797, "text": "C#" }, { "code": null, "e": 31804, "s": 31800, "text": "PHP" }, { "code": null, "e": 31815, "s": 31804, "text": "Javascript" }, { "code": "// C++ program to find// transpose of a matrix#include <bits/stdc++.h>using namespace std;#define M 3#define N 4 // This function stores transpose// of A[][] in B[][]void transpose(int A[][N], int B[][M]){ int i, j; for(i = 0; i < N; i++) for(j = 0; j < M; j++) B[i][j] = A[j][i];} // Driver codeint main(){ int A[M][N] = { { 1, 1, 1, 1 }, { 2, 2, 2, 2 }, { 3, 3, 3, 3 } }; // Note dimensions of B[][] int B[N][M], i, j; transpose(A, B); cout << \"Result matrix is \\n\"; for(i = 0; i < N; i++) { for(j = 0; j < M; j++) cout << \" \" << B[i][j]; cout << \"\\n\"; } return 0;} // This code is contributed by shivanisinghss2110", "e": 32563, "s": 31815, "text": null }, { "code": "#include <stdio.h>#define M 3#define N 4 // This function stores transpose of A[][] in B[][]void transpose(int A[][N], int B[][M]){ int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i];} int main(){ int A[M][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; // Note dimensions of B[][] int B[N][M], i, j; transpose(A, B); printf(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) printf(\"%d \", B[i][j]); printf(\"\\n\"); } return 0;}", "e": 33154, "s": 32563, "text": null }, { "code": "// Java Program to find// transpose of a matrix class GFG{ static final int M = 3; static final int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int A[][], int B[][]) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i]; } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; int B[][] = new int[N][M], i, j; transpose(A, B); System.out.print(\"Result matrix is \\n\"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) System.out.print(B[i][j] + \" \"); System.out.print(\"\\n\"); } }} // This code is contributed by Anant Agarwal.", "e": 34026, "s": 33154, "text": null }, { "code": "# Python3 Program to find# transpose of a matrix M = 3N = 4 # This function stores# transpose of A[][] in B[][] def transpose(A, B): for i in range(N): for j in range(M): B[i][j] = A[j][i] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] # To store resultB = [[0 for x in range(M)] for y in range(N)] transpose(A, B) print(\"Result matrix is\")for i in range(N): for j in range(M): print(B[i][j], \" \", end='') print() ", "e": 34499, "s": 34026, "text": null }, { "code": "// C# Program to find// transpose of a matrix using System;class GFG { static int M = 3; static int N = 4; // This function stores transpose // of A[][] in B[][] static void transpose(int [,]A, int [,]B) { int i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i,j] = A[j,i]; } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}}; int [,]B= new int[N,M]; transpose(A, B); Console.WriteLine(\"Result matrix is \\n\"); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) Console.Write(B[i,j] + \" \"); Console.Write(\"\\n\"); } }} // This code is contributed by nitin mittal", "e": 35353, "s": 34499, "text": null }, { "code": "<?php // This function stores transpose// of A[][] in B[][]function transpose(&$A, &$B){ $N = 4; $M = 3; for ($i = 0; $i < $N; $i++) for ($j = 0; $j < $M; $j++) $B[$i][$j] = $A[$j][$i];} // Driver code $A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3)); $N = 4;$M = 3;transpose($A, $B); echo \"Result matrix is \\n\";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $M; $j++) { echo $B[$i][$j]; echo \" \"; } echo \"\\n\";} // This code is contributed// by Shivi_Aggarwal?>", "e": 35899, "s": 35353, "text": null }, { "code": "<script>// javascript Program to find// transpose of a matrix var M = 3; var N = 4; // This function stores transpose // of A in B function transpose(A , B) { var i, j; for (i = 0; i < N; i++) for (j = 0; j < M; j++) B[i][j] = A[j][i]; } // Driver code var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ]]; var B = Array(N); for(i=0;i<N;i++) B[i] =Array(M).fill(0); transpose(A, B); document.write(\"Result matrix is <br/>\"); for (i = 0; i < N; i++) { for (j = 0; j < M; j++) document.write(B[i][j] + \" \"); document.write(\"<br/>\"); }// This code contributed by Rajput-Ji</script>", "e": 36647, "s": 35899, "text": null }, { "code": null, "e": 36657, "s": 36647, "text": "Output: " }, { "code": null, "e": 36701, "s": 36657, "text": "Result matrix is\n1 2 3 \n1 2 3 \n1 2 3 \n1 2 3" }, { "code": null, "e": 36730, "s": 36701, "text": "In-Place for Square Matrix: " }, { "code": null, "e": 36734, "s": 36730, "text": "C++" }, { "code": null, "e": 36739, "s": 36734, "text": "Java" }, { "code": null, "e": 36747, "s": 36739, "text": "Python3" }, { "code": null, "e": 36750, "s": 36747, "text": "C#" }, { "code": null, "e": 36754, "s": 36750, "text": "PHP" }, { "code": null, "e": 36765, "s": 36754, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; #define N 4 // Converts A[][] to its transposevoid transpose(int A[][N]){ for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) swap(A[i][j], A[j][i]);} int main(){ int A[N][N] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); printf(\"Modified matrix is \\n\"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) printf(\"%d \", A[i][j]); printf(\"\\n\"); } return 0;}", "e": 37334, "s": 36765, "text": null }, { "code": "// Java Program to find// transpose of a matrix class GFG{ static final int N = 4; // Finds transpose of A[][] in-place static void transpose(int A[][]) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) { int temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Driver code public static void main (String[] args) { int A[][] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); System.out.print(\"Modified matrix is \\n\"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(A[i][j] + \" \"); System.out.print(\"\\n\"); } }}", "e": 38189, "s": 37334, "text": null }, { "code": "# Python3 Program to find# transpose of a matrix N = 4 # Finds transpose of A[][] in-placedef transpose(A): for i in range(N): for j in range(i+1, N): A[i][j], A[j][i] = A[j][i], A[i][j] # driver codeA = [ [1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3], [4, 4, 4, 4]] transpose(A) print(\"Modified matrix is\")for i in range(N): for j in range(N): print(A[i][j], \" \", end='') print() # This code is contributed# by Anant Agarwal.", "e": 38663, "s": 38189, "text": null }, { "code": "// C# Program to find transpose of// a matrixusing System; class GFG { static int N = 4; // Finds transpose of A[][] in-place static void transpose(int [,]A) { for (int i = 0; i < N; i++) for (int j = i+1; j < N; j++) { int temp = A[i,j]; A[i,j] = A[j,i]; A[j,i] = temp; } } // Driver code public static void Main () { int [,]A = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}}; transpose(A); Console.WriteLine(\"Modified matrix is \"); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(A[i,j] + \" \"); Console.WriteLine(); } }} // This code is contributed by anuj_67.", "e": 39555, "s": 38663, "text": null }, { "code": "<?php// Converts A[][] to its transposefunction transpose(&$A){ $N = 4; for ($i = 0; $i < $N; $i++) for ($j = $i + 1; $j < $N; $j++) { $temp = $A[$i][$j]; $A[$i][$j] = $A[$j][$i]; $A[$j][$i] = $temp; }} // Driver Code$N = 4;$A = array(array(1, 1, 1, 1), array(2, 2, 2, 2), array(3, 3, 3, 3), array(4, 4, 4, 4)); transpose($A); echo \"Modified matrix is \" . \"\\n\";for ($i = 0; $i < $N; $i++){ for ($j = 0; $j < $N; $j++) echo $A[$i][$j] . \" \"; echo \"\\n\";} // This code is contributed// by Akanksha Rai(Abby_akku)?>", "e": 40191, "s": 39555, "text": null }, { "code": "<script> // JavaScript Program to find// transpose of a matrix var N = 4; // Finds transpose of A in-place function transpose(A) { for (i = 0; i < N; i++) for (j = i + 1; j < N; j++) { var temp = A[i][j]; A[i][j] = A[j][i]; A[j][i] = temp; } } // Driver code var A = [ [ 1, 1, 1, 1 ], [ 2, 2, 2, 2 ], [ 3, 3, 3, 3 ], [ 4, 4, 4, 4 ] ]; transpose(A); document.write(\"Modified matrix is <br/>\"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) document.write(A[i][j] + \" \"); document.write(\"\\<br/>\"); } // This code is contributed by aashish1995 </script>", "e": 40966, "s": 40191, "text": null }, { "code": null, "e": 40975, "s": 40966, "text": "Output: " }, { "code": null, "e": 41026, "s": 40975, "text": "Modified matrix is\n1 2 3 4\n1 2 3 4\n1 2 3 4\n1 2 3 4" }, { "code": null, "e": 41349, "s": 41026, "text": "Note- Transpose has a time complexity of O(n + m), where n is the number of columns and m is the number of non-zero elements in the matrix. The computational time for transpose of a matrix using identity matrix as reference matrix is O(m*n). Suppose, if the given matrix is a square matrix, the running time will be O(n2)." }, { "code": null, "e": 41474, "s": 41349, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 41490, "s": 41474, "text": "AbhijeetPrakash" }, { "code": null, "e": 41503, "s": 41490, "text": "nitin mittal" }, { "code": null, "e": 41508, "s": 41503, "text": "vt_m" }, { "code": null, "e": 41523, "s": 41508, "text": "Shivi_Aggarwal" }, { "code": null, "e": 41536, "s": 41523, "text": "Akanksha_Rai" }, { "code": null, "e": 41557, "s": 41536, "text": "Himanshu Srivastav 2" }, { "code": null, "e": 41571, "s": 41557, "text": "GauravRajput1" }, { "code": null, "e": 41581, "s": 41571, "text": "Rajput-Ji" }, { "code": null, "e": 41593, "s": 41581, "text": "aashish1995" }, { "code": null, "e": 41612, "s": 41593, "text": "shivanisinghss2110" }, { "code": null, "e": 41622, "s": 41612, "text": "gargr0109" }, { "code": null, "e": 41629, "s": 41622, "text": "Amazon" }, { "code": null, "e": 41640, "s": 41629, "text": "MakeMyTrip" }, { "code": null, "e": 41646, "s": 41640, "text": "Wipro" }, { "code": null, "e": 41653, "s": 41646, "text": "Matrix" }, { "code": null, "e": 41672, "s": 41653, "text": "School Programming" }, { "code": null, "e": 41679, "s": 41672, "text": "Amazon" }, { "code": null, "e": 41690, "s": 41679, "text": "MakeMyTrip" }, { "code": null, "e": 41696, "s": 41690, "text": "Wipro" }, { "code": null, "e": 41703, "s": 41696, "text": "Matrix" }, { "code": null, "e": 41801, "s": 41703, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41844, "s": 41801, "text": "Maximum size square sub-matrix with all 1s" }, { "code": null, "e": 41868, "s": 41844, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 41930, "s": 41868, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 41983, "s": 41930, "text": "Maximum size rectangle binary sub-matrix with all 1s" }, { "code": null, "e": 42016, "s": 41983, "text": "Program to multiply two matrices" }, { "code": null, "e": 42034, "s": 42016, "text": "Python Dictionary" }, { "code": null, "e": 42050, "s": 42034, "text": "Arrays in C/C++" }, { "code": null, "e": 42069, "s": 42050, "text": "Inheritance in C++" }, { "code": null, "e": 42094, "s": 42069, "text": "Reverse a string in Java" } ]
Convert JSON data Into a Custom Python Object - GeeksforGeeks
16 Dec, 2021 Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(), the return value of object_hook will be used instead of the default dict value.We can also implement custom decoders using this.Example 1 : Python3 # importing the moduleimport jsonfrom collections import namedtuple # creating the datadata = '{"name" : "Geek", "id" : 1, "location" : "Mumbai"}' # making the objectx = json.loads(data, object_hook = lambda d : namedtuple('X', d.keys()) (*d.values())) # accessing the JSON data as an objectprint(x.name, x.id, x.location) Output : As we can see in the above example, the namedtuple is a class, under the collections module. It contains keys that are mapped to some values. In this case, we can access the elements using keys and indexes. We can also create a custom decoder function, in which we can convert dict into a custom Python type and pass the value to the object_hook parameter which is illustrated in the next example.Example 2 : Python3 # importing the moduleimport jsonfrom collections import namedtuple # customDecoder functiondef customDecoder(geekDict): return namedtuple('X', geekDict.keys())(*geekDict.values()) # creating the datageekJsonData = '{"name" : "GeekCustomDecoder", "id" : 2, "location" : "Pune"}' # creating the objectx = json.loads(geekJsonData, object_hook = customDecoder) # accessing the JSON data as an objectprint(x.name, x.id, x.location) Output : We can also use SimpleNamespace class from the types module as the container for JSON objects. Advantages of a SimpleNamespace solution over a namedtuple solution: – It is faster because it does not create a class for each object.It is shorter and simpler. It is faster because it does not create a class for each object. It is shorter and simpler. Example 3 : Python3 # importing the moduleimport jsontry: from types import SimpleNamespace as Namespaceexcept ImportError: from argparse import Namespace # creating the datadata = '{"name" : "GeekNamespace", "id" : 3, "location" : "Bangalore"}' # creating the objectx = json.loads(data, object_hook = lambda d : Namespace(**d)) # accessing the JSON data as an objectprint(x.name, x.id, x.location) Output : prachisoda1234 Python json-programs Python-json Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n16 Dec, 2021" }, { "code": null, "e": 26029, "s": 25537, "text": "Let us see how to convert JSON data into a custom object in Python. Converting JSON data into a custom python object is also known as decoding or deserializing JSON data. To decode JSON data we can make use of the json.loads(), json.load() method and the object_hook parameter. The object_hook parameter is used so that, when we execute json.loads(), the return value of object_hook will be used instead of the default dict value.We can also implement custom decoders using this.Example 1 : " }, { "code": null, "e": 26037, "s": 26029, "text": "Python3" }, { "code": "# importing the moduleimport jsonfrom collections import namedtuple # creating the datadata = '{\"name\" : \"Geek\", \"id\" : 1, \"location\" : \"Mumbai\"}' # making the objectx = json.loads(data, object_hook = lambda d : namedtuple('X', d.keys()) (*d.values())) # accessing the JSON data as an objectprint(x.name, x.id, x.location)", "e": 26388, "s": 26037, "text": null }, { "code": null, "e": 26398, "s": 26388, "text": "Output : " }, { "code": null, "e": 26809, "s": 26398, "text": "As we can see in the above example, the namedtuple is a class, under the collections module. It contains keys that are mapped to some values. In this case, we can access the elements using keys and indexes. We can also create a custom decoder function, in which we can convert dict into a custom Python type and pass the value to the object_hook parameter which is illustrated in the next example.Example 2 : " }, { "code": null, "e": 26817, "s": 26809, "text": "Python3" }, { "code": "# importing the moduleimport jsonfrom collections import namedtuple # customDecoder functiondef customDecoder(geekDict): return namedtuple('X', geekDict.keys())(*geekDict.values()) # creating the datageekJsonData = '{\"name\" : \"GeekCustomDecoder\", \"id\" : 2, \"location\" : \"Pune\"}' # creating the objectx = json.loads(geekJsonData, object_hook = customDecoder) # accessing the JSON data as an objectprint(x.name, x.id, x.location)", "e": 27248, "s": 26817, "text": null }, { "code": null, "e": 27258, "s": 27248, "text": "Output : " }, { "code": null, "e": 27424, "s": 27258, "text": "We can also use SimpleNamespace class from the types module as the container for JSON objects. Advantages of a SimpleNamespace solution over a namedtuple solution: –" }, { "code": null, "e": 27515, "s": 27424, "text": "It is faster because it does not create a class for each object.It is shorter and simpler." }, { "code": null, "e": 27580, "s": 27515, "text": "It is faster because it does not create a class for each object." }, { "code": null, "e": 27607, "s": 27580, "text": "It is shorter and simpler." }, { "code": null, "e": 27620, "s": 27607, "text": "Example 3 : " }, { "code": null, "e": 27628, "s": 27620, "text": "Python3" }, { "code": "# importing the moduleimport jsontry: from types import SimpleNamespace as Namespaceexcept ImportError: from argparse import Namespace # creating the datadata = '{\"name\" : \"GeekNamespace\", \"id\" : 3, \"location\" : \"Bangalore\"}' # creating the objectx = json.loads(data, object_hook = lambda d : Namespace(**d)) # accessing the JSON data as an objectprint(x.name, x.id, x.location)", "e": 28013, "s": 27628, "text": null }, { "code": null, "e": 28023, "s": 28013, "text": "Output : " }, { "code": null, "e": 28038, "s": 28023, "text": "prachisoda1234" }, { "code": null, "e": 28059, "s": 28038, "text": "Python json-programs" }, { "code": null, "e": 28071, "s": 28059, "text": "Python-json" }, { "code": null, "e": 28078, "s": 28071, "text": "Python" }, { "code": null, "e": 28176, "s": 28078, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28208, "s": 28176, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28250, "s": 28208, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28292, "s": 28250, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28348, "s": 28292, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28375, "s": 28348, "text": "Python Classes and Objects" }, { "code": null, "e": 28414, "s": 28375, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28445, "s": 28414, "text": "Python | os.path.join() method" }, { "code": null, "e": 28474, "s": 28445, "text": "Create a directory in Python" }, { "code": null, "e": 28496, "s": 28474, "text": "Defaultdict in Python" } ]
HTML <marquee> Tag - GeeksforGeeks
02 Mar, 2022 The <marquee> tag in HTML is used to create scrolling text or image in a webpages. It scrolls either from horizontally left to right or right to left, or vertically top to bottom or bottom to top. Syntax : The marquee element comes in pairs. It means means that the tag has opening and closing elements. <marquee> <--- contents ---> </marquee> Attributes Methods start (): This method is used to start the scrolling of the Marquee Tag. stop (): This method is used to stop the scrolling of the Marquee Tag. Example: html <!DOCTYPE html><html><head> <title>Marquee Tag</title> <style> .main { text-align:center; } .marq { padding-top:30px; padding-bottom:30px; } .geek1 { font-size:36px; font-weight:bold; color:white; padding-bottom:10px; } </style></head> <body> <div class = "main"> <marquee class="marq" bgcolor = "Green" direction = "left" loop="" > <div class="geek1">GeeksforGeeks</div> <div class="geek2">A computer science portal for geeks</div> </marquee> </div></body></html> Output: Marquee Tag Example: html <!DOCTYPE html><html><head> <title>Marquee Tag</title> <style> .main { text-align:center; font-family:"Times New Roman"; } .marq { padding-top:30px; padding-bottom:30px; } .geek1 { font-size:36px; font-weight:bold; color:white; text-align:center; } .geek2 { text-align:center; } </style></head> <body> <div class = "main"> <marquee class="marq" bgcolor = "Green" direction = "up" loop="" > <div class="geek1">GeeksforGeeks</div> <div class="geek2">A computer science portal for geeks</div> </marquee> </div></body></html> Output: Marquee Tag Example: html <!DOCTYPE html><html><head> <title>Marquee Tag</title> <style> .main { text-align:center; font-family:"Times New Roman"; } .marq { padding-top:30px; padding-bottom:30px; } .geek1 { font-size:36px; font-weight:bold; color:white; text-align:center; } .geek2 { text-align:center; } </style></head> <body> <div class = "main"> <marquee class="marq" bgcolor = "Green" direction = "down" loop="" > <div class="geek1">GeeksforGeeks</div> <div class="geek2">A computer science portal for geeks</div> </marquee> </div></body></html> Output: Marquee Tag Supported Browsers Google Chrome 1.0 Edge 12.0 Firefox 65.0 Internet Explorer 2.0 Opera 7.2 Safari 1.2 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 hritikbhatnagar2182 Web technologies HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) How to Insert Form Data into Database using PHP ? Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? HTML | <img> align Attribute 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25469, "s": 25441, "text": "\n02 Mar, 2022" }, { "code": null, "e": 25667, "s": 25469, "text": "The <marquee> tag in HTML is used to create scrolling text or image in a webpages. It scrolls either from horizontally left to right or right to left, or vertically top to bottom or bottom to top. " }, { "code": null, "e": 25677, "s": 25667, "text": "Syntax : " }, { "code": null, "e": 25776, "s": 25677, "text": "The marquee element comes in pairs. It means means that the tag has opening and closing elements. " }, { "code": null, "e": 25820, "s": 25776, "text": "<marquee>\n <--- contents --->\n</marquee> " }, { "code": null, "e": 25831, "s": 25820, "text": "Attributes" }, { "code": null, "e": 25840, "s": 25831, "text": "Methods " }, { "code": null, "e": 25913, "s": 25840, "text": "start (): This method is used to start the scrolling of the Marquee Tag." }, { "code": null, "e": 25984, "s": 25913, "text": "stop (): This method is used to stop the scrolling of the Marquee Tag." }, { "code": null, "e": 25995, "s": 25984, "text": "Example: " }, { "code": null, "e": 26000, "s": 25995, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Marquee Tag</title> <style> .main { text-align:center; } .marq { padding-top:30px; padding-bottom:30px; } .geek1 { font-size:36px; font-weight:bold; color:white; padding-bottom:10px; } </style></head> <body> <div class = \"main\"> <marquee class=\"marq\" bgcolor = \"Green\" direction = \"left\" loop=\"\" > <div class=\"geek1\">GeeksforGeeks</div> <div class=\"geek2\">A computer science portal for geeks</div> </marquee> </div></body></html> ", "e": 26586, "s": 26000, "text": null }, { "code": null, "e": 26608, "s": 26586, "text": "Output: Marquee Tag " }, { "code": null, "e": 26621, "s": 26610, "text": "Example: " }, { "code": null, "e": 26626, "s": 26621, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Marquee Tag</title> <style> .main { text-align:center; font-family:\"Times New Roman\"; } .marq { padding-top:30px; padding-bottom:30px; } .geek1 { font-size:36px; font-weight:bold; color:white; text-align:center; } .geek2 { text-align:center; } </style></head> <body> <div class = \"main\"> <marquee class=\"marq\" bgcolor = \"Green\" direction = \"up\" loop=\"\" > <div class=\"geek1\">GeeksforGeeks</div> <div class=\"geek2\">A computer science portal for geeks</div> </marquee> </div></body></html> ", "e": 27289, "s": 26626, "text": null }, { "code": null, "e": 27311, "s": 27289, "text": "Output: Marquee Tag " }, { "code": null, "e": 27324, "s": 27313, "text": "Example: " }, { "code": null, "e": 27329, "s": 27324, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Marquee Tag</title> <style> .main { text-align:center; font-family:\"Times New Roman\"; } .marq { padding-top:30px; padding-bottom:30px; } .geek1 { font-size:36px; font-weight:bold; color:white; text-align:center; } .geek2 { text-align:center; } </style></head> <body> <div class = \"main\"> <marquee class=\"marq\" bgcolor = \"Green\" direction = \"down\" loop=\"\" > <div class=\"geek1\">GeeksforGeeks</div> <div class=\"geek2\">A computer science portal for geeks</div> </marquee> </div></body></html> ", "e": 27994, "s": 27329, "text": null }, { "code": null, "e": 28016, "s": 27994, "text": "Output: Marquee Tag " }, { "code": null, "e": 28037, "s": 28018, "text": "Supported Browsers" }, { "code": null, "e": 28055, "s": 28037, "text": "Google Chrome 1.0" }, { "code": null, "e": 28065, "s": 28055, "text": "Edge 12.0" }, { "code": null, "e": 28078, "s": 28065, "text": "Firefox 65.0" }, { "code": null, "e": 28100, "s": 28078, "text": "Internet Explorer 2.0" }, { "code": null, "e": 28110, "s": 28100, "text": "Opera 7.2" }, { "code": null, "e": 28123, "s": 28110, "text": "Safari 1.2 " }, { "code": null, "e": 28260, "s": 28123, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 28274, "s": 28260, "text": "ManasChhabra2" }, { "code": null, "e": 28294, "s": 28274, "text": "hritikbhatnagar2182" }, { "code": null, "e": 28311, "s": 28294, "text": "Web technologies" }, { "code": null, "e": 28316, "s": 28311, "text": "HTML" }, { "code": null, "e": 28333, "s": 28316, "text": "Web Technologies" }, { "code": null, "e": 28338, "s": 28333, "text": "HTML" }, { "code": null, "e": 28436, "s": 28338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28460, "s": 28436, "text": "REST API (Introduction)" }, { "code": null, "e": 28510, "s": 28460, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28547, "s": 28510, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 28611, "s": 28547, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 28640, "s": 28611, "text": "HTML | <img> align Attribute" }, { "code": null, "e": 28680, "s": 28640, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28713, "s": 28680, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28758, "s": 28713, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28801, "s": 28758, "text": "How to fetch data from an API in ReactJS ?" } ]
Data Science for E-Commerce with Python | by Julian Herrera | Towards Data Science
E-Commerce is currently one of the fastest and dynamically evolving industries in the world. Its popularity has been growing rapidly with the ease of digital transactions and quick door-to-door deliveries. A major source of big tech companies revenues comes from the interaction of their underlying proprietary algorithms that are heavily powered by data science, so it’s fundamental to understand the methods applied to maintain and grow the number of clients. In this article, I’ll give you some insights about how this amazing industry is applying data science with a Python script to practically show the case. Both the datasets and the script can be found at my GitHub following this link. 1. Introduction to data and Data Science (1 min read) 2. E-commerce applications of Data Science (1 min read) 3. Recommender Systems (1 min read) 4. Customer Analytics (2 min read) 5. Data Exploratory Analysis with Python (4 min read) The definition of data is simply a collection of raw facts, such as numbers, words, or observations, whereas Data Science is the scientific discipline that deals with the study of data. Nowadays, most e-commerce platforms collect tons of data from users without hampering customer experience. Collected data is stored in structured or tabulated tables in order to facilitate analysis and interpretation. Not only structured data is stored, but also non-structured data such as images, videos or documents, which also have plenty of value at the moment of studying users preferences and are frequently harder to process and analyze. Data analysis provides these companies with insights and metrics that are constantly changing and that allow them to build even better products. The reason for this major outbreak in interest for data science is its widespread adoption due to the growth of data volumes and computing power. The growth of data is directly related to the widespread digitization and internet penetration and mobile devices massive adoption, which are continuously generating data without human intervention. On the other hand, computing power has enabled data scientists to store, process and study large chunks of data in an efficient way. Nowadays, not only are big tech companies, such as Google, Facebook, Apple, Amazon or Microsoft, the ones that are taking full advantage in their core businesses, but also small and local businesses as well as startups have gradually adopted data science to add value to their businesses. E- commerce stands for electronic commerce and represents the online version of physical retail stores. It allows people from all over the world to purchase, browse and sell products through online platforms. Although it may seem a fairly simple process from the customer standpoint, there are several obstacles to overcome in order to provide a seamless online shopping experience, such as processes-related ones which include product ordering, delivery and fair pricing. However, with the growing number of people looking to shop online, the e-commerce industry is expanding rapidly. This also means that an increasing proportion of traditional businesses are switching or complementing their business model to electronic commerce. In the context of e-commerce industry evolution, Data Science helps to bring maximum value out of the vast amount of data available in such platforms, and helps to switch focus towards customer engagement and experience. It focuses on: Product recommendation for users. Analysis of customer trends and behaviors Forecasting sales and stock logistics. Optimizing product pricing and payment methods. Each of these applications involves storage and interpretation of large amounts of volumes of data, in which data analysis techniques come in handy. One example of the application of Data Analytics techniques in case studies are company’s Recommender Systems, which are a means of predicting the preference that users might have towards an item based on previous purchases or searches on the platform. Recommender systems are used strategically to increase conversion rates, elevate customer experience and amplify user engagement. A large-scale recommender system that has proved to work is Amazon’s data-driven and personalized marketing approach to boosting sales in the platform through intelligent recommendations to users. According to McKinsey Insights magazine, 35% of Amazon’s revenue is generated by its recommendation engine. This achievement has been possible because of the recommendation system’s application in email campaigns and on most of its web site’s pages, both on-site and off-site recommendations. There are two types of recommender systems: Content-Based Recommendations: Method that makes recommendations based on attributes or features of the product. For instance, if a product shares attributes with another, in case a user purchased the first, the system should recommend the second as there is a higher probability that the user’s preferences will match the second product.Collaborative Recommendations: This method makes recommendations based on the interactions displayed by multiple users. For instance, if several clients have purchased a certain product with another one, the system should recommend each of the products reciprocally as previous customers purchased both items together on previous occasions. Content-Based Recommendations: Method that makes recommendations based on attributes or features of the product. For instance, if a product shares attributes with another, in case a user purchased the first, the system should recommend the second as there is a higher probability that the user’s preferences will match the second product. Collaborative Recommendations: This method makes recommendations based on the interactions displayed by multiple users. For instance, if several clients have purchased a certain product with another one, the system should recommend each of the products reciprocally as previous customers purchased both items together on previous occasions. Customers are a key factor for any e-commerce company and emphasizing in providing great customer experience and satisfaction to the client should be a primer concern. In order to achieve such a level of service, it’s necessary to get to know the client and its preferences. E-commerce platforms have the possibility to track a customer’s activity from the moment he or she enters the site till the time they leave, whether this happens after purchasing or selling some product, or after skimming through the products. Based on this necessity to know the client, every action that it’s taken must be recorded and stored as potential useful data to determine the client’s profile. The process of generating actionable insights about the customers from their collected data is known as Customer Analytics. Customer Analytics helps to understand the trends and shifts in customer’s behavior in order to modify business strategies, as well as make key business decisions accordingly. It also provides a means to analyze which channels of acquisition and retention of clients are actually working and which are not. In order to build a Customer Analytics platforms, e-commerce companies must focus on key features about customers, which include: Customer profiling and segmentation: Customers can be grouped based on their preferences, purchases and browsing patterns, in order to build a personal profile and provide recommendations based on it. In addition, this profiling helps to build target audiences, personalized products and even marketing strategies that work for each group. It also helps to shift focus to most profitable clients to establish better customer relations. Customers can be classified among geographical characteristics, behavior in the platform, demographic features and psychological characteristics. Sentiment Analysis: This is the process of determining the emotion behind a set of words or sentences, in order to identify a sentiment expressed by customers for their purchased or sold products, through product reviews or in support tickets. Sentiment classifiers can be either positive, negative or neutral, and help to respond to complaints and improve customer service, among others. Churn Analysis: This is the process of analyzing the likelihood of when a customer will purchase a product, based on its activity in the platform, directed towards optimizing existing acquisition and retention strategies. An improvement in the churn rate can highly impact the growth and even the sustainability of the business. Lifetime Value Prediction: This is the estimated total revenue that a customer will provide to the business during his or her relationship with the platform. The estimation is made using factors such as early transaction patterns, frequency and volume of transactions, among others.Predicting Lifetime Value Prediction, helps in planning what kind of customers to invest business resources in to extract the most value out of them. The first step before analyzing a dataset is to preview the information it contains. To process this information easily we’re going to use Pandas, the Python library for data manipulation and analysis that offers data structures and operations for manipulating numerical tables and time series. For those who are not familiar with Python, it is a high-level and general-purpose programming language that emphasizes coding efficiency, readability and re-usage of scripts. Both the datasets and the script can be found at my GitHub following this link. Below, I’ll include the necessary code to run the analysis on your computers: # Imports import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsimport numpy as np After proceeding with the imports of the necessary libraries, proceed with the creation of a pandas dataframe that contains the information of the dataset, and explore it: # Read dataset and previewdata = pd.read_csv('e_commerce.csv')# Exploring datadata.info() From the result of the application of the info() method in the “data” variable, we access to the information inside the dataset, which consists of a series of transactions made in an e-commerce platforms, for which we have identified the user ID, purchase product ID and many more descriptive data that will be useful in the process. After moving on with the analysis, we proceed with some cleaning of the null features in the dataframe. As we can see with the code below, there are 173.638 null fields for product 2, meaning that the user did not purchase more than one in such cases. Also, there are 383.247 null fields for product 3: # Count null features in the datasetdata.isnull().sum() Now, let’s proceed with the replacement of null features with zero values, as we need to have a clean dataset to perform operations with it: # Replace the null features with 0:data.fillna(0, inplace=True) # Re-check N/A was replaced with 0. In the dataframe, we have all the transactions made by customers, which include every transaction each one made. In order to identify users that spend the most in our platform, lets group by user ID and add up the amount spent: # Group by User ID:purchases = data.groupby(['User_ID']).sum().reset_index() Also, we can access to which products each User ID purchased, let’s try with user ID 1.000.001: data[data['User_ID'] == 1000001] After identifying most-spending users, let’s extract the range of ages of these users and the average sale for each age group: purchase_by_age = data.groupby('Age')['Purchase'].mean().reset_index() The group of users whose age ranges from 51–55 is the one that spends the most at the platform, so maybe we should target our marketing campaigns to them. Let’s take a look a the graphical distribution of users age: plt.figure(figsize=(16,4))plt.plot(purchase_by_age.index, purchase_by_age.values, color='purple', marker='*')plt.grid()plt.xlabel('Age Group', fontsize=10)plt.ylabel('Total Purchases in $', fontsize=10)plt.title('Average Sales distributed by age group', fontsize=15)plt.show() On the other hand, it would be interested to find out which age group and gender makes more transactions.These two facts can easily be calculated with few lines of code: # Grouping by gender and ageage_and_gender = data.groupby('Age')['Gender'].count().reset_index()gender = data.groupby('Gender')['Age'].count().reset_index()# Plot distributionplt.figure(figsize=(12,9))plt.pie(age_and_gender['Gender'], labels=age_and_gender['Age'],autopct='%d%%', colors=['cyan', 'steelblue','peru','blue','yellowgreen','salmon','#0040FF'])plt.axis('equal')plt.title("Age Distribution", fontsize='20')plt.show() # Plot gender distributionplt.figure(figsize=(12,9))plt.pie(gender['Age'], labels=gender['Gender'],autopct='%d%%', colors=['salmon','steelblue'])plt.axis('equal')plt.title("Gender Distribution", fontsize='20')plt.show() In addition, we can calculate which occupations of those displayed by the customers of the platform are the ones that purchase more products. Take a look a the code below: # Group by occupation:occupation = data.groupby('Occupation')['Purchase'].mean().reset_index()# Plot bar chart with line plot:sns.set(style="white", rc={"lines.linewidth": 3})fig, ax1 = plt.subplots(figsize=(12,9))sns.barplot(x=occupation['Occupation'],y=occupation['Purchase'],color='#004488',ax=ax1)sns.lineplot(x=occupation['Occupation'],y=occupation['Purchase'],color='salmon',marker="o",ax=ax1)plt.axis([-1,21,8000,10000])plt.title('Occupation Bar Chart', fontsize='15')plt.show()sns.set() And lastly, we can determine which are the best-selling products in the platform: # Group by product IDproduct = data.groupby('Product_ID')['Purchase'].count().reset_index()product.rename(columns={'Purchase':'Count'},inplace=True)product_sorted = product.sort_values('Count',ascending=False)# Plot line plotplt.figure(figsize=(14,8))plt.plot(product_sorted['Product_ID'][:10], product_sorted['Count'][:10], linestyle='-', color='purple', marker='o')plt.title("Best-selling Products", fontsize='15')plt.xlabel('Product ID', fontsize='15')plt.ylabel('Products Sold', fontsize='15')plt.show() My aim with this article was to provide an intuition about how global companies apply data science for acquiring, retaining, and growing their customer base. In addition to this, I wanted to provide a practical explanation of theory involved in e-commerce business which includes recommendations systems and customer analytics. If you liked the information included in this article don’t hesitate to contact me to share your thoughts. It motivates me to keep on sharing! Neural networks application for Stack Overflow profiles: medium.com Data Analysis for Airbnb rentals in New York: towardsdatascience.com Enhance metrics, KPIs and data interpretation with nice visualizations: towardsdatascience.com Thanks for taking the time to read my article! If you have any questions or ideas to share, please feel free to contact me to my email, or you can find me in the following social networks for more related content: LinkedIn. GitHub. [1] Python official website [2] McKinsey Insights magazine.
[ { "code": null, "e": 634, "s": 172, "text": "E-Commerce is currently one of the fastest and dynamically evolving industries in the world. Its popularity has been growing rapidly with the ease of digital transactions and quick door-to-door deliveries. A major source of big tech companies revenues comes from the interaction of their underlying proprietary algorithms that are heavily powered by data science, so it’s fundamental to understand the methods applied to maintain and grow the number of clients." }, { "code": null, "e": 867, "s": 634, "text": "In this article, I’ll give you some insights about how this amazing industry is applying data science with a Python script to practically show the case. Both the datasets and the script can be found at my GitHub following this link." }, { "code": null, "e": 921, "s": 867, "text": "1. Introduction to data and Data Science (1 min read)" }, { "code": null, "e": 977, "s": 921, "text": "2. E-commerce applications of Data Science (1 min read)" }, { "code": null, "e": 1013, "s": 977, "text": "3. Recommender Systems (1 min read)" }, { "code": null, "e": 1048, "s": 1013, "text": "4. Customer Analytics (2 min read)" }, { "code": null, "e": 1102, "s": 1048, "text": "5. Data Exploratory Analysis with Python (4 min read)" }, { "code": null, "e": 1288, "s": 1102, "text": "The definition of data is simply a collection of raw facts, such as numbers, words, or observations, whereas Data Science is the scientific discipline that deals with the study of data." }, { "code": null, "e": 1734, "s": 1288, "text": "Nowadays, most e-commerce platforms collect tons of data from users without hampering customer experience. Collected data is stored in structured or tabulated tables in order to facilitate analysis and interpretation. Not only structured data is stored, but also non-structured data such as images, videos or documents, which also have plenty of value at the moment of studying users preferences and are frequently harder to process and analyze." }, { "code": null, "e": 1879, "s": 1734, "text": "Data analysis provides these companies with insights and metrics that are constantly changing and that allow them to build even better products." }, { "code": null, "e": 2357, "s": 1879, "text": "The reason for this major outbreak in interest for data science is its widespread adoption due to the growth of data volumes and computing power. The growth of data is directly related to the widespread digitization and internet penetration and mobile devices massive adoption, which are continuously generating data without human intervention. On the other hand, computing power has enabled data scientists to store, process and study large chunks of data in an efficient way." }, { "code": null, "e": 2646, "s": 2357, "text": "Nowadays, not only are big tech companies, such as Google, Facebook, Apple, Amazon or Microsoft, the ones that are taking full advantage in their core businesses, but also small and local businesses as well as startups have gradually adopted data science to add value to their businesses." }, { "code": null, "e": 2855, "s": 2646, "text": "E- commerce stands for electronic commerce and represents the online version of physical retail stores. It allows people from all over the world to purchase, browse and sell products through online platforms." }, { "code": null, "e": 3119, "s": 2855, "text": "Although it may seem a fairly simple process from the customer standpoint, there are several obstacles to overcome in order to provide a seamless online shopping experience, such as processes-related ones which include product ordering, delivery and fair pricing." }, { "code": null, "e": 3380, "s": 3119, "text": "However, with the growing number of people looking to shop online, the e-commerce industry is expanding rapidly. This also means that an increasing proportion of traditional businesses are switching or complementing their business model to electronic commerce." }, { "code": null, "e": 3616, "s": 3380, "text": "In the context of e-commerce industry evolution, Data Science helps to bring maximum value out of the vast amount of data available in such platforms, and helps to switch focus towards customer engagement and experience. It focuses on:" }, { "code": null, "e": 3650, "s": 3616, "text": "Product recommendation for users." }, { "code": null, "e": 3692, "s": 3650, "text": "Analysis of customer trends and behaviors" }, { "code": null, "e": 3731, "s": 3692, "text": "Forecasting sales and stock logistics." }, { "code": null, "e": 3779, "s": 3731, "text": "Optimizing product pricing and payment methods." }, { "code": null, "e": 3928, "s": 3779, "text": "Each of these applications involves storage and interpretation of large amounts of volumes of data, in which data analysis techniques come in handy." }, { "code": null, "e": 4181, "s": 3928, "text": "One example of the application of Data Analytics techniques in case studies are company’s Recommender Systems, which are a means of predicting the preference that users might have towards an item based on previous purchases or searches on the platform." }, { "code": null, "e": 4311, "s": 4181, "text": "Recommender systems are used strategically to increase conversion rates, elevate customer experience and amplify user engagement." }, { "code": null, "e": 4801, "s": 4311, "text": "A large-scale recommender system that has proved to work is Amazon’s data-driven and personalized marketing approach to boosting sales in the platform through intelligent recommendations to users. According to McKinsey Insights magazine, 35% of Amazon’s revenue is generated by its recommendation engine. This achievement has been possible because of the recommendation system’s application in email campaigns and on most of its web site’s pages, both on-site and off-site recommendations." }, { "code": null, "e": 4845, "s": 4801, "text": "There are two types of recommender systems:" }, { "code": null, "e": 5524, "s": 4845, "text": "Content-Based Recommendations: Method that makes recommendations based on attributes or features of the product. For instance, if a product shares attributes with another, in case a user purchased the first, the system should recommend the second as there is a higher probability that the user’s preferences will match the second product.Collaborative Recommendations: This method makes recommendations based on the interactions displayed by multiple users. For instance, if several clients have purchased a certain product with another one, the system should recommend each of the products reciprocally as previous customers purchased both items together on previous occasions." }, { "code": null, "e": 5863, "s": 5524, "text": "Content-Based Recommendations: Method that makes recommendations based on attributes or features of the product. For instance, if a product shares attributes with another, in case a user purchased the first, the system should recommend the second as there is a higher probability that the user’s preferences will match the second product." }, { "code": null, "e": 6204, "s": 5863, "text": "Collaborative Recommendations: This method makes recommendations based on the interactions displayed by multiple users. For instance, if several clients have purchased a certain product with another one, the system should recommend each of the products reciprocally as previous customers purchased both items together on previous occasions." }, { "code": null, "e": 6479, "s": 6204, "text": "Customers are a key factor for any e-commerce company and emphasizing in providing great customer experience and satisfaction to the client should be a primer concern. In order to achieve such a level of service, it’s necessary to get to know the client and its preferences." }, { "code": null, "e": 6884, "s": 6479, "text": "E-commerce platforms have the possibility to track a customer’s activity from the moment he or she enters the site till the time they leave, whether this happens after purchasing or selling some product, or after skimming through the products. Based on this necessity to know the client, every action that it’s taken must be recorded and stored as potential useful data to determine the client’s profile." }, { "code": null, "e": 7008, "s": 6884, "text": "The process of generating actionable insights about the customers from their collected data is known as Customer Analytics." }, { "code": null, "e": 7315, "s": 7008, "text": "Customer Analytics helps to understand the trends and shifts in customer’s behavior in order to modify business strategies, as well as make key business decisions accordingly. It also provides a means to analyze which channels of acquisition and retention of clients are actually working and which are not." }, { "code": null, "e": 7445, "s": 7315, "text": "In order to build a Customer Analytics platforms, e-commerce companies must focus on key features about customers, which include:" }, { "code": null, "e": 8027, "s": 7445, "text": "Customer profiling and segmentation: Customers can be grouped based on their preferences, purchases and browsing patterns, in order to build a personal profile and provide recommendations based on it. In addition, this profiling helps to build target audiences, personalized products and even marketing strategies that work for each group. It also helps to shift focus to most profitable clients to establish better customer relations. Customers can be classified among geographical characteristics, behavior in the platform, demographic features and psychological characteristics." }, { "code": null, "e": 8416, "s": 8027, "text": "Sentiment Analysis: This is the process of determining the emotion behind a set of words or sentences, in order to identify a sentiment expressed by customers for their purchased or sold products, through product reviews or in support tickets. Sentiment classifiers can be either positive, negative or neutral, and help to respond to complaints and improve customer service, among others." }, { "code": null, "e": 8745, "s": 8416, "text": "Churn Analysis: This is the process of analyzing the likelihood of when a customer will purchase a product, based on its activity in the platform, directed towards optimizing existing acquisition and retention strategies. An improvement in the churn rate can highly impact the growth and even the sustainability of the business." }, { "code": null, "e": 9177, "s": 8745, "text": "Lifetime Value Prediction: This is the estimated total revenue that a customer will provide to the business during his or her relationship with the platform. The estimation is made using factors such as early transaction patterns, frequency and volume of transactions, among others.Predicting Lifetime Value Prediction, helps in planning what kind of customers to invest business resources in to extract the most value out of them." }, { "code": null, "e": 9472, "s": 9177, "text": "The first step before analyzing a dataset is to preview the information it contains. To process this information easily we’re going to use Pandas, the Python library for data manipulation and analysis that offers data structures and operations for manipulating numerical tables and time series." }, { "code": null, "e": 9648, "s": 9472, "text": "For those who are not familiar with Python, it is a high-level and general-purpose programming language that emphasizes coding efficiency, readability and re-usage of scripts." }, { "code": null, "e": 9806, "s": 9648, "text": "Both the datasets and the script can be found at my GitHub following this link. Below, I’ll include the necessary code to run the analysis on your computers:" }, { "code": null, "e": 9944, "s": 9806, "text": "# Imports import pandas as pdimport matplotlib.pyplot as pltimport matplotlib.gridspec as gridspecimport seaborn as snsimport numpy as np" }, { "code": null, "e": 10116, "s": 9944, "text": "After proceeding with the imports of the necessary libraries, proceed with the creation of a pandas dataframe that contains the information of the dataset, and explore it:" }, { "code": null, "e": 10206, "s": 10116, "text": "# Read dataset and previewdata = pd.read_csv('e_commerce.csv')# Exploring datadata.info()" }, { "code": null, "e": 10540, "s": 10206, "text": "From the result of the application of the info() method in the “data” variable, we access to the information inside the dataset, which consists of a series of transactions made in an e-commerce platforms, for which we have identified the user ID, purchase product ID and many more descriptive data that will be useful in the process." }, { "code": null, "e": 10843, "s": 10540, "text": "After moving on with the analysis, we proceed with some cleaning of the null features in the dataframe. As we can see with the code below, there are 173.638 null fields for product 2, meaning that the user did not purchase more than one in such cases. Also, there are 383.247 null fields for product 3:" }, { "code": null, "e": 10899, "s": 10843, "text": "# Count null features in the datasetdata.isnull().sum()" }, { "code": null, "e": 11040, "s": 10899, "text": "Now, let’s proceed with the replacement of null features with zero values, as we need to have a clean dataset to perform operations with it:" }, { "code": null, "e": 11140, "s": 11040, "text": "# Replace the null features with 0:data.fillna(0, inplace=True) # Re-check N/A was replaced with 0." }, { "code": null, "e": 11368, "s": 11140, "text": "In the dataframe, we have all the transactions made by customers, which include every transaction each one made. In order to identify users that spend the most in our platform, lets group by user ID and add up the amount spent:" }, { "code": null, "e": 11445, "s": 11368, "text": "# Group by User ID:purchases = data.groupby(['User_ID']).sum().reset_index()" }, { "code": null, "e": 11541, "s": 11445, "text": "Also, we can access to which products each User ID purchased, let’s try with user ID 1.000.001:" }, { "code": null, "e": 11574, "s": 11541, "text": "data[data['User_ID'] == 1000001]" }, { "code": null, "e": 11701, "s": 11574, "text": "After identifying most-spending users, let’s extract the range of ages of these users and the average sale for each age group:" }, { "code": null, "e": 11772, "s": 11701, "text": "purchase_by_age = data.groupby('Age')['Purchase'].mean().reset_index()" }, { "code": null, "e": 11988, "s": 11772, "text": "The group of users whose age ranges from 51–55 is the one that spends the most at the platform, so maybe we should target our marketing campaigns to them. Let’s take a look a the graphical distribution of users age:" }, { "code": null, "e": 12265, "s": 11988, "text": "plt.figure(figsize=(16,4))plt.plot(purchase_by_age.index, purchase_by_age.values, color='purple', marker='*')plt.grid()plt.xlabel('Age Group', fontsize=10)plt.ylabel('Total Purchases in $', fontsize=10)plt.title('Average Sales distributed by age group', fontsize=15)plt.show()" }, { "code": null, "e": 12435, "s": 12265, "text": "On the other hand, it would be interested to find out which age group and gender makes more transactions.These two facts can easily be calculated with few lines of code:" }, { "code": null, "e": 12863, "s": 12435, "text": "# Grouping by gender and ageage_and_gender = data.groupby('Age')['Gender'].count().reset_index()gender = data.groupby('Gender')['Age'].count().reset_index()# Plot distributionplt.figure(figsize=(12,9))plt.pie(age_and_gender['Gender'], labels=age_and_gender['Age'],autopct='%d%%', colors=['cyan', 'steelblue','peru','blue','yellowgreen','salmon','#0040FF'])plt.axis('equal')plt.title(\"Age Distribution\", fontsize='20')plt.show()" }, { "code": null, "e": 13083, "s": 12863, "text": "# Plot gender distributionplt.figure(figsize=(12,9))plt.pie(gender['Age'], labels=gender['Gender'],autopct='%d%%', colors=['salmon','steelblue'])plt.axis('equal')plt.title(\"Gender Distribution\", fontsize='20')plt.show()" }, { "code": null, "e": 13255, "s": 13083, "text": "In addition, we can calculate which occupations of those displayed by the customers of the platform are the ones that purchase more products. Take a look a the code below:" }, { "code": null, "e": 13750, "s": 13255, "text": "# Group by occupation:occupation = data.groupby('Occupation')['Purchase'].mean().reset_index()# Plot bar chart with line plot:sns.set(style=\"white\", rc={\"lines.linewidth\": 3})fig, ax1 = plt.subplots(figsize=(12,9))sns.barplot(x=occupation['Occupation'],y=occupation['Purchase'],color='#004488',ax=ax1)sns.lineplot(x=occupation['Occupation'],y=occupation['Purchase'],color='salmon',marker=\"o\",ax=ax1)plt.axis([-1,21,8000,10000])plt.title('Occupation Bar Chart', fontsize='15')plt.show()sns.set()" }, { "code": null, "e": 13832, "s": 13750, "text": "And lastly, we can determine which are the best-selling products in the platform:" }, { "code": null, "e": 14340, "s": 13832, "text": "# Group by product IDproduct = data.groupby('Product_ID')['Purchase'].count().reset_index()product.rename(columns={'Purchase':'Count'},inplace=True)product_sorted = product.sort_values('Count',ascending=False)# Plot line plotplt.figure(figsize=(14,8))plt.plot(product_sorted['Product_ID'][:10], product_sorted['Count'][:10], linestyle='-', color='purple', marker='o')plt.title(\"Best-selling Products\", fontsize='15')plt.xlabel('Product ID', fontsize='15')plt.ylabel('Products Sold', fontsize='15')plt.show()" }, { "code": null, "e": 14668, "s": 14340, "text": "My aim with this article was to provide an intuition about how global companies apply data science for acquiring, retaining, and growing their customer base. In addition to this, I wanted to provide a practical explanation of theory involved in e-commerce business which includes recommendations systems and customer analytics." }, { "code": null, "e": 14811, "s": 14668, "text": "If you liked the information included in this article don’t hesitate to contact me to share your thoughts. It motivates me to keep on sharing!" }, { "code": null, "e": 14868, "s": 14811, "text": "Neural networks application for Stack Overflow profiles:" }, { "code": null, "e": 14879, "s": 14868, "text": "medium.com" }, { "code": null, "e": 14925, "s": 14879, "text": "Data Analysis for Airbnb rentals in New York:" }, { "code": null, "e": 14948, "s": 14925, "text": "towardsdatascience.com" }, { "code": null, "e": 15020, "s": 14948, "text": "Enhance metrics, KPIs and data interpretation with nice visualizations:" }, { "code": null, "e": 15043, "s": 15020, "text": "towardsdatascience.com" }, { "code": null, "e": 15257, "s": 15043, "text": "Thanks for taking the time to read my article! If you have any questions or ideas to share, please feel free to contact me to my email, or you can find me in the following social networks for more related content:" }, { "code": null, "e": 15267, "s": 15257, "text": "LinkedIn." }, { "code": null, "e": 15275, "s": 15267, "text": "GitHub." }, { "code": null, "e": 15303, "s": 15275, "text": "[1] Python official website" } ]
java.util.zip.ZipOutputStream.setLevel() Method Example
The java.util.zip.ZipOutputStream.setLevel(int level) method sets the compression level for subsequent entries which are DEFLATED. The default setting is DEFAULT_COMPRESSION. Following is the declaration for java.util.zip.ZipOutputStream.setLevel(int level) method. public void setLevel(int level) level − the compression level (0-9). level − the compression level (0-9). IllegalArgumentException − if the compression level is invalid. IllegalArgumentException − if the compression level is invalid. Create a file Hello.txt in D:> test > directory with the following content. This is an example. The following example shows the usage of java.util.zip.ZipOutputStream.setLevel(int level) method. package com.tutorialspoint; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Date; import java.util.zip.Adler32; import java.util.zip.CheckedOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import java.util.zip.Deflater; public class ZipOutputStreamDemo { private static String SOURCE_FILE = "D:\\test\\Hello.txt"; private static String TARGET_FILE = "D:\\test\\Hello.zip"; public static void main(String[] args) { try { createZipFile(); readZipFile(); } catch(IOException ioe) { System.out.println("IOException : " + ioe); } } private static void createZipFile() throws IOException{ FileOutputStream fout = new FileOutputStream(TARGET_FILE); CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32()); ZipOutputStream zout = new ZipOutputStream(checksum); zout.setLevel(Deflater.DEFAULT_COMPRESSION); FileInputStream fin = new FileInputStream(SOURCE_FILE); ZipEntry zipEntry = new ZipEntry(SOURCE_FILE); zout.putNextEntry(zipEntry); int length; byte[] buffer = new byte[1024]; while((length = fin.read(buffer)) > 0) { zout.write(buffer, 0, length); } zout.closeEntry(); zout.finish(); fin.close(); zout.close(); } private static void readZipFile() throws IOException{ ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); ZipEntry entry; while((entry = zin.getNextEntry())!=null){ System.out.printf("File: %s Modified on %TD %n", entry.getName(), new Date(entry.getTime())); extractFile(entry, zin); System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE); zin.closeEntry(); } zin.close(); } private static void extractFile(final ZipEntry entry, ZipInputStream is) throws IOException { FileOutputStream fos = null; try { fos = new FileOutputStream(entry.getName()); while(is.available() != 0){ fos.write(is.read()); } } catch (IOException ioex) { fos.close(); } } } Let us compile and run the above program, this will produce the following result − Zip File: D:\test\Hello.zip, Contains 1 file(s). File: D:\test\Hello.txt Size 1026 Modified on 05/22/17 Zip file D:\test\Hello.txt extracted successfully. Print Add Notes Bookmark this page
[ { "code": null, "e": 2367, "s": 2192, "text": "The java.util.zip.ZipOutputStream.setLevel(int level) method sets the compression level for subsequent entries which are DEFLATED. The default setting is DEFAULT_COMPRESSION." }, { "code": null, "e": 2458, "s": 2367, "text": "Following is the declaration for java.util.zip.ZipOutputStream.setLevel(int level) method." }, { "code": null, "e": 2491, "s": 2458, "text": "public void setLevel(int level)\n" }, { "code": null, "e": 2528, "s": 2491, "text": "level − the compression level (0-9)." }, { "code": null, "e": 2565, "s": 2528, "text": "level − the compression level (0-9)." }, { "code": null, "e": 2630, "s": 2565, "text": "IllegalArgumentException − if the compression level is invalid." }, { "code": null, "e": 2695, "s": 2630, "text": "IllegalArgumentException − if the compression level is invalid." }, { "code": null, "e": 2772, "s": 2695, "text": "Create a file Hello.txt in D:> test > directory with the following content." }, { "code": null, "e": 2793, "s": 2772, "text": "This is an example.\n" }, { "code": null, "e": 2892, "s": 2793, "text": "The following example shows the usage of java.util.zip.ZipOutputStream.setLevel(int level) method." }, { "code": null, "e": 5189, "s": 2892, "text": "package com.tutorialspoint;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.zip.Adler32;\nimport java.util.zip.CheckedOutputStream;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipInputStream;\nimport java.util.zip.ZipOutputStream;\nimport java.util.zip.Deflater;\n\npublic class ZipOutputStreamDemo {\n private static String SOURCE_FILE = \"D:\\\\test\\\\Hello.txt\";\n private static String TARGET_FILE = \"D:\\\\test\\\\Hello.zip\";\n\n public static void main(String[] args) {\n try {\n createZipFile();\n readZipFile();\n } catch(IOException ioe) {\n System.out.println(\"IOException : \" + ioe);\n }\n }\n\n private static void createZipFile() throws IOException{\n FileOutputStream fout = new FileOutputStream(TARGET_FILE);\n CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());\n ZipOutputStream zout = new ZipOutputStream(checksum);\n zout.setLevel(Deflater.DEFAULT_COMPRESSION);\n FileInputStream fin = new FileInputStream(SOURCE_FILE);\n ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);\n zout.putNextEntry(zipEntry);\n int length;\n byte[] buffer = new byte[1024];\n while((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n zout.finish();\n fin.close();\n zout.close();\n }\n\n private static void readZipFile() throws IOException{\n ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); \n\n ZipEntry entry;\n while((entry = zin.getNextEntry())!=null){\n System.out.printf(\"File: %s Modified on %TD %n\", \n entry.getName(), new Date(entry.getTime()));\n extractFile(entry, zin); \n System.out.printf(\"Zip file %s extracted successfully.\", SOURCE_FILE);\n zin.closeEntry();\n }\n zin.close();\n }\n\n private static void extractFile(final ZipEntry entry, ZipInputStream is) \n throws IOException {\n FileOutputStream fos = null; \n try { \n fos = new FileOutputStream(entry.getName()); \n while(is.available() != 0){\n fos.write(is.read()); \n }\n } catch (IOException ioex) { \n fos.close(); \n } \n }\n}" }, { "code": null, "e": 5272, "s": 5189, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 5430, "s": 5272, "text": "Zip File: D:\\test\\Hello.zip, Contains 1 file(s). \nFile: D:\\test\\Hello.txt Size 1026 Modified on 05/22/17 \nZip file D:\\test\\Hello.txt extracted successfully.\n" }, { "code": null, "e": 5437, "s": 5430, "text": " Print" }, { "code": null, "e": 5448, "s": 5437, "text": " Add Notes" } ]
Seaborn - Multi Panel Categorical Plots
Categorical data can we visualized using two plots, you can either use the functions pointplot(), or the higher-level function factorplot(). Factorplot draws a categorical plot on a FacetGrid. Using ‘kind’ parameter we can choose the plot like boxplot, violinplot, barplot and stripplot. FacetGrid uses pointplot by default. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('exercise') sb.factorplot(x = "time", y = pulse", hue = "kind",data = df); plt.show() We can use different plot to visualize the same data using the kind parameter. import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('exercise') sb.factorplot(x = "time", y = "pulse", hue = "kind", kind = 'violin',data = df); plt.show() In factorplot, the data is plotted on a facet grid. Facet grid forms a matrix of panels defined by row and column by dividing the variables. Due of panels, a single plot looks like multiple plots. It is very helpful to analyze all combinations in two discrete variables. Let us visualize the above the definition with an example import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('exercise') sb.factorplot(x = "time", y = "pulse", hue = "kind", kind = 'violin', col = "diet", data = df); plt.show() The advantage of using Facet is, we can input another variable into the plot. The above plot is divided into two plots based on a third variable called ‘diet’ using the ‘col’ parameter. We can make many column facets and align them with the rows of the grid − import pandas as pd import seaborn as sb from matplotlib import pyplot as plt df = sb.load_dataset('titanic') sb.factorplot("alive", col = "deck", col_wrap = 3,data = df[df.deck.notnull()],kind = "count") plt.show() 11 Lectures 4 hours DATAhill Solutions Srinivas Reddy 11 Lectures 2.5 hours DATAhill Solutions Srinivas Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2180, "s": 2039, "text": "Categorical data can we visualized using two plots, you can either use the functions pointplot(), or the higher-level function factorplot()." }, { "code": null, "e": 2364, "s": 2180, "text": "Factorplot draws a categorical plot on a FacetGrid. Using ‘kind’ parameter we can choose the plot like boxplot, violinplot, barplot and stripplot. FacetGrid uses pointplot by default." }, { "code": null, "e": 2550, "s": 2364, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('exercise')\nsb.factorplot(x = \"time\", y = pulse\", hue = \"kind\",data = df);\nplt.show()\n" }, { "code": null, "e": 2629, "s": 2550, "text": "We can use different plot to visualize the same data using the kind parameter." }, { "code": null, "e": 2833, "s": 2629, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('exercise')\nsb.factorplot(x = \"time\", y = \"pulse\", hue = \"kind\", kind = 'violin',data = df);\nplt.show()\n" }, { "code": null, "e": 2885, "s": 2833, "text": "In factorplot, the data is plotted on a facet grid." }, { "code": null, "e": 3104, "s": 2885, "text": "Facet grid forms a matrix of panels defined by row and column by dividing the variables. Due of panels, a single plot looks like multiple plots. It is very helpful to analyze all combinations in two discrete variables." }, { "code": null, "e": 3162, "s": 3104, "text": "Let us visualize the above the definition with an example" }, { "code": null, "e": 3381, "s": 3162, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('exercise')\nsb.factorplot(x = \"time\", y = \"pulse\", hue = \"kind\", kind = 'violin', col = \"diet\", data = df);\nplt.show()\n" }, { "code": null, "e": 3567, "s": 3381, "text": "The advantage of using Facet is, we can input another variable into the plot. The above plot is divided into two plots based on a third variable called ‘diet’ using the ‘col’ parameter." }, { "code": null, "e": 3641, "s": 3567, "text": "We can make many column facets and align them with the rows of the grid −" }, { "code": null, "e": 3858, "s": 3641, "text": "import pandas as pd\nimport seaborn as sb\nfrom matplotlib import pyplot as plt\ndf = sb.load_dataset('titanic')\nsb.factorplot(\"alive\", col = \"deck\", col_wrap = 3,data = df[df.deck.notnull()],kind = \"count\")\nplt.show()\n" }, { "code": null, "e": 3891, "s": 3858, "text": "\n 11 Lectures \n 4 hours \n" }, { "code": null, "e": 3926, "s": 3891, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 3961, "s": 3926, "text": "\n 11 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3996, "s": 3961, "text": " DATAhill Solutions Srinivas Reddy" }, { "code": null, "e": 4003, "s": 3996, "text": " Print" }, { "code": null, "e": 4014, "s": 4003, "text": " Add Notes" } ]
How to Add a Floating Action Button to Bottom Navigation Bar in Android? - GeeksforGeeks
19 Feb, 2021 The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app’s UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. Bottom navigation bars allow movement between primary destinations in an app. Some popular examples include Instagram, WhatsApp, etc. In this article, we will learn how to add a Floating Action Button (FAB) in the middle of the Bottom Navigation bar in android. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Step 2: Add dependency to the build.gradle file Inside build.gradle(app) add Material Design Dependency. implementation ‘com.google.android.material:material:1.3.0-alpha03’ After adding the material design dependency click on the Sync now. Step 3: Change the theme of the app to Material Components Below is the code for the styles.xml file. XML <resources> <!-- Base application theme. --> <style name="Theme.Fab_Bottom_app_bar" parent="Theme.MaterialComponents.DayNight.NoActionBar"> <item name="colorPrimary">#0F9D58</item> <item name="colorPrimaryVariant">#0F9D58</item> <item name="colorOnPrimary">#000</item> </style> </resources> Step 4: Import Icons from Vector assets Go to res > drawable (right-click) > new -> vector assets and import five icons from there namely Home, Search, Person, Add, Settings. And your project structure should look like this after this step. Step 5: Create menu items that have to be shown in the bottom navigation view Go to res (right-click) > New > Android resource file and in the pop-up menu choose the resource type to menu and name the file bottom_nav_menu. It should look like this. Inside bottom_nav_menu.xml add items that we want to show in the bottom app bar. Below is the code for the bottom_nav_menu.xml file. XML <?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/home" android:icon="@drawable/ic_baseline_home_24" android:title="Home" /> <item android:id="@+id/Search" android:icon="@drawable/ic_baseline_search_24" android:title="Search" /> <item android:id="@+id/placeholder" android:title="" /> <item android:id="@+id/Profile" android:icon="@drawable/ic_baseline_person_24" android:title="Profile" /> <item android:id="@+id/Settings" android:icon="@drawable/ic_baseline_settings_24" android:title="Settings" /> </menu> Step 6: Working with the AndroidManifest.xml file Change the theme inside the AndroidManifest.xml file. Below is the code for the AndroidManifest.xml file. XML <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.floatingactionbuttontobottomnavigation"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.Fab_Bottom_app_bar"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Step 7: Working with the activity_main.xml file Change the root layout to Coordinator Layout Add Bottom App bar. Inside the Bottom app, the bar adds the bottom Navigation View and adds the menu items that we created in the last step. Add the Floating action button. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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.google.android.material.bottomappbar.BottomAppBar android:id="@+id/bottomAppBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:fabCradleMargin="10dp" app:fabCradleRoundedCornerRadius="10dp" app:fabCradleVerticalOffset="10dp"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id="@+id/bottomNavigationView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginEnd="16dp" android:background="@android:color/transparent" app:menu="@menu/bottom_nav_menu" /> </com.google.android.material.bottomappbar.BottomAppBar> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:contentDescription="@string/app_name" android:src="@drawable/ic_baseline_add_24" app:layout_anchor="@id/bottomAppBar" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Step 8: Working with the MainActivity.kt file Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Kotlin import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) bottomNavigationView.background = null bottomNavigationView.menu.getItem(2).isEnabled = false }} Android-Button Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android GridView in Android with Example How to Change the Background Color After Clicking the Button in Android? Android Listview in Java with Example Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android MVP (Model View Presenter) Architecture Pattern in Android with Example
[ { "code": null, "e": 25142, "s": 25114, "text": "\n19 Feb, 2021" }, { "code": null, "e": 25911, "s": 25142, "text": "The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app’s UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. Bottom navigation bars allow movement between primary destinations in an app. Some popular examples include Instagram, WhatsApp, etc. In this article, we will learn how to add a Floating Action Button (FAB) in the middle of the Bottom Navigation bar in android. A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. " }, { "code": null, "e": 25940, "s": 25911, "text": "Step 1: Create a New Project" }, { "code": null, "e": 26104, "s": 25940, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 26152, "s": 26104, "text": "Step 2: Add dependency to the build.gradle file" }, { "code": null, "e": 26209, "s": 26152, "text": "Inside build.gradle(app) add Material Design Dependency." }, { "code": null, "e": 26277, "s": 26209, "text": "implementation ‘com.google.android.material:material:1.3.0-alpha03’" }, { "code": null, "e": 26344, "s": 26277, "text": "After adding the material design dependency click on the Sync now." }, { "code": null, "e": 26403, "s": 26344, "text": "Step 3: Change the theme of the app to Material Components" }, { "code": null, "e": 26446, "s": 26403, "text": "Below is the code for the styles.xml file." }, { "code": null, "e": 26450, "s": 26446, "text": "XML" }, { "code": "<resources> <!-- Base application theme. --> <style name=\"Theme.Fab_Bottom_app_bar\" parent=\"Theme.MaterialComponents.DayNight.NoActionBar\"> <item name=\"colorPrimary\">#0F9D58</item> <item name=\"colorPrimaryVariant\">#0F9D58</item> <item name=\"colorOnPrimary\">#000</item> </style> </resources>", "e": 26778, "s": 26450, "text": null }, { "code": null, "e": 26818, "s": 26778, "text": "Step 4: Import Icons from Vector assets" }, { "code": null, "e": 27019, "s": 26818, "text": "Go to res > drawable (right-click) > new -> vector assets and import five icons from there namely Home, Search, Person, Add, Settings. And your project structure should look like this after this step." }, { "code": null, "e": 27097, "s": 27019, "text": "Step 5: Create menu items that have to be shown in the bottom navigation view" }, { "code": null, "e": 27268, "s": 27097, "text": "Go to res (right-click) > New > Android resource file and in the pop-up menu choose the resource type to menu and name the file bottom_nav_menu. It should look like this." }, { "code": null, "e": 27401, "s": 27268, "text": "Inside bottom_nav_menu.xml add items that we want to show in the bottom app bar. Below is the code for the bottom_nav_menu.xml file." }, { "code": null, "e": 27405, "s": 27401, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><menu xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:id=\"@+id/home\" android:icon=\"@drawable/ic_baseline_home_24\" android:title=\"Home\" /> <item android:id=\"@+id/Search\" android:icon=\"@drawable/ic_baseline_search_24\" android:title=\"Search\" /> <item android:id=\"@+id/placeholder\" android:title=\"\" /> <item android:id=\"@+id/Profile\" android:icon=\"@drawable/ic_baseline_person_24\" android:title=\"Profile\" /> <item android:id=\"@+id/Settings\" android:icon=\"@drawable/ic_baseline_settings_24\" android:title=\"Settings\" /> </menu>", "e": 28119, "s": 27405, "text": null }, { "code": null, "e": 28169, "s": 28119, "text": "Step 6: Working with the AndroidManifest.xml file" }, { "code": null, "e": 28275, "s": 28169, "text": "Change the theme inside the AndroidManifest.xml file. Below is the code for the AndroidManifest.xml file." }, { "code": null, "e": 28279, "s": 28275, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.floatingactionbuttontobottomnavigation\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/Theme.Fab_Bottom_app_bar\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 29046, "s": 28279, "text": null }, { "code": null, "e": 29094, "s": 29046, "text": "Step 7: Working with the activity_main.xml file" }, { "code": null, "e": 29139, "s": 29094, "text": "Change the root layout to Coordinator Layout" }, { "code": null, "e": 29159, "s": 29139, "text": "Add Bottom App bar." }, { "code": null, "e": 29280, "s": 29159, "text": "Inside the Bottom app, the bar adds the bottom Navigation View and adds the menu items that we created in the last step." }, { "code": null, "e": 29312, "s": 29280, "text": "Add the Floating action button." }, { "code": null, "e": 29362, "s": 29312, "text": "Below is the code for the activity_main.xml file." }, { "code": null, "e": 29366, "s": 29362, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout 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.google.android.material.bottomappbar.BottomAppBar android:id=\"@+id/bottomAppBar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_gravity=\"bottom\" app:fabCradleMargin=\"10dp\" app:fabCradleRoundedCornerRadius=\"10dp\" app:fabCradleVerticalOffset=\"10dp\"> <com.google.android.material.bottomnavigation.BottomNavigationView android:id=\"@+id/bottomNavigationView\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_marginEnd=\"16dp\" android:background=\"@android:color/transparent\" app:menu=\"@menu/bottom_nav_menu\" /> </com.google.android.material.bottomappbar.BottomAppBar> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id=\"@+id/fab\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:contentDescription=\"@string/app_name\" android:src=\"@drawable/ic_baseline_add_24\" app:layout_anchor=\"@id/bottomAppBar\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 30916, "s": 29366, "text": null }, { "code": null, "e": 30962, "s": 30916, "text": "Step 8: Working with the MainActivity.kt file" }, { "code": null, "e": 31074, "s": 30962, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file." }, { "code": null, "e": 31081, "s": 31074, "text": "Kotlin" }, { "code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) bottomNavigationView.background = null bottomNavigationView.menu.getItem(2).isEnabled = false }}", "e": 31510, "s": 31081, "text": null }, { "code": null, "e": 31525, "s": 31510, "text": "Android-Button" }, { "code": null, "e": 31533, "s": 31525, "text": "Android" }, { "code": null, "e": 31540, "s": 31533, "text": "Kotlin" }, { "code": null, "e": 31548, "s": 31540, "text": "Android" }, { "code": null, "e": 31646, "s": 31548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31655, "s": 31646, "text": "Comments" }, { "code": null, "e": 31668, "s": 31655, "text": "Old Comments" }, { "code": null, "e": 31707, "s": 31668, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 31749, "s": 31707, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 31782, "s": 31749, "text": "GridView in Android with Example" }, { "code": null, "e": 31855, "s": 31782, "text": "How to Change the Background Color After Clicking the Button in Android?" }, { "code": null, "e": 31893, "s": 31855, "text": "Android Listview in Java with Example" }, { "code": null, "e": 31912, "s": 31893, "text": "Android UI Layouts" }, { "code": null, "e": 31925, "s": 31912, "text": "Kotlin Array" }, { "code": null, "e": 31967, "s": 31925, "text": "Retrofit with Kotlin Coroutine in Android" } ]
Simple SVD algorithms. Naive ways to calculate SVD | by Risto Hinno | Towards Data Science
Aim of this post is to show some simple and educational examples how to calculate singular value decomposition using simple methods. If you are interested in industry strength implementations, you might find this useful. Singular value decomposition (SVD) is a matrix factorization method that generalizes the eigendecomposition of a square matrix (n x n) to any matrix (n x m) (source). If you don’t know what is eigendecomposition or eigenvectors/eigenvalues, you should google it or read this post. This post assumes that you are familiar with these concepts. SVD is similar to Principal Component Analysis (PCA), but more general. PCA assumes that input square matrix, SVD doesn’t have this assumption. General formula of SVD is: M=UΣVt, where: M-is original matrix we want to decompose U-is left singular matrix (columns are left singular vectors). U columns contain eigenvectors of matrix MMt Σ-is a diagonal matrix containing singular (eigen)values V-is right singular matrix (columns are right singular vectors). V columns contain eigenvectors of matrix MtM SVD is more general than PCA. From the previous picture we see that SVD can handle matrices with different number of columns and rows. SVD is similar to PCA. PCA formula is M=QΛQt, which decomposes matrix into orthogonal matrix Q and diagonal matrix Λ. Simply this could be interpreted as: change of the basis from standard basis to basis Q (using Qt) applying transformation matrix Λ which changes length not direction as this is diagonal matrix change of the basis from basis Q to standard basis (using Q) SVD does similar things, but it doesn’t return to same basis from which we started transformations. It could not do it because our original matrix M isn’t square matrix. Following picture shows change of basis and transformations related to SVD. From the graph we see that SVD does following steps: change of the basis from standard basis to basis V (using Vt). Note that in graph this is shown as simple rotation apply transformation described by matrix Σ. This scales our vector in basis V change of the basis from V to basis U. Because our original matrix M isn’t square, matrix U can’t have same dimensions as V and we can’t return to our original standard basis (see picture “SVD matrices”) There are numerous variants of SVD and ways to calculate SVD. I’ll show just a few of the ways to calculate it. If you want to try coding examples yourself use this notebook which has all the examples used in this post. Power iteration starts with b0 which might be a random vector. At every iteration this vector is updated using following rule: First we multiply b0 with original matrix A (Abk) and divide result with the norm (||Abk||). We’ll continue until result has converged (updates are less than threshold). Power method has few assumptions: b0 has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue. Initializing b0 randomly minimizes possibility that this assumption is not fulfilled matrix A has dominant eigenvalue which has strictly greater magnitude than other eigenvalues (source). These assumptions guarantee that algorithm converges to a reasonable result. The smaller is difference between dominant eigenvalue and second eigenvalue, the longer it might take to converge. Very simple example of power method could be found here. I’ve made example which also finds eigenvalue. As you can see core of this function is power iteration. For a simple example we use beer dataset (which is available from here). We’ll construct covariance matrix and try to determine dominant singular value of the dataset. Full example with data processing is available in the notebook. #construct data df=pd.read_csv('data/beer_dataset.csv')X = np.array([df['Temperatura Maxima (C)'], df['Consumo de cerveja (litros)']]).TC = np.cov(X, rowvar=False)eigen_value, eigen_vec = svd_power_iteration(C) We can plot dominant eigenvector with original data. As we can see from the plot, this method really found dominant singular value/eigenvector. It looks like it is working. You can use notebook to see that results are very close to results from svd implementation provided by numpy . Next we’ll see how to get more than just first dominant singular values. To get more than just most dominant singular value from matrix, we could still use power iteration. We’ll implement new function which uses our previous svd_power_iteration function. Finding first dominant singular value is easy. We could use previously mentioned function. But how to find second singular value? We should remove dominant direction from the matrix and repeat finding most dominant singular value (source). To do that we could subtract previous eigenvector(s) component(s) from the original matrix (using singular values and left and right singular vectors we have already calculated): A_next = A-(singular_value1)(u1)(v1)t Here is example code (borrowed it from here, made minor modifications) for calculating multiple eigenvalues/eigenvectors. When we apply to our beer dataset we get two eigenvalues and eigenvectors. Note that this example works also with matrices which have more columns than rows or more rows than columns. Results are comparable to numpy svd implementation. Here is one example: mat = np.array([[1,2,3], [4,5,6]])u, s, v = np.linalg.svd(mat, full_matrices=False)values, left_s, rigth_s = svd(mat)np.allclose(np.absolute(u), np.absolute(left_s))#Truenp.allclose(np.absolute(s), np.absolute(values))#Truenp.allclose(np.absolute(v), np.absolute(rigth_s))#True To compare our custom solution results with numpy svd implementation we take absolute values because signs in he matrices might be opposite. It means that vectors point opposite directions but are still on the same line and thus are still eigenvectors. Now that we have found a way to calculate multiple singular values/singular vectors, we might ask could we do it more efficiently? This version has also names like simultaneous power iteration or orthogonal iteration. Idea behind this version is pretty straightforward (source): other eigenvectors are orthogonal to the dominant one we can use the power method, and force that the second vector is orthogonal to the first one algorithm converges to two different eigenvectors do this for many vectors, not just two of them Each step we multiply A not just by just one vector, but by multiple vectors which we put in a matrix Q. At each step we’ll normalize the vectors using QR Decomposition. QR Decomposition decomposes matrix into following components: A=QR, where A-original matrix we want to decompose Q-orthogonal matrix R-upper triangular matrix If algorithm converges then Q will be eigenvectors and R eigenvalues. Here is example code: From the code we could see that calculating singular vectors and values is small part of the code. Much of the code is dedicated to dealing with different shaped matrices. If we apply this function to beer dataset we should get similar results as we did with previous approach. Eigenvectors point opposite directions compared to previous version, but they are on the same (with some small error) line and thus are the same eigenvectors. In the notebook I have examples which compares output with numpy svd implementation. To calculate dominant singular value and singular vector we could start from power iteration method. This method could be adjusted for calculating n-dominant singular values and vectors. For simultaneous singular value decomposition we could use block version of Power Iteration. These methods are not fastest and most stabile methods but are great sources for learning. Beer Consumption — Sao Paulo, Kaggle Eigenvalues and Eigenvectors, Risto Hinno How to Compute the SVD Power Iteration, ML Wiki Power Iteration, Wikipedia QR decomposition, Wikipedia Singular value decomposition, Wikipedia Singular Value Decomposition Part 2: Theorem, Proof, Algorithm, Jeremy Kun
[ { "code": null, "e": 393, "s": 172, "text": "Aim of this post is to show some simple and educational examples how to calculate singular value decomposition using simple methods. If you are interested in industry strength implementations, you might find this useful." }, { "code": null, "e": 560, "s": 393, "text": "Singular value decomposition (SVD) is a matrix factorization method that generalizes the eigendecomposition of a square matrix (n x n) to any matrix (n x m) (source)." }, { "code": null, "e": 735, "s": 560, "text": "If you don’t know what is eigendecomposition or eigenvectors/eigenvalues, you should google it or read this post. This post assumes that you are familiar with these concepts." }, { "code": null, "e": 906, "s": 735, "text": "SVD is similar to Principal Component Analysis (PCA), but more general. PCA assumes that input square matrix, SVD doesn’t have this assumption. General formula of SVD is:" }, { "code": null, "e": 921, "s": 906, "text": "M=UΣVt, where:" }, { "code": null, "e": 963, "s": 921, "text": "M-is original matrix we want to decompose" }, { "code": null, "e": 1071, "s": 963, "text": "U-is left singular matrix (columns are left singular vectors). U columns contain eigenvectors of matrix MMt" }, { "code": null, "e": 1128, "s": 1071, "text": "Σ-is a diagonal matrix containing singular (eigen)values" }, { "code": null, "e": 1238, "s": 1128, "text": "V-is right singular matrix (columns are right singular vectors). V columns contain eigenvectors of matrix MtM" }, { "code": null, "e": 1528, "s": 1238, "text": "SVD is more general than PCA. From the previous picture we see that SVD can handle matrices with different number of columns and rows. SVD is similar to PCA. PCA formula is M=QΛQt, which decomposes matrix into orthogonal matrix Q and diagonal matrix Λ. Simply this could be interpreted as:" }, { "code": null, "e": 1590, "s": 1528, "text": "change of the basis from standard basis to basis Q (using Qt)" }, { "code": null, "e": 1685, "s": 1590, "text": "applying transformation matrix Λ which changes length not direction as this is diagonal matrix" }, { "code": null, "e": 1746, "s": 1685, "text": "change of the basis from basis Q to standard basis (using Q)" }, { "code": null, "e": 1992, "s": 1746, "text": "SVD does similar things, but it doesn’t return to same basis from which we started transformations. It could not do it because our original matrix M isn’t square matrix. Following picture shows change of basis and transformations related to SVD." }, { "code": null, "e": 2045, "s": 1992, "text": "From the graph we see that SVD does following steps:" }, { "code": null, "e": 2160, "s": 2045, "text": "change of the basis from standard basis to basis V (using Vt). Note that in graph this is shown as simple rotation" }, { "code": null, "e": 2238, "s": 2160, "text": "apply transformation described by matrix Σ. This scales our vector in basis V" }, { "code": null, "e": 2442, "s": 2238, "text": "change of the basis from V to basis U. Because our original matrix M isn’t square, matrix U can’t have same dimensions as V and we can’t return to our original standard basis (see picture “SVD matrices”)" }, { "code": null, "e": 2554, "s": 2442, "text": "There are numerous variants of SVD and ways to calculate SVD. I’ll show just a few of the ways to calculate it." }, { "code": null, "e": 2662, "s": 2554, "text": "If you want to try coding examples yourself use this notebook which has all the examples used in this post." }, { "code": null, "e": 2789, "s": 2662, "text": "Power iteration starts with b0 which might be a random vector. At every iteration this vector is updated using following rule:" }, { "code": null, "e": 2959, "s": 2789, "text": "First we multiply b0 with original matrix A (Abk) and divide result with the norm (||Abk||). We’ll continue until result has converged (updates are less than threshold)." }, { "code": null, "e": 2993, "s": 2959, "text": "Power method has few assumptions:" }, { "code": null, "e": 3181, "s": 2993, "text": "b0 has a nonzero component in the direction of an eigenvector associated with the dominant eigenvalue. Initializing b0 randomly minimizes possibility that this assumption is not fulfilled" }, { "code": null, "e": 3284, "s": 3181, "text": "matrix A has dominant eigenvalue which has strictly greater magnitude than other eigenvalues (source)." }, { "code": null, "e": 3476, "s": 3284, "text": "These assumptions guarantee that algorithm converges to a reasonable result. The smaller is difference between dominant eigenvalue and second eigenvalue, the longer it might take to converge." }, { "code": null, "e": 3637, "s": 3476, "text": "Very simple example of power method could be found here. I’ve made example which also finds eigenvalue. As you can see core of this function is power iteration." }, { "code": null, "e": 3869, "s": 3637, "text": "For a simple example we use beer dataset (which is available from here). We’ll construct covariance matrix and try to determine dominant singular value of the dataset. Full example with data processing is available in the notebook." }, { "code": null, "e": 4093, "s": 3869, "text": "#construct data df=pd.read_csv('data/beer_dataset.csv')X = np.array([df['Temperatura Maxima (C)'], df['Consumo de cerveja (litros)']]).TC = np.cov(X, rowvar=False)eigen_value, eigen_vec = svd_power_iteration(C)" }, { "code": null, "e": 4146, "s": 4093, "text": "We can plot dominant eigenvector with original data." }, { "code": null, "e": 4450, "s": 4146, "text": "As we can see from the plot, this method really found dominant singular value/eigenvector. It looks like it is working. You can use notebook to see that results are very close to results from svd implementation provided by numpy . Next we’ll see how to get more than just first dominant singular values." }, { "code": null, "e": 4763, "s": 4450, "text": "To get more than just most dominant singular value from matrix, we could still use power iteration. We’ll implement new function which uses our previous svd_power_iteration function. Finding first dominant singular value is easy. We could use previously mentioned function. But how to find second singular value?" }, { "code": null, "e": 5052, "s": 4763, "text": "We should remove dominant direction from the matrix and repeat finding most dominant singular value (source). To do that we could subtract previous eigenvector(s) component(s) from the original matrix (using singular values and left and right singular vectors we have already calculated):" }, { "code": null, "e": 5090, "s": 5052, "text": "A_next = A-(singular_value1)(u1)(v1)t" }, { "code": null, "e": 5212, "s": 5090, "text": "Here is example code (borrowed it from here, made minor modifications) for calculating multiple eigenvalues/eigenvectors." }, { "code": null, "e": 5287, "s": 5212, "text": "When we apply to our beer dataset we get two eigenvalues and eigenvectors." }, { "code": null, "e": 5469, "s": 5287, "text": "Note that this example works also with matrices which have more columns than rows or more rows than columns. Results are comparable to numpy svd implementation. Here is one example:" }, { "code": null, "e": 5762, "s": 5469, "text": "mat = np.array([[1,2,3], [4,5,6]])u, s, v = np.linalg.svd(mat, full_matrices=False)values, left_s, rigth_s = svd(mat)np.allclose(np.absolute(u), np.absolute(left_s))#Truenp.allclose(np.absolute(s), np.absolute(values))#Truenp.allclose(np.absolute(v), np.absolute(rigth_s))#True" }, { "code": null, "e": 6015, "s": 5762, "text": "To compare our custom solution results with numpy svd implementation we take absolute values because signs in he matrices might be opposite. It means that vectors point opposite directions but are still on the same line and thus are still eigenvectors." }, { "code": null, "e": 6146, "s": 6015, "text": "Now that we have found a way to calculate multiple singular values/singular vectors, we might ask could we do it more efficiently?" }, { "code": null, "e": 6294, "s": 6146, "text": "This version has also names like simultaneous power iteration or orthogonal iteration. Idea behind this version is pretty straightforward (source):" }, { "code": null, "e": 6348, "s": 6294, "text": "other eigenvectors are orthogonal to the dominant one" }, { "code": null, "e": 6441, "s": 6348, "text": "we can use the power method, and force that the second vector is orthogonal to the first one" }, { "code": null, "e": 6491, "s": 6441, "text": "algorithm converges to two different eigenvectors" }, { "code": null, "e": 6538, "s": 6491, "text": "do this for many vectors, not just two of them" }, { "code": null, "e": 6770, "s": 6538, "text": "Each step we multiply A not just by just one vector, but by multiple vectors which we put in a matrix Q. At each step we’ll normalize the vectors using QR Decomposition. QR Decomposition decomposes matrix into following components:" }, { "code": null, "e": 6782, "s": 6770, "text": "A=QR, where" }, { "code": null, "e": 6821, "s": 6782, "text": "A-original matrix we want to decompose" }, { "code": null, "e": 6841, "s": 6821, "text": "Q-orthogonal matrix" }, { "code": null, "e": 6867, "s": 6841, "text": "R-upper triangular matrix" }, { "code": null, "e": 6959, "s": 6867, "text": "If algorithm converges then Q will be eigenvectors and R eigenvalues. Here is example code:" }, { "code": null, "e": 7131, "s": 6959, "text": "From the code we could see that calculating singular vectors and values is small part of the code. Much of the code is dedicated to dealing with different shaped matrices." }, { "code": null, "e": 7237, "s": 7131, "text": "If we apply this function to beer dataset we should get similar results as we did with previous approach." }, { "code": null, "e": 7481, "s": 7237, "text": "Eigenvectors point opposite directions compared to previous version, but they are on the same (with some small error) line and thus are the same eigenvectors. In the notebook I have examples which compares output with numpy svd implementation." }, { "code": null, "e": 7852, "s": 7481, "text": "To calculate dominant singular value and singular vector we could start from power iteration method. This method could be adjusted for calculating n-dominant singular values and vectors. For simultaneous singular value decomposition we could use block version of Power Iteration. These methods are not fastest and most stabile methods but are great sources for learning." }, { "code": null, "e": 7889, "s": 7852, "text": "Beer Consumption — Sao Paulo, Kaggle" }, { "code": null, "e": 7931, "s": 7889, "text": "Eigenvalues and Eigenvectors, Risto Hinno" }, { "code": null, "e": 7954, "s": 7931, "text": "How to Compute the SVD" }, { "code": null, "e": 7979, "s": 7954, "text": "Power Iteration, ML Wiki" }, { "code": null, "e": 8006, "s": 7979, "text": "Power Iteration, Wikipedia" }, { "code": null, "e": 8034, "s": 8006, "text": "QR decomposition, Wikipedia" }, { "code": null, "e": 8074, "s": 8034, "text": "Singular value decomposition, Wikipedia" } ]
How to make an Android device vibrate?
In android, using vibrate service, we can vibrate android mobile. This example demonstrate about how to make an Android device vibrate Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/parent" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:gravity="center" android:background="#33FFFF00" android:orientation="vertical"> <TextView android:id="@+id/text" android:textSize="18sp" android:text="Click here to vibrate" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> In the above code, we have taken textview, when you click on textview. it will vibrate. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.VibrationEffect; import android.os.Vibrator; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); final LinearLayout parent = findViewById(R.id.parent); textView = findViewById(R.id.text); textView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)); } else { vibrator.vibrate(500); } } }); } } In the above code, we have taken vibrate service, it is system service as shown below - Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE)); } else { vibrator.vibrate(500); } In the above code we have given 500ms so it going to vibrate 500ms continuously. Step 4 − Add the following code to manifest.java <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.andy.myapplication"> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> In the above code we have given vibrate user permission, without permission it can't vibrate. Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − In the above result, when you click on text view. it will vibrate for 500ms. Click here to download the project code
[ { "code": null, "e": 1197, "s": 1062, "text": "In android, using vibrate service, we can vibrate android mobile. This example demonstrate about how to make an Android device vibrate" }, { "code": null, "e": 1326, "s": 1197, "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": 1391, "s": 1326, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2009, "s": 1391, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/parent\"\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 android:gravity=\"center\"\n android:background=\"#33FFFF00\"\n android:orientation=\"vertical\">\n <TextView\n android:id=\"@+id/text\"\n android:textSize=\"18sp\"\n android:text=\"Click here to vibrate\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 2097, "s": 2009, "text": "In the above code, we have taken textview, when you click on textview. it will vibrate." }, { "code": null, "e": 2154, "s": 2097, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3380, "s": 2154, "text": "package com.example.andy.myapplication;\n\nimport android.content.Context;\nimport android.content.Intent;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.os.VibrationEffect;\nimport android.os.Vibrator;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.LinearLayout;\nimport android.widget.TextView;\nimport android.widget.Toast;\n\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n final LinearLayout parent = findViewById(R.id.parent);\n textView = findViewById(R.id.text);\n textView.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));\n } else {\n vibrator.vibrate(500);\n }\n }\n });\n }\n}" }, { "code": null, "e": 3468, "s": 3380, "text": "In the above code, we have taken vibrate service, it is system service as shown below -" }, { "code": null, "e": 3726, "s": 3468, "text": "Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);\nif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {\n vibrator.vibrate(VibrationEffect.createOneShot(500, VibrationEffect.DEFAULT_AMPLITUDE));\n} else {\n vibrator.vibrate(500);\n}" }, { "code": null, "e": 3807, "s": 3726, "text": "In the above code we have given 500ms so it going to vibrate 500ms continuously." }, { "code": null, "e": 3856, "s": 3807, "text": "Step 4 − Add the following code to manifest.java" }, { "code": null, "e": 4665, "s": 3856, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.andy.myapplication\">\n <uses-permission android:name=\"android.permission.VIBRATE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity\n android:name=\".MainActivity\"\n android:screenOrientation=\"portrait\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4759, "s": 4665, "text": "In the above code we have given vibrate user permission, without permission it can't vibrate." }, { "code": null, "e": 5108, "s": 4759, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5185, "s": 5108, "text": "In the above result, when you click on text view. it will vibrate for 500ms." }, { "code": null, "e": 5225, "s": 5185, "text": "Click here to download the project code" } ]
How to convert binary variable to 0/1 format in an R data frame?
A binary variable is a type of variable that can take only two possible values like gender that has two categories male and female, citizenship of a country with two categories as yes and no, etc. If the binary variable is not in 0/1 format then it can be converted with the help of ifelse function. Check out the below examples to understand how it works. Consider the below data frame − Live Demo Temp<-sample(c("Hot","Cold"),20,replace=TRUE) Response<-rnorm(20,25,3.2) df1<-data.frame(Temp,Response) df1 Temp Response 1 Cold 26.02542 2 Cold 22.39046 3 Hot 24.84536 4 Cold 25.64836 5 Hot 28.29392 6 Cold 27.58198 7 Hot 23.77825 8 Cold 30.17105 9 Cold 27.08661 10 Cold 36.36730 11 Hot 24.73742 12 Cold 23.43371 13 Hot 23.72180 14 Cold 19.81232 15 Hot 24.45042 16 Cold 30.39320 17 Cold 21.23361 18 Hot 25.21617 19 Cold 23.20461 20 Cold 25.22150 Converting Temp column of df1 to 0/1 format − df1$Temp<-ifelse(df1$Temp=="Cold",1,0) df1 Temp Response 1 1 26.02542 2 1 22.39046 3 0 24.84536 4 1 25.64836 5 0 28.29392 6 1 27.58198 7 0 23.77825 8 1 30.17105 9 1 27.08661 10 1 36.36730 11 0 24.73742 12 1 23.43371 13 0 23.72180 14 1 19.81232 15 0 24.45042 16 1 30.39320 17 1 21.23361 18 0 25.21617 19 1 23.20461 20 1 25.22150
[ { "code": null, "e": 1419, "s": 1062, "text": "A binary variable is a type of variable that can take only two possible values like gender that has two categories male and female, citizenship of a country with two categories as yes and no, etc. If the binary variable is not in 0/1 format then it can be converted with the help of ifelse function. Check out the below examples to understand how it works." }, { "code": null, "e": 1451, "s": 1419, "text": "Consider the below data frame −" }, { "code": null, "e": 1462, "s": 1451, "text": " Live Demo" }, { "code": null, "e": 1570, "s": 1462, "text": "Temp<-sample(c(\"Hot\",\"Cold\"),20,replace=TRUE)\nResponse<-rnorm(20,25,3.2)\ndf1<-data.frame(Temp,Response)\ndf1" }, { "code": null, "e": 1968, "s": 1570, "text": " Temp Response\n1 Cold 26.02542\n2 Cold 22.39046\n3 Hot 24.84536\n4 Cold 25.64836\n5 Hot 28.29392\n6 Cold 27.58198\n7 Hot 23.77825\n8 Cold 30.17105\n9 Cold 27.08661\n10 Cold 36.36730\n11 Hot 24.73742\n12 Cold 23.43371\n13 Hot 23.72180\n14 Cold 19.81232\n15 Hot 24.45042\n16 Cold 30.39320\n17 Cold 21.23361\n18 Hot 25.21617\n19 Cold 23.20461\n20 Cold 25.22150" }, { "code": null, "e": 2014, "s": 1968, "text": "Converting Temp column of df1 to 0/1 format −" }, { "code": null, "e": 2057, "s": 2014, "text": "df1$Temp<-ifelse(df1$Temp==\"Cold\",1,0)\ndf1" }, { "code": null, "e": 2414, "s": 2057, "text": " Temp Response\n1 1 26.02542\n2 1 22.39046\n3 0 24.84536\n4 1 25.64836\n5 0 28.29392\n6 1 27.58198\n7 0 23.77825\n8 1 30.17105\n9 1 27.08661\n10 1 36.36730\n11 0 24.73742\n12 1 23.43371\n13 0 23.72180\n14 1 19.81232\n15 0 24.45042\n16 1 30.39320\n17 1 21.23361\n18 0 25.21617\n19 1 23.20461\n20 1 25.22150" } ]
Display scientific notation as float in Python - GeeksforGeeks
30 Jun, 2021 In this article, the task is to display the scientific notation as float in Python. The scientific notation means any number expressed in the power of 10.for example- 340 can be written in scientific notation as 3.4 X102.in pythons, we use str.format() on a number with “{:e}” to format the number to scientific notation. str.format() formats the number as a float, followed by “e+” and the appropriate power of 10. For example- 340 will be displayed as 3.4e+2 Example: -51000000000.0000000 in scientific notation results in “5.10e+10”,where the no. after “e+”denotes power of 10-5189 in scientific notation results in “5.189e+3”-439929 in scientific notation results in “4.39929e+5” Python3 # codescientific_format = "{:e}".format(512349000.000000) print(scientific_format) Output: 5.123490e+08 In the above example, the scientific notation of 512349000.000000 will be a decimal after the first digit and the power of 10 ie- 5.123490 X 108 To only include a certain number of digits after the decimal point, we use “{:.Ne}”, where N is the number of digits. Python3 # code# code# after decimal point,only 3 digit will be displayedprint("{:.3e}".format(345000)) Output: 3.450e+05 To display reverse of scientific numbers to float We have to pass a variable holding the scientific format of a number, as follows: Python3 # codex = 3.234e+4 print("{:f}".format(x)) # f represents float Output: 32340.000000 pradiptamukherjee Picked Python-string-functions Technical Scripter 2020 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n30 Jun, 2021" }, { "code": null, "e": 25998, "s": 25537, "text": "In this article, the task is to display the scientific notation as float in Python. The scientific notation means any number expressed in the power of 10.for example- 340 can be written in scientific notation as 3.4 X102.in pythons, we use str.format() on a number with “{:e}” to format the number to scientific notation. str.format() formats the number as a float, followed by “e+” and the appropriate power of 10. For example- 340 will be displayed as 3.4e+2" }, { "code": null, "e": 26007, "s": 25998, "text": "Example:" }, { "code": null, "e": 26226, "s": 26007, "text": "-51000000000.0000000 in scientific notation results in “5.10e+10”,where the no. after “e+”denotes power of 10-5189 in scientific notation results in “5.189e+3”-439929 in scientific notation results in “4.39929e+5”" }, { "code": null, "e": 26234, "s": 26226, "text": "Python3" }, { "code": "# codescientific_format = \"{:e}\".format(512349000.000000) print(scientific_format)", "e": 26317, "s": 26234, "text": null }, { "code": null, "e": 26325, "s": 26317, "text": "Output:" }, { "code": null, "e": 26338, "s": 26325, "text": "5.123490e+08" }, { "code": null, "e": 26483, "s": 26338, "text": "In the above example, the scientific notation of 512349000.000000 will be a decimal after the first digit and the power of 10 ie- 5.123490 X 108" }, { "code": null, "e": 26601, "s": 26483, "text": "To only include a certain number of digits after the decimal point, we use “{:.Ne}”, where N is the number of digits." }, { "code": null, "e": 26609, "s": 26601, "text": "Python3" }, { "code": "# code# code# after decimal point,only 3 digit will be displayedprint(\"{:.3e}\".format(345000))", "e": 26704, "s": 26609, "text": null }, { "code": null, "e": 26712, "s": 26704, "text": "Output:" }, { "code": null, "e": 26722, "s": 26712, "text": "3.450e+05" }, { "code": null, "e": 26772, "s": 26722, "text": "To display reverse of scientific numbers to float" }, { "code": null, "e": 26854, "s": 26772, "text": "We have to pass a variable holding the scientific format of a number, as follows:" }, { "code": null, "e": 26862, "s": 26854, "text": "Python3" }, { "code": "# codex = 3.234e+4 print(\"{:f}\".format(x)) # f represents float", "e": 26927, "s": 26862, "text": null }, { "code": null, "e": 26935, "s": 26927, "text": "Output:" }, { "code": null, "e": 26948, "s": 26935, "text": "32340.000000" }, { "code": null, "e": 26966, "s": 26948, "text": "pradiptamukherjee" }, { "code": null, "e": 26973, "s": 26966, "text": "Picked" }, { "code": null, "e": 26997, "s": 26973, "text": "Python-string-functions" }, { "code": null, "e": 27021, "s": 26997, "text": "Technical Scripter 2020" }, { "code": null, "e": 27028, "s": 27021, "text": "Python" }, { "code": null, "e": 27047, "s": 27028, "text": "Technical Scripter" }, { "code": null, "e": 27145, "s": 27047, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27177, "s": 27145, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27219, "s": 27177, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27261, "s": 27219, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27288, "s": 27261, "text": "Python Classes and Objects" }, { "code": null, "e": 27344, "s": 27288, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27383, "s": 27344, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27405, "s": 27383, "text": "Defaultdict in Python" }, { "code": null, "e": 27436, "s": 27405, "text": "Python | os.path.join() method" }, { "code": null, "e": 27465, "s": 27436, "text": "Create a directory in Python" } ]
How to implement 'add tag' functionality in an Angular 9 app ? - GeeksforGeeks
26 Jun, 2020 Angular makes it very easy to implement almost every functionality. In this article, we will learn how to implement add tag functionality in your angular app. Adding tags have applications in several areas like music apps, online shopping apps, etc. By using this functionality we can filter the results of a search, according to to the need of the user. Approach: Angular material library provides mat-chip, which can be used to implement this functionality. We can use it inside a form field to take input from user and update our tags list. Once user has finished adding tags we can save the tag list. Now we have our tag list, we can use it any way that we want. Step by step implementation: For the component class: Import MatChipInputEvent from @angular/material/chips to handle the tags input event. Import COMMA, ENTER from @angular/cdk/keycodes to add the separator keys. Create a list which will contain all the tags entered by user. Create your custom add and remove method to add and remove tags. Code for the component: import {Component} from '@angular/core';import {COMMA, ENTER} from '@angular/cdk/keycodes';import {MatChipInputEvent} from '@angular/material/chips'; @Component({ selector: 'add-tags', templateUrl: 'tags.html', styleUrls: ['tags.css'],})export class addTags { /*Set the values of these properties to use them in the HTML view.*/ visible = true; selectable = true; removable = true; /*set the separator keys.*/ readonly separatorKeysCodes: number[] = [ENTER, COMMA]; /*create the tags list.*/ Tags: string[] = []; /*our custom add method which will take matChipInputTokenEnd event as input.*/ add(event: MatChipInputEvent): void { /*we will store the input and value in local variables.*/ const input = event.input; const value = event.value; if ((value || '').trim()) { /*the input string will be pushed to the tag list.*/ this.Tags.push(value); } if (input) { /*after storing the input we will clear the input field.*/ input.value = ''; } } /*custom method to remove a tag.*/ remove(tag: string): void { const index = this.Tags.indexOf(tag); if (index >= 0) { /*the tag of a particular index is removed from the tag list.*/ this.Tags.splice(index, 1); } }} For the HTML view: Create a form field which will take input and display the list of tags. There are some parameters:1.matChipInputFor: it takes the id of form field, from which we will take the input of tags.2.matChipInputSeparatorKeyCodes: It takes the value of keys which will be used as separator.3.matChipInputTokenEnd: As soon as user press separator key, this will contain the last entered tag, and we can update the tag list by our custom add method. To remove a particular tag, add a mat-icon with matChipRemove directive. Code for the HTML view: <!DOCTYPE html><html> <head> <title>tutorial</title> </head> <body> <mat-form-field class="input"> <!--this contains the list of tags--> <mat-chip-list #taglist> <!--set the properties for the tags--> <mat-chip selected color="primary" *ngFor="let Tag of Tags" [selectable]="selectable" [removable]="removable" (removed)="remove(Tag)"> {{Tag}} <!--add icon with matChipRemove directive to remove any tag--> <mat-icon matChipRemove *ngIf="removable">cancel </mat-icon> </mat-chip> <input placeholder="Add Tags" [matChipInputFor]="taglist" [matChipInputSeparatorKeyCodes]="separatorKeysCodes" (matChipInputTokenEnd)="add($event)" /> </mat-chip-list> </mat-form-field> </body></html> Now in the main component include this ‘add-tags’ component. import {Component} from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style="align-items: center;"> <app-test></app-test> </div> `, styleUrls: ['main.css'],}) export class AppComponent { } We have successfully implemented add tags functionality. Output: Mat-chips over the form field represents the tags entered by the user. AngularJS-Misc AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Auth Guards in Angular 9/10/11 Angular PrimeNG Calendar Component What is AOT and JIT Compiler in Angular ? How to bundle an Angular app for production? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 26172, "s": 26144, "text": "\n26 Jun, 2020" }, { "code": null, "e": 26528, "s": 26172, "text": "Angular makes it very easy to implement almost every functionality. In this article, we will learn how to implement add tag functionality in your angular app. Adding tags have applications in several areas like music apps, online shopping apps, etc. By using this functionality we can filter the results of a search, according to to the need of the user." }, { "code": null, "e": 26538, "s": 26528, "text": "Approach:" }, { "code": null, "e": 26633, "s": 26538, "text": "Angular material library provides mat-chip, which can be used to implement this functionality." }, { "code": null, "e": 26717, "s": 26633, "text": "We can use it inside a form field to take input from user and update our tags list." }, { "code": null, "e": 26778, "s": 26717, "text": "Once user has finished adding tags we can save the tag list." }, { "code": null, "e": 26840, "s": 26778, "text": "Now we have our tag list, we can use it any way that we want." }, { "code": null, "e": 26869, "s": 26840, "text": "Step by step implementation:" }, { "code": null, "e": 26894, "s": 26869, "text": "For the component class:" }, { "code": null, "e": 26980, "s": 26894, "text": "Import MatChipInputEvent from @angular/material/chips to handle the tags input event." }, { "code": null, "e": 27054, "s": 26980, "text": "Import COMMA, ENTER from @angular/cdk/keycodes to add the separator keys." }, { "code": null, "e": 27117, "s": 27054, "text": "Create a list which will contain all the tags entered by user." }, { "code": null, "e": 27182, "s": 27117, "text": "Create your custom add and remove method to add and remove tags." }, { "code": null, "e": 27206, "s": 27182, "text": "Code for the component:" }, { "code": "import {Component} from '@angular/core';import {COMMA, ENTER} from '@angular/cdk/keycodes';import {MatChipInputEvent} from '@angular/material/chips'; @Component({ selector: 'add-tags', templateUrl: 'tags.html', styleUrls: ['tags.css'],})export class addTags { /*Set the values of these properties to use them in the HTML view.*/ visible = true; selectable = true; removable = true; /*set the separator keys.*/ readonly separatorKeysCodes: number[] = [ENTER, COMMA]; /*create the tags list.*/ Tags: string[] = []; /*our custom add method which will take matChipInputTokenEnd event as input.*/ add(event: MatChipInputEvent): void { /*we will store the input and value in local variables.*/ const input = event.input; const value = event.value; if ((value || '').trim()) { /*the input string will be pushed to the tag list.*/ this.Tags.push(value); } if (input) { /*after storing the input we will clear the input field.*/ input.value = ''; } } /*custom method to remove a tag.*/ remove(tag: string): void { const index = this.Tags.indexOf(tag); if (index >= 0) { /*the tag of a particular index is removed from the tag list.*/ this.Tags.splice(index, 1); } }}", "e": 28470, "s": 27206, "text": null }, { "code": null, "e": 28489, "s": 28470, "text": "For the HTML view:" }, { "code": null, "e": 28561, "s": 28489, "text": "Create a form field which will take input and display the list of tags." }, { "code": null, "e": 28929, "s": 28561, "text": "There are some parameters:1.matChipInputFor: it takes the id of form field, from which we will take the input of tags.2.matChipInputSeparatorKeyCodes: It takes the value of keys which will be used as separator.3.matChipInputTokenEnd: As soon as user press separator key, this will contain the last entered tag, and we can update the tag list by our custom add method." }, { "code": null, "e": 29002, "s": 28929, "text": "To remove a particular tag, add a mat-icon with matChipRemove directive." }, { "code": null, "e": 29026, "s": 29002, "text": "Code for the HTML view:" }, { "code": "<!DOCTYPE html><html> <head> <title>tutorial</title> </head> <body> <mat-form-field class=\"input\"> <!--this contains the list of tags--> <mat-chip-list #taglist> <!--set the properties for the tags--> <mat-chip selected color=\"primary\" *ngFor=\"let Tag of Tags\" [selectable]=\"selectable\" [removable]=\"removable\" (removed)=\"remove(Tag)\"> {{Tag}} <!--add icon with matChipRemove directive to remove any tag--> <mat-icon matChipRemove *ngIf=\"removable\">cancel </mat-icon> </mat-chip> <input placeholder=\"Add Tags\" [matChipInputFor]=\"taglist\" [matChipInputSeparatorKeyCodes]=\"separatorKeysCodes\" (matChipInputTokenEnd)=\"add($event)\" /> </mat-chip-list> </mat-form-field> </body></html>", "e": 30131, "s": 29026, "text": null }, { "code": null, "e": 30192, "s": 30131, "text": "Now in the main component include this ‘add-tags’ component." }, { "code": "import {Component} from '@angular/core'; @Component({ selector: 'app-root', template: ` <div style=\"align-items: center;\"> <app-test></app-test> </div> `, styleUrls: ['main.css'],}) export class AppComponent { }", "e": 30414, "s": 30192, "text": null }, { "code": null, "e": 30471, "s": 30414, "text": "We have successfully implemented add tags functionality." }, { "code": null, "e": 30550, "s": 30471, "text": "Output: Mat-chips over the form field represents the tags entered by the user." }, { "code": null, "e": 30565, "s": 30550, "text": "AngularJS-Misc" }, { "code": null, "e": 30575, "s": 30565, "text": "AngularJS" }, { "code": null, "e": 30592, "s": 30575, "text": "Web Technologies" }, { "code": null, "e": 30690, "s": 30592, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30725, "s": 30690, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 30756, "s": 30725, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 30791, "s": 30756, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 30833, "s": 30791, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 30878, "s": 30833, "text": "How to bundle an Angular app for production?" }, { "code": null, "e": 30918, "s": 30878, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30951, "s": 30918, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30996, "s": 30951, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31039, "s": 30996, "text": "How to fetch data from an API in ReactJS ?" } ]